blob: 812c66faf0339daee62bbe8c49169d2fd02f4f4d [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
35 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
36 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
37 {0}
38};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000039
Guido van Rossumc0b618a1997-05-02 03:12:38 +000040static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000041type_name(PyTypeObject *type, void *context)
42{
43 char *s;
44
45 s = strrchr(type->tp_name, '.');
46 if (s == NULL)
47 s = type->tp_name;
48 else
49 s++;
50 return PyString_FromString(s);
51}
52
53static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000054type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000055{
Guido van Rossumc3542212001-08-16 09:18:56 +000056 PyObject *mod;
57 char *s;
58
59 s = strrchr(type->tp_name, '.');
60 if (s != NULL)
61 return PyString_FromStringAndSize(type->tp_name,
62 (int)(s - type->tp_name));
63 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
64 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000065 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000066 if (mod != NULL && PyString_Check(mod)) {
67 Py_INCREF(mod);
68 return mod;
69 }
70 PyErr_SetString(PyExc_AttributeError, "__module__");
71 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000072}
73
Guido van Rossum3926a632001-09-25 16:25:58 +000074static int
75type_set_module(PyTypeObject *type, PyObject *value, void *context)
76{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000077 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000078 strrchr(type->tp_name, '.')) {
79 PyErr_Format(PyExc_TypeError,
80 "can't set %s.__module__", type->tp_name);
81 return -1;
82 }
83 if (!value) {
84 PyErr_Format(PyExc_TypeError,
85 "can't delete %s.__module__", type->tp_name);
86 return -1;
87 }
88 return PyDict_SetItemString(type->tp_dict, "__module__", value);
89}
90
Tim Peters6d6c1a32001-08-02 04:15:00 +000091static PyObject *
92type_dict(PyTypeObject *type, void *context)
93{
94 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095 Py_INCREF(Py_None);
96 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000098 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000099}
100
Tim Peters24008312002-03-17 18:56:20 +0000101static PyObject *
102type_get_doc(PyTypeObject *type, void *context)
103{
104 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000106 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000107 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000108 if (result == NULL) {
109 result = Py_None;
110 Py_INCREF(result);
111 }
112 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000113 result = result->ob_type->tp_descr_get(result, NULL,
114 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000115 }
116 else {
117 Py_INCREF(result);
118 }
Tim Peters24008312002-03-17 18:56:20 +0000119 return result;
120}
121
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000122static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000123 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000125 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000126 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000127 {0}
128};
129
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000130static int
131type_compare(PyObject *v, PyObject *w)
132{
133 /* This is called with type objects only. So we
134 can just compare the addresses. */
135 Py_uintptr_t vv = (Py_uintptr_t)v;
136 Py_uintptr_t ww = (Py_uintptr_t)w;
137 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
138}
139
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000140static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000141type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000143 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000144 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000145
146 mod = type_module(type, NULL);
147 if (mod == NULL)
148 PyErr_Clear();
149 else if (!PyString_Check(mod)) {
150 Py_DECREF(mod);
151 mod = NULL;
152 }
153 name = type_name(type, NULL);
154 if (name == NULL)
155 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000156
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000157 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
158 kind = "class";
159 else
160 kind = "type";
161
Barry Warsaw7ce36942001-08-24 18:34:26 +0000162 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000163 rtn = PyString_FromFormat("<%s '%s.%s'>",
164 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000165 PyString_AS_STRING(mod),
166 PyString_AS_STRING(name));
167 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000168 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000169 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000170
Guido van Rossumc3542212001-08-16 09:18:56 +0000171 Py_XDECREF(mod);
172 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000173 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Tim Peters6d6c1a32001-08-02 04:15:00 +0000176static PyObject *
177type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
178{
179 PyObject *obj;
180
181 if (type->tp_new == NULL) {
182 PyErr_Format(PyExc_TypeError,
183 "cannot create '%.100s' instances",
184 type->tp_name);
185 return NULL;
186 }
187
Tim Peters3f996e72001-09-13 19:18:27 +0000188 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000189 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000190 /* Ugly exception: when the call was type(something),
191 don't call tp_init on the result. */
192 if (type == &PyType_Type &&
193 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
194 (kwds == NULL ||
195 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
196 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000197 /* If the returned object is not an instance of type,
198 it won't be initialized. */
199 if (!PyType_IsSubtype(obj->ob_type, type))
200 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000202 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
203 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000204 type->tp_init(obj, args, kwds) < 0) {
205 Py_DECREF(obj);
206 obj = NULL;
207 }
208 }
209 return obj;
210}
211
212PyObject *
213PyType_GenericAlloc(PyTypeObject *type, int nitems)
214{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000216 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000217
218 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000219 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000220 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000221 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000222
Neil Schemenauerc806c882001-08-29 23:54:54 +0000223 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000224 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000225
Neil Schemenauerc806c882001-08-29 23:54:54 +0000226 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000227
Tim Peters6d6c1a32001-08-02 04:15:00 +0000228 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
229 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000230
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231 if (type->tp_itemsize == 0)
232 PyObject_INIT(obj, type);
233 else
234 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000235
Tim Peters6d6c1a32001-08-02 04:15:00 +0000236 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000237 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000238 return obj;
239}
240
241PyObject *
242PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
243{
244 return type->tp_alloc(type, 0);
245}
246
Guido van Rossum9475a232001-10-05 20:51:39 +0000247/* Helpers for subtyping */
248
249static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000250traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
251{
252 int i, n;
253 PyMemberDef *mp;
254
255 n = type->ob_size;
256 mp = ((etype *)type)->members;
257 for (i = 0; i < n; i++, mp++) {
258 if (mp->type == T_OBJECT_EX) {
259 char *addr = (char *)self + mp->offset;
260 PyObject *obj = *(PyObject **)addr;
261 if (obj != NULL) {
262 int err = visit(obj, arg);
263 if (err)
264 return err;
265 }
266 }
267 }
268 return 0;
269}
270
271static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000272subtype_traverse(PyObject *self, visitproc visit, void *arg)
273{
274 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000275 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000276
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000277 /* Find the nearest base with a different tp_traverse,
278 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000279 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000280 base = type;
281 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
282 if (base->ob_size) {
283 int err = traverse_slots(base, self, visit, arg);
284 if (err)
285 return err;
286 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000287 base = base->tp_base;
288 assert(base);
289 }
290
291 if (type->tp_dictoffset != base->tp_dictoffset) {
292 PyObject **dictptr = _PyObject_GetDictPtr(self);
293 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000294 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000295 if (err)
296 return err;
297 }
298 }
299
Guido van Rossuma3862092002-06-10 15:24:42 +0000300 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
301 /* For a heaptype, the instances count as references
302 to the type. Traverse the type so the collector
303 can find cycles involving this link. */
304 int err = visit((PyObject *)type, arg);
305 if (err)
306 return err;
307 }
308
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000309 if (basetraverse)
310 return basetraverse(self, visit, arg);
311 return 0;
312}
313
314static void
315clear_slots(PyTypeObject *type, PyObject *self)
316{
317 int i, n;
318 PyMemberDef *mp;
319
320 n = type->ob_size;
321 mp = ((etype *)type)->members;
322 for (i = 0; i < n; i++, mp++) {
323 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
324 char *addr = (char *)self + mp->offset;
325 PyObject *obj = *(PyObject **)addr;
326 if (obj != NULL) {
327 Py_DECREF(obj);
328 *(PyObject **)addr = NULL;
329 }
330 }
331 }
332}
333
334static int
335subtype_clear(PyObject *self)
336{
337 PyTypeObject *type, *base;
338 inquiry baseclear;
339
340 /* Find the nearest base with a different tp_clear
341 and clear slots while we're at it */
342 type = self->ob_type;
343 base = type;
344 while ((baseclear = base->tp_clear) == subtype_clear) {
345 if (base->ob_size)
346 clear_slots(base, self);
347 base = base->tp_base;
348 assert(base);
349 }
350
Guido van Rossuma3862092002-06-10 15:24:42 +0000351 /* There's no need to clear the instance dict (if any);
352 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000353
354 if (baseclear)
355 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000356 return 0;
357}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000358
359static void
360subtype_dealloc(PyObject *self)
361{
Guido van Rossum14227b42001-12-06 02:35:58 +0000362 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000363 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000364
Guido van Rossum22b13872002-08-06 21:41:44 +0000365 /* Extract the type; we expect it to be a heap type */
366 type = self->ob_type;
367 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368
Guido van Rossum22b13872002-08-06 21:41:44 +0000369 /* Test whether the type has GC exactly once */
370
371 if (!PyType_IS_GC(type)) {
372 /* It's really rare to find a dynamic type that doesn't have
373 GC; it can only happen when deriving from 'object' and not
374 adding any slots or instance variables. This allows
375 certain simplifications: there's no need to call
376 clear_slots(), or DECREF the dict, or clear weakrefs. */
377
378 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000379 if (type->tp_del) {
380 type->tp_del(self);
381 if (self->ob_refcnt > 0)
382 return;
383 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000384
385 /* Find the nearest base with a different tp_dealloc */
386 base = type;
387 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
388 assert(base->ob_size == 0);
389 base = base->tp_base;
390 assert(base);
391 }
392
393 /* Call the base tp_dealloc() */
394 assert(basedealloc);
395 basedealloc(self);
396
397 /* Can't reference self beyond this point */
398 Py_DECREF(type);
399
400 /* Done */
401 return;
402 }
403
404 /* We get here only if the type has GC */
405
406 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000407 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000408 Py_TRASHCAN_SAFE_BEGIN(self);
409 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
410
411 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000412 if (type->tp_del) {
413 type->tp_del(self);
414 if (self->ob_refcnt > 0)
415 goto endlabel;
416 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000417
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000418 /* Find the nearest base with a different tp_dealloc
419 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000420 base = type;
421 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
422 if (base->ob_size)
423 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 base = base->tp_base;
425 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000426 }
427
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000429 if (type->tp_dictoffset && !base->tp_dictoffset) {
430 PyObject **dictptr = _PyObject_GetDictPtr(self);
431 if (dictptr != NULL) {
432 PyObject *dict = *dictptr;
433 if (dict != NULL) {
434 Py_DECREF(dict);
435 *dictptr = NULL;
436 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 }
438 }
439
Guido van Rossum9676b222001-08-17 20:32:36 +0000440 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000441 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000442 PyObject_ClearWeakRefs(self);
443
Tim Peters6d6c1a32001-08-02 04:15:00 +0000444 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000445 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000446 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447
448 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000449 assert(basedealloc);
450 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451
452 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000453 Py_DECREF(type);
454
Guido van Rossum0906e072002-08-07 20:42:09 +0000455 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000456 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000457}
458
Jeremy Hylton938ace62002-07-17 16:30:39 +0000459static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461/* type test with subclassing support */
462
463int
464PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
465{
466 PyObject *mro;
467
Guido van Rossum9478d072001-09-07 18:52:13 +0000468 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
469 return b == a || b == &PyBaseObject_Type;
470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 mro = a->tp_mro;
472 if (mro != NULL) {
473 /* Deal with multiple inheritance without recursion
474 by walking the MRO tuple */
475 int i, n;
476 assert(PyTuple_Check(mro));
477 n = PyTuple_GET_SIZE(mro);
478 for (i = 0; i < n; i++) {
479 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
480 return 1;
481 }
482 return 0;
483 }
484 else {
485 /* a is not completely initilized yet; follow tp_base */
486 do {
487 if (a == b)
488 return 1;
489 a = a->tp_base;
490 } while (a != NULL);
491 return b == &PyBaseObject_Type;
492 }
493}
494
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000495/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000496 without looking in the instance dictionary
497 (so we can't use PyObject_GetAttr) but still binding
498 it to the instance. The arguments are the object,
499 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000500 static variable used to cache the interned Python string.
501
502 Two variants:
503
504 - lookup_maybe() returns NULL without raising an exception
505 when the _PyType_Lookup() call fails;
506
507 - lookup_method() always raises an exception upon errors.
508*/
Guido van Rossum60718732001-08-28 17:47:51 +0000509
510static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000511lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000512{
513 PyObject *res;
514
515 if (*attrobj == NULL) {
516 *attrobj = PyString_InternFromString(attrstr);
517 if (*attrobj == NULL)
518 return NULL;
519 }
520 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000521 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000522 descrgetfunc f;
523 if ((f = res->ob_type->tp_descr_get) == NULL)
524 Py_INCREF(res);
525 else
526 res = f(res, self, (PyObject *)(self->ob_type));
527 }
528 return res;
529}
530
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000531static PyObject *
532lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
533{
534 PyObject *res = lookup_maybe(self, attrstr, attrobj);
535 if (res == NULL && !PyErr_Occurred())
536 PyErr_SetObject(PyExc_AttributeError, *attrobj);
537 return res;
538}
539
Guido van Rossum2730b132001-08-28 18:22:14 +0000540/* A variation of PyObject_CallMethod that uses lookup_method()
541 instead of PyObject_GetAttrString(). This uses the same convention
542 as lookup_method to cache the interned name string object. */
543
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000544static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000545call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
546{
547 va_list va;
548 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000549 va_start(va, format);
550
Guido van Rossumda21c012001-10-03 00:50:18 +0000551 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000552 if (func == NULL) {
553 va_end(va);
554 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000555 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000556 return NULL;
557 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000558
559 if (format && *format)
560 args = Py_VaBuildValue(format, va);
561 else
562 args = PyTuple_New(0);
563
564 va_end(va);
565
566 if (args == NULL)
567 return NULL;
568
569 assert(PyTuple_Check(args));
570 retval = PyObject_Call(func, args, NULL);
571
572 Py_DECREF(args);
573 Py_DECREF(func);
574
575 return retval;
576}
577
578/* Clone of call_method() that returns NotImplemented when the lookup fails. */
579
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000580static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000581call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
582{
583 va_list va;
584 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000585 va_start(va, format);
586
Guido van Rossumda21c012001-10-03 00:50:18 +0000587 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000588 if (func == NULL) {
589 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000590 if (!PyErr_Occurred()) {
591 Py_INCREF(Py_NotImplemented);
592 return Py_NotImplemented;
593 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000594 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000595 }
596
597 if (format && *format)
598 args = Py_VaBuildValue(format, va);
599 else
600 args = PyTuple_New(0);
601
602 va_end(va);
603
Guido van Rossum717ce002001-09-14 16:58:08 +0000604 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000605 return NULL;
606
Guido van Rossum717ce002001-09-14 16:58:08 +0000607 assert(PyTuple_Check(args));
608 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000609
610 Py_DECREF(args);
611 Py_DECREF(func);
612
613 return retval;
614}
615
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616/* Method resolution order algorithm from "Putting Metaclasses to Work"
617 by Forman and Danforth (Addison-Wesley 1999). */
618
619static int
620conservative_merge(PyObject *left, PyObject *right)
621{
622 int left_size;
623 int right_size;
624 int i, j, r, ok;
625 PyObject *temp, *rr;
626
627 assert(PyList_Check(left));
628 assert(PyList_Check(right));
629
630 again:
631 left_size = PyList_GET_SIZE(left);
632 right_size = PyList_GET_SIZE(right);
633 for (i = 0; i < left_size; i++) {
634 for (j = 0; j < right_size; j++) {
635 if (PyList_GET_ITEM(left, i) ==
636 PyList_GET_ITEM(right, j)) {
637 /* found a merge point */
638 temp = PyList_New(0);
639 if (temp == NULL)
640 return -1;
641 for (r = 0; r < j; r++) {
642 rr = PyList_GET_ITEM(right, r);
643 ok = PySequence_Contains(left, rr);
644 if (ok < 0) {
645 Py_DECREF(temp);
646 return -1;
647 }
648 if (!ok) {
649 ok = PyList_Append(temp, rr);
650 if (ok < 0) {
651 Py_DECREF(temp);
652 return -1;
653 }
654 }
655 }
656 ok = PyList_SetSlice(left, i, i, temp);
657 Py_DECREF(temp);
658 if (ok < 0)
659 return -1;
660 ok = PyList_SetSlice(right, 0, j+1, NULL);
661 if (ok < 0)
662 return -1;
663 goto again;
664 }
665 }
666 }
667 return PyList_SetSlice(left, left_size, left_size, right);
668}
669
670static int
671serious_order_disagreements(PyObject *left, PyObject *right)
672{
673 return 0; /* XXX later -- for now, we cheat: "don't do that" */
674}
675
Tim Petersa91e9642001-11-14 23:32:33 +0000676static int
677fill_classic_mro(PyObject *mro, PyObject *cls)
678{
679 PyObject *bases, *base;
680 int i, n;
681
682 assert(PyList_Check(mro));
683 assert(PyClass_Check(cls));
684 i = PySequence_Contains(mro, cls);
685 if (i < 0)
686 return -1;
687 if (!i) {
688 if (PyList_Append(mro, cls) < 0)
689 return -1;
690 }
691 bases = ((PyClassObject *)cls)->cl_bases;
692 assert(bases && PyTuple_Check(bases));
693 n = PyTuple_GET_SIZE(bases);
694 for (i = 0; i < n; i++) {
695 base = PyTuple_GET_ITEM(bases, i);
696 if (fill_classic_mro(mro, base) < 0)
697 return -1;
698 }
699 return 0;
700}
701
702static PyObject *
703classic_mro(PyObject *cls)
704{
705 PyObject *mro;
706
707 assert(PyClass_Check(cls));
708 mro = PyList_New(0);
709 if (mro != NULL) {
710 if (fill_classic_mro(mro, cls) == 0)
711 return mro;
712 Py_DECREF(mro);
713 }
714 return NULL;
715}
716
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717static PyObject *
718mro_implementation(PyTypeObject *type)
719{
720 int i, n, ok;
721 PyObject *bases, *result;
722
Guido van Rossum63517572002-06-18 16:44:57 +0000723 if(type->tp_dict == NULL) {
724 if(PyType_Ready(type) < 0)
725 return NULL;
726 }
727
Tim Peters6d6c1a32001-08-02 04:15:00 +0000728 bases = type->tp_bases;
729 n = PyTuple_GET_SIZE(bases);
730 result = Py_BuildValue("[O]", (PyObject *)type);
731 if (result == NULL)
732 return NULL;
733 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000734 PyObject *base = PyTuple_GET_ITEM(bases, i);
735 PyObject *parentMRO;
736 if (PyType_Check(base))
737 parentMRO = PySequence_List(
738 ((PyTypeObject*)base)->tp_mro);
739 else
740 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 if (parentMRO == NULL) {
742 Py_DECREF(result);
743 return NULL;
744 }
745 if (serious_order_disagreements(result, parentMRO)) {
746 Py_DECREF(result);
747 return NULL;
748 }
749 ok = conservative_merge(result, parentMRO);
750 Py_DECREF(parentMRO);
751 if (ok < 0) {
752 Py_DECREF(result);
753 return NULL;
754 }
755 }
756 return result;
757}
758
759static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000760mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761{
762 PyTypeObject *type = (PyTypeObject *)self;
763
Tim Peters6d6c1a32001-08-02 04:15:00 +0000764 return mro_implementation(type);
765}
766
767static int
768mro_internal(PyTypeObject *type)
769{
770 PyObject *mro, *result, *tuple;
771
772 if (type->ob_type == &PyType_Type) {
773 result = mro_implementation(type);
774 }
775 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000776 static PyObject *mro_str;
777 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 if (mro == NULL)
779 return -1;
780 result = PyObject_CallObject(mro, NULL);
781 Py_DECREF(mro);
782 }
783 if (result == NULL)
784 return -1;
785 tuple = PySequence_Tuple(result);
786 Py_DECREF(result);
787 type->tp_mro = tuple;
788 return 0;
789}
790
791
792/* Calculate the best base amongst multiple base classes.
793 This is the first one that's on the path to the "solid base". */
794
795static PyTypeObject *
796best_base(PyObject *bases)
797{
798 int i, n;
799 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000800 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000801
802 assert(PyTuple_Check(bases));
803 n = PyTuple_GET_SIZE(bases);
804 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000805 base = NULL;
806 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000808 base_proto = PyTuple_GET_ITEM(bases, i);
809 if (PyClass_Check(base_proto))
810 continue;
811 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812 PyErr_SetString(
813 PyExc_TypeError,
814 "bases must be types");
815 return NULL;
816 }
Tim Petersa91e9642001-11-14 23:32:33 +0000817 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000819 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820 return NULL;
821 }
822 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000823 if (winner == NULL) {
824 winner = candidate;
825 base = base_i;
826 }
827 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828 ;
829 else if (PyType_IsSubtype(candidate, winner)) {
830 winner = candidate;
831 base = base_i;
832 }
833 else {
834 PyErr_SetString(
835 PyExc_TypeError,
836 "multiple bases have "
837 "instance lay-out conflict");
838 return NULL;
839 }
840 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000841 if (base == NULL)
842 PyErr_SetString(PyExc_TypeError,
843 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844 return base;
845}
846
847static int
848extra_ivars(PyTypeObject *type, PyTypeObject *base)
849{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000850 size_t t_size = type->tp_basicsize;
851 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
Guido van Rossum9676b222001-08-17 20:32:36 +0000853 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854 if (type->tp_itemsize || base->tp_itemsize) {
855 /* If itemsize is involved, stricter rules */
856 return t_size != b_size ||
857 type->tp_itemsize != base->tp_itemsize;
858 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000859 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
860 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
861 t_size -= sizeof(PyObject *);
862 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
863 type->tp_dictoffset + sizeof(PyObject *) == t_size)
864 t_size -= sizeof(PyObject *);
865
866 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867}
868
869static PyTypeObject *
870solid_base(PyTypeObject *type)
871{
872 PyTypeObject *base;
873
874 if (type->tp_base)
875 base = solid_base(type->tp_base);
876 else
877 base = &PyBaseObject_Type;
878 if (extra_ivars(type, base))
879 return type;
880 else
881 return base;
882}
883
Jeremy Hylton938ace62002-07-17 16:30:39 +0000884static void object_dealloc(PyObject *);
885static int object_init(PyObject *, PyObject *, PyObject *);
886static int update_slot(PyTypeObject *, PyObject *);
887static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000888
889static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000890subtype_dict(PyObject *obj, void *context)
891{
892 PyObject **dictptr = _PyObject_GetDictPtr(obj);
893 PyObject *dict;
894
895 if (dictptr == NULL) {
896 PyErr_SetString(PyExc_AttributeError,
897 "This object has no __dict__");
898 return NULL;
899 }
900 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000901 if (dict == NULL)
902 *dictptr = dict = PyDict_New();
903 Py_XINCREF(dict);
904 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000905}
906
Guido van Rossum6661be32001-10-26 04:26:12 +0000907static int
908subtype_setdict(PyObject *obj, PyObject *value, void *context)
909{
910 PyObject **dictptr = _PyObject_GetDictPtr(obj);
911 PyObject *dict;
912
913 if (dictptr == NULL) {
914 PyErr_SetString(PyExc_AttributeError,
915 "This object has no __dict__");
916 return -1;
917 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000918 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000919 PyErr_SetString(PyExc_TypeError,
920 "__dict__ must be set to a dictionary");
921 return -1;
922 }
923 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000924 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000925 *dictptr = value;
926 Py_XDECREF(dict);
927 return 0;
928}
929
Guido van Rossumad47da02002-08-12 19:05:44 +0000930static PyObject *
931subtype_getweakref(PyObject *obj, void *context)
932{
933 PyObject **weaklistptr;
934 PyObject *result;
935
936 if (obj->ob_type->tp_weaklistoffset == 0) {
937 PyErr_SetString(PyExc_AttributeError,
938 "This object has no __weaklist__");
939 return NULL;
940 }
941 assert(obj->ob_type->tp_weaklistoffset > 0);
942 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +0000943 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +0000944 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +0000945 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +0000946 if (*weaklistptr == NULL)
947 result = Py_None;
948 else
949 result = *weaklistptr;
950 Py_INCREF(result);
951 return result;
952}
953
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000954static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +0000955 /* Not all objects have these attributes!
956 The descriptor's __get__ method may raise AttributeError. */
957 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +0000958 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +0000959 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +0000960 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +0000961 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000962};
963
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000964/* bozo: __getstate__ that raises TypeError */
965
966static PyObject *
967bozo_func(PyObject *self, PyObject *args)
968{
969 PyErr_SetString(PyExc_TypeError,
970 "a class that defines __slots__ without "
971 "defining __getstate__ cannot be pickled");
972 return NULL;
973}
974
Neal Norwitz93c1e232002-03-31 16:06:11 +0000975static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000976
977static PyObject *bozo_obj = NULL;
978
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000979static int
980valid_identifier(PyObject *s)
981{
Guido van Rossum03013a02002-07-16 14:30:28 +0000982 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000983 int i, n;
984
985 if (!PyString_Check(s)) {
986 PyErr_SetString(PyExc_TypeError,
987 "__slots__ must be strings");
988 return 0;
989 }
Guido van Rossum03013a02002-07-16 14:30:28 +0000990 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000991 n = PyString_GET_SIZE(s);
992 /* We must reject an empty name. As a hack, we bump the
993 length to 1 so that the loop will balk on the trailing \0. */
994 if (n == 0)
995 n = 1;
996 for (i = 0; i < n; i++, p++) {
997 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
998 PyErr_SetString(PyExc_TypeError,
999 "__slots__ must be identifiers");
1000 return 0;
1001 }
1002 }
1003 return 1;
1004}
1005
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001006static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1008{
1009 PyObject *name, *bases, *dict;
1010 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001011 static char buffer[256];
1012 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001013 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001015 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001016 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001017 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018
Tim Peters3abca122001-10-27 19:37:48 +00001019 assert(args != NULL && PyTuple_Check(args));
1020 assert(kwds == NULL || PyDict_Check(kwds));
1021
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001022 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001023 {
1024 const int nargs = PyTuple_GET_SIZE(args);
1025 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1026
1027 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1028 PyObject *x = PyTuple_GET_ITEM(args, 0);
1029 Py_INCREF(x->ob_type);
1030 return (PyObject *) x->ob_type;
1031 }
1032
1033 /* SF bug 475327 -- if that didn't trigger, we need 3
1034 arguments. but PyArg_ParseTupleAndKeywords below may give
1035 a msg saying type() needs exactly 3. */
1036 if (nargs + nkwds != 3) {
1037 PyErr_SetString(PyExc_TypeError,
1038 "type() takes 1 or 3 arguments");
1039 return NULL;
1040 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041 }
1042
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001043 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001044 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1045 &name,
1046 &PyTuple_Type, &bases,
1047 &PyDict_Type, &dict))
1048 return NULL;
1049
1050 /* Determine the proper metatype to deal with this,
1051 and check for metatype conflicts while we're at it.
1052 Note that if some other metatype wins to contract,
1053 it's possible that its instances are not types. */
1054 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001055 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056 for (i = 0; i < nbases; i++) {
1057 tmp = PyTuple_GET_ITEM(bases, i);
1058 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001059 if (tmptype == &PyClass_Type)
1060 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001061 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001062 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001063 if (PyType_IsSubtype(tmptype, winner)) {
1064 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001065 continue;
1066 }
1067 PyErr_SetString(PyExc_TypeError,
1068 "metatype conflict among bases");
1069 return NULL;
1070 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001071 if (winner != metatype) {
1072 if (winner->tp_new != type_new) /* Pass it to the winner */
1073 return winner->tp_new(winner, args, kwds);
1074 metatype = winner;
1075 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076
1077 /* Adjust for empty tuple bases */
1078 if (nbases == 0) {
1079 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1080 if (bases == NULL)
1081 return NULL;
1082 nbases = 1;
1083 }
1084 else
1085 Py_INCREF(bases);
1086
1087 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1088
1089 /* Calculate best base, and check that all bases are type objects */
1090 base = best_base(bases);
1091 if (base == NULL)
1092 return NULL;
1093 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1094 PyErr_Format(PyExc_TypeError,
1095 "type '%.100s' is not an acceptable base type",
1096 base->tp_name);
1097 return NULL;
1098 }
1099
Tim Peters6d6c1a32001-08-02 04:15:00 +00001100 /* Check for a __slots__ sequence variable in dict, and count it */
1101 slots = PyDict_GetItemString(dict, "__slots__");
1102 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001103 add_dict = 0;
1104 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001105 may_add_dict = base->tp_dictoffset == 0;
1106 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1107 if (slots == NULL) {
1108 if (may_add_dict) {
1109 add_dict++;
1110 }
1111 if (may_add_weak) {
1112 add_weak++;
1113 }
1114 }
1115 else {
1116 /* Have slots */
1117
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118 /* Make it into a tuple */
1119 if (PyString_Check(slots))
1120 slots = Py_BuildValue("(O)", slots);
1121 else
1122 slots = PySequence_Tuple(slots);
1123 if (slots == NULL)
1124 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001125 assert(PyTuple_Check(slots));
1126
1127 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001129 if (nslots > 0 && base->tp_itemsize != 0) {
1130 PyErr_Format(PyExc_TypeError,
1131 "nonempty __slots__ "
1132 "not supported for subtype of '%s'",
1133 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001134 bad_slots:
1135 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001136 return NULL;
1137 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001138
1139 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001141 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1142 char *s;
1143 if (!valid_identifier(tmp))
1144 goto bad_slots;
1145 assert(PyString_Check(tmp));
1146 s = PyString_AS_STRING(tmp);
1147 if (strcmp(s, "__dict__") == 0) {
1148 if (!may_add_dict || add_dict) {
1149 PyErr_SetString(PyExc_TypeError,
1150 "__dict__ slot disallowed: "
1151 "we already got one");
1152 goto bad_slots;
1153 }
1154 add_dict++;
1155 }
1156 if (strcmp(s, "__weakref__") == 0) {
1157 if (!may_add_weak || add_weak) {
1158 PyErr_SetString(PyExc_TypeError,
1159 "__weakref__ slot disallowed: "
1160 "either we already got one, "
1161 "or __itemsize__ != 0");
1162 goto bad_slots;
1163 }
1164 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 }
1166 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001167
Guido van Rossumad47da02002-08-12 19:05:44 +00001168 /* Copy slots into yet another tuple, demangling names */
1169 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001170 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001171 goto bad_slots;
1172 for (i = j = 0; i < nslots; i++) {
1173 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001174 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001175 s = PyString_AS_STRING(tmp);
1176 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1177 (add_weak && strcmp(s, "__weakref__") == 0))
1178 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001179 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001180 PyString_AS_STRING(tmp),
1181 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001182 {
1183 tmp = PyString_FromString(buffer);
1184 } else {
1185 Py_INCREF(tmp);
1186 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001187 PyTuple_SET_ITEM(newslots, j, tmp);
1188 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001189 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001190 assert(j == nslots - add_dict - add_weak);
1191 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001192 Py_DECREF(slots);
1193 slots = newslots;
1194
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001195 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001196 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001197 /* If not, provide a bozo that raises TypeError */
1198 if (bozo_obj == NULL) {
1199 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001200 if (bozo_obj == NULL)
1201 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001202 }
1203 if (PyDict_SetItemString(dict,
1204 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001205 bozo_obj) < 0)
1206 {
1207 Py_DECREF(bozo_obj);
1208 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001209 }
1210 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001211
1212 /* Secondary bases may provide weakrefs or dict */
1213 if (nbases > 1 &&
1214 ((may_add_dict && !add_dict) ||
1215 (may_add_weak && !add_weak))) {
1216 for (i = 0; i < nbases; i++) {
1217 tmp = PyTuple_GET_ITEM(bases, i);
1218 if (tmp == (PyObject *)base)
1219 continue; /* Skip primary base */
1220 if (PyClass_Check(tmp)) {
1221 /* Classic base class provides both */
1222 if (may_add_dict && !add_dict)
1223 add_dict++;
1224 if (may_add_weak && !add_weak)
1225 add_weak++;
1226 break;
1227 }
1228 assert(PyType_Check(tmp));
1229 tmptype = (PyTypeObject *)tmp;
1230 if (may_add_dict && !add_dict &&
1231 tmptype->tp_dictoffset != 0)
1232 add_dict++;
1233 if (may_add_weak && !add_weak &&
1234 tmptype->tp_weaklistoffset != 0)
1235 add_weak++;
1236 if (may_add_dict && !add_dict)
1237 continue;
1238 if (may_add_weak && !add_weak)
1239 continue;
1240 /* Nothing more to check */
1241 break;
1242 }
1243 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001244 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245
1246 /* XXX From here until type is safely allocated,
1247 "return NULL" may leak slots! */
1248
1249 /* Allocate the type object */
1250 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001251 if (type == NULL) {
1252 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001254 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255
1256 /* Keep name and slots alive in the extended type object */
1257 et = (etype *)type;
1258 Py_INCREF(name);
1259 et->name = name;
1260 et->slots = slots;
1261
Guido van Rossumdc91b992001-08-08 22:26:22 +00001262 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1264 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001265 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1266 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001267
1268 /* It's a new-style number unless it specifically inherits any
1269 old-style numeric behavior */
1270 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1271 (base->tp_as_number == NULL))
1272 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1273
1274 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 type->tp_as_number = &et->as_number;
1276 type->tp_as_sequence = &et->as_sequence;
1277 type->tp_as_mapping = &et->as_mapping;
1278 type->tp_as_buffer = &et->as_buffer;
1279 type->tp_name = PyString_AS_STRING(name);
1280
1281 /* Set tp_base and tp_bases */
1282 type->tp_bases = bases;
1283 Py_INCREF(base);
1284 type->tp_base = base;
1285
Guido van Rossum687ae002001-10-15 22:03:32 +00001286 /* Initialize tp_dict from passed-in dict */
1287 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288 if (dict == NULL) {
1289 Py_DECREF(type);
1290 return NULL;
1291 }
1292
Guido van Rossumc3542212001-08-16 09:18:56 +00001293 /* Set __module__ in the dict */
1294 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1295 tmp = PyEval_GetGlobals();
1296 if (tmp != NULL) {
1297 tmp = PyDict_GetItemString(tmp, "__name__");
1298 if (tmp != NULL) {
1299 if (PyDict_SetItemString(dict, "__module__",
1300 tmp) < 0)
1301 return NULL;
1302 }
1303 }
1304 }
1305
Tim Peters2f93e282001-10-04 05:27:00 +00001306 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001307 and is a string. The __doc__ accessor will first look for tp_doc;
1308 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001309 */
1310 {
1311 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1312 if (doc != NULL && PyString_Check(doc)) {
1313 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001314 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001315 if (type->tp_doc == NULL) {
1316 Py_DECREF(type);
1317 return NULL;
1318 }
1319 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1320 }
1321 }
1322
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 /* Special-case __new__: if it's a plain function,
1324 make it a static function */
1325 tmp = PyDict_GetItemString(dict, "__new__");
1326 if (tmp != NULL && PyFunction_Check(tmp)) {
1327 tmp = PyStaticMethod_New(tmp);
1328 if (tmp == NULL) {
1329 Py_DECREF(type);
1330 return NULL;
1331 }
1332 PyDict_SetItemString(dict, "__new__", tmp);
1333 Py_DECREF(tmp);
1334 }
1335
1336 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1337 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001338 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 if (slots != NULL) {
1340 for (i = 0; i < nslots; i++, mp++) {
1341 mp->name = PyString_AS_STRING(
1342 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001343 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001345 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001346 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001347 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001348 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001349 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001350 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001351 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352 slotoffset += sizeof(PyObject *);
1353 }
1354 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001355 if (add_dict) {
1356 if (base->tp_itemsize)
1357 type->tp_dictoffset = -(long)sizeof(PyObject *);
1358 else
1359 type->tp_dictoffset = slotoffset;
1360 slotoffset += sizeof(PyObject *);
1361 }
1362 if (add_weak) {
1363 assert(!base->tp_itemsize);
1364 type->tp_weaklistoffset = slotoffset;
1365 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 }
1367 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001368 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001369 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001370 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371
1372 /* Special case some slots */
1373 if (type->tp_dictoffset != 0 || nslots > 0) {
1374 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1375 type->tp_getattro = PyObject_GenericGetAttr;
1376 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1377 type->tp_setattro = PyObject_GenericSetAttr;
1378 }
1379 type->tp_dealloc = subtype_dealloc;
1380
Guido van Rossum9475a232001-10-05 20:51:39 +00001381 /* Enable GC unless there are really no instance variables possible */
1382 if (!(type->tp_basicsize == sizeof(PyObject) &&
1383 type->tp_itemsize == 0))
1384 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1385
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386 /* Always override allocation strategy to use regular heap */
1387 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001388 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001389 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001390 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001391 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001392 }
1393 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001394 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395
1396 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001397 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398 Py_DECREF(type);
1399 return NULL;
1400 }
1401
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001402 /* Put the proper slots in place */
1403 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001404
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405 return (PyObject *)type;
1406}
1407
1408/* Internal API to look for a name through the MRO.
1409 This returns a borrowed reference, and doesn't set an exception! */
1410PyObject *
1411_PyType_Lookup(PyTypeObject *type, PyObject *name)
1412{
1413 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001414 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415
Guido van Rossum687ae002001-10-15 22:03:32 +00001416 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001417 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001418
1419 /* If mro is NULL, the type is either not yet initialized
1420 by PyType_Ready(), or already cleared by type_clear().
1421 Either way the safest thing to do is to return NULL. */
1422 if (mro == NULL)
1423 return NULL;
1424
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 assert(PyTuple_Check(mro));
1426 n = PyTuple_GET_SIZE(mro);
1427 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001428 base = PyTuple_GET_ITEM(mro, i);
1429 if (PyClass_Check(base))
1430 dict = ((PyClassObject *)base)->cl_dict;
1431 else {
1432 assert(PyType_Check(base));
1433 dict = ((PyTypeObject *)base)->tp_dict;
1434 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001435 assert(dict && PyDict_Check(dict));
1436 res = PyDict_GetItem(dict, name);
1437 if (res != NULL)
1438 return res;
1439 }
1440 return NULL;
1441}
1442
1443/* This is similar to PyObject_GenericGetAttr(),
1444 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1445static PyObject *
1446type_getattro(PyTypeObject *type, PyObject *name)
1447{
1448 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001449 PyObject *meta_attribute, *attribute;
1450 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451
1452 /* Initialize this type (we'll assume the metatype is initialized) */
1453 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001454 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001455 return NULL;
1456 }
1457
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001458 /* No readable descriptor found yet */
1459 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001460
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001461 /* Look for the attribute in the metatype */
1462 meta_attribute = _PyType_Lookup(metatype, name);
1463
1464 if (meta_attribute != NULL) {
1465 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001466
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001467 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1468 /* Data descriptors implement tp_descr_set to intercept
1469 * writes. Assume the attribute is not overridden in
1470 * type's tp_dict (and bases): call the descriptor now.
1471 */
1472 return meta_get(meta_attribute, (PyObject *)type,
1473 (PyObject *)metatype);
1474 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475 }
1476
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001477 /* No data descriptor found on metatype. Look in tp_dict of this
1478 * type and its bases */
1479 attribute = _PyType_Lookup(type, name);
1480 if (attribute != NULL) {
1481 /* Implement descriptor functionality, if any */
1482 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1483 if (local_get != NULL) {
1484 /* NULL 2nd argument indicates the descriptor was
1485 * found on the target object itself (or a base) */
1486 return local_get(attribute, (PyObject *)NULL,
1487 (PyObject *)type);
1488 }
Tim Peters34592512002-07-11 06:23:50 +00001489
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001490 Py_INCREF(attribute);
1491 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492 }
1493
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001494 /* No attribute found in local __dict__ (or bases): use the
1495 * descriptor from the metatype, if any */
1496 if (meta_get != NULL)
1497 return meta_get(meta_attribute, (PyObject *)type,
1498 (PyObject *)metatype);
1499
1500 /* If an ordinary attribute was found on the metatype, return it now */
1501 if (meta_attribute != NULL) {
1502 Py_INCREF(meta_attribute);
1503 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504 }
1505
1506 /* Give up */
1507 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001508 "type object '%.50s' has no attribute '%.400s'",
1509 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510 return NULL;
1511}
1512
1513static int
1514type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1515{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001516 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1517 PyErr_Format(
1518 PyExc_TypeError,
1519 "can't set attributes of built-in/extension type '%s'",
1520 type->tp_name);
1521 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001522 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001523 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1524 return -1;
1525 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526}
1527
1528static void
1529type_dealloc(PyTypeObject *type)
1530{
1531 etype *et;
1532
1533 /* Assert this is a heap-allocated type object */
1534 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001535 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001536 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537 et = (etype *)type;
1538 Py_XDECREF(type->tp_base);
1539 Py_XDECREF(type->tp_dict);
1540 Py_XDECREF(type->tp_bases);
1541 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001542 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001543 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001544 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 Py_XDECREF(et->name);
1546 Py_XDECREF(et->slots);
1547 type->ob_type->tp_free((PyObject *)type);
1548}
1549
Guido van Rossum1c450732001-10-08 15:18:27 +00001550static PyObject *
1551type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1552{
1553 PyObject *list, *raw, *ref;
1554 int i, n;
1555
1556 list = PyList_New(0);
1557 if (list == NULL)
1558 return NULL;
1559 raw = type->tp_subclasses;
1560 if (raw == NULL)
1561 return list;
1562 assert(PyList_Check(raw));
1563 n = PyList_GET_SIZE(raw);
1564 for (i = 0; i < n; i++) {
1565 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001566 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001567 ref = PyWeakref_GET_OBJECT(ref);
1568 if (ref != Py_None) {
1569 if (PyList_Append(list, ref) < 0) {
1570 Py_DECREF(list);
1571 return NULL;
1572 }
1573 }
1574 }
1575 return list;
1576}
1577
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001579 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001581 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1582 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583 {0}
1584};
1585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001586PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001588"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589
Guido van Rossum048eb752001-10-02 21:24:57 +00001590static int
1591type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1592{
Guido van Rossum048eb752001-10-02 21:24:57 +00001593 int err;
1594
Guido van Rossuma3862092002-06-10 15:24:42 +00001595 /* Because of type_is_gc(), the collector only calls this
1596 for heaptypes. */
1597 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001598
1599#define VISIT(SLOT) \
1600 if (SLOT) { \
1601 err = visit((PyObject *)(SLOT), arg); \
1602 if (err) \
1603 return err; \
1604 }
1605
1606 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001607 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001608 VISIT(type->tp_mro);
1609 VISIT(type->tp_bases);
1610 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001611
1612 /* There's no need to visit type->tp_subclasses or
1613 ((etype *)type)->slots, because they can't be involved
1614 in cycles; tp_subclasses is a list of weak references,
1615 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001616
1617#undef VISIT
1618
1619 return 0;
1620}
1621
1622static int
1623type_clear(PyTypeObject *type)
1624{
Guido van Rossum048eb752001-10-02 21:24:57 +00001625 PyObject *tmp;
1626
Guido van Rossuma3862092002-06-10 15:24:42 +00001627 /* Because of type_is_gc(), the collector only calls this
1628 for heaptypes. */
1629 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001630
1631#define CLEAR(SLOT) \
1632 if (SLOT) { \
1633 tmp = (PyObject *)(SLOT); \
1634 SLOT = NULL; \
1635 Py_DECREF(tmp); \
1636 }
1637
Guido van Rossuma3862092002-06-10 15:24:42 +00001638 /* The only field we need to clear is tp_mro, which is part of a
1639 hard cycle (its first element is the class itself) that won't
1640 be broken otherwise (it's a tuple and tuples don't have a
1641 tp_clear handler). None of the other fields need to be
1642 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001643
Guido van Rossuma3862092002-06-10 15:24:42 +00001644 tp_dict:
1645 It is a dict, so the collector will call its tp_clear.
1646
1647 tp_cache:
1648 Not used; if it were, it would be a dict.
1649
1650 tp_bases, tp_base:
1651 If these are involved in a cycle, there must be at least
1652 one other, mutable object in the cycle, e.g. a base
1653 class's dict; the cycle will be broken that way.
1654
1655 tp_subclasses:
1656 A list of weak references can't be part of a cycle; and
1657 lists have their own tp_clear.
1658
1659 slots (in etype):
1660 A tuple of strings can't be part of a cycle.
1661 */
1662
1663 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001664
Guido van Rossum048eb752001-10-02 21:24:57 +00001665#undef CLEAR
1666
1667 return 0;
1668}
1669
1670static int
1671type_is_gc(PyTypeObject *type)
1672{
1673 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1674}
1675
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001676PyTypeObject PyType_Type = {
1677 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001678 0, /* ob_size */
1679 "type", /* tp_name */
1680 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001681 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682 (destructor)type_dealloc, /* tp_dealloc */
1683 0, /* tp_print */
1684 0, /* tp_getattr */
1685 0, /* tp_setattr */
1686 type_compare, /* tp_compare */
1687 (reprfunc)type_repr, /* tp_repr */
1688 0, /* tp_as_number */
1689 0, /* tp_as_sequence */
1690 0, /* tp_as_mapping */
1691 (hashfunc)_Py_HashPointer, /* tp_hash */
1692 (ternaryfunc)type_call, /* tp_call */
1693 0, /* tp_str */
1694 (getattrofunc)type_getattro, /* tp_getattro */
1695 (setattrofunc)type_setattro, /* tp_setattro */
1696 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001697 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1698 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001699 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001700 (traverseproc)type_traverse, /* tp_traverse */
1701 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001703 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704 0, /* tp_iter */
1705 0, /* tp_iternext */
1706 type_methods, /* tp_methods */
1707 type_members, /* tp_members */
1708 type_getsets, /* tp_getset */
1709 0, /* tp_base */
1710 0, /* tp_dict */
1711 0, /* tp_descr_get */
1712 0, /* tp_descr_set */
1713 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1714 0, /* tp_init */
1715 0, /* tp_alloc */
1716 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001717 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001718 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001719};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720
1721
1722/* The base type of all types (eventually)... except itself. */
1723
1724static int
1725object_init(PyObject *self, PyObject *args, PyObject *kwds)
1726{
1727 return 0;
1728}
1729
1730static void
1731object_dealloc(PyObject *self)
1732{
1733 self->ob_type->tp_free(self);
1734}
1735
Guido van Rossum8e248182001-08-12 05:17:56 +00001736static PyObject *
1737object_repr(PyObject *self)
1738{
Guido van Rossum76e69632001-08-16 18:52:43 +00001739 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001740 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001741
Guido van Rossum76e69632001-08-16 18:52:43 +00001742 type = self->ob_type;
1743 mod = type_module(type, NULL);
1744 if (mod == NULL)
1745 PyErr_Clear();
1746 else if (!PyString_Check(mod)) {
1747 Py_DECREF(mod);
1748 mod = NULL;
1749 }
1750 name = type_name(type, NULL);
1751 if (name == NULL)
1752 return NULL;
1753 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001754 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001755 PyString_AS_STRING(mod),
1756 PyString_AS_STRING(name),
1757 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001758 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001759 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001760 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001761 Py_XDECREF(mod);
1762 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001763 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001764}
1765
Guido van Rossumb8f63662001-08-15 23:57:02 +00001766static PyObject *
1767object_str(PyObject *self)
1768{
1769 unaryfunc f;
1770
1771 f = self->ob_type->tp_repr;
1772 if (f == NULL)
1773 f = object_repr;
1774 return f(self);
1775}
1776
Guido van Rossum8e248182001-08-12 05:17:56 +00001777static long
1778object_hash(PyObject *self)
1779{
1780 return _Py_HashPointer(self);
1781}
Guido van Rossum8e248182001-08-12 05:17:56 +00001782
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001783static PyObject *
1784object_get_class(PyObject *self, void *closure)
1785{
1786 Py_INCREF(self->ob_type);
1787 return (PyObject *)(self->ob_type);
1788}
1789
1790static int
1791equiv_structs(PyTypeObject *a, PyTypeObject *b)
1792{
1793 return a == b ||
1794 (a != NULL &&
1795 b != NULL &&
1796 a->tp_basicsize == b->tp_basicsize &&
1797 a->tp_itemsize == b->tp_itemsize &&
1798 a->tp_dictoffset == b->tp_dictoffset &&
1799 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1800 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1801 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1802}
1803
1804static int
1805same_slots_added(PyTypeObject *a, PyTypeObject *b)
1806{
1807 PyTypeObject *base = a->tp_base;
1808 int size;
1809
1810 if (base != b->tp_base)
1811 return 0;
1812 if (equiv_structs(a, base) && equiv_structs(b, base))
1813 return 1;
1814 size = base->tp_basicsize;
1815 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1816 size += sizeof(PyObject *);
1817 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1818 size += sizeof(PyObject *);
1819 return size == a->tp_basicsize && size == b->tp_basicsize;
1820}
1821
1822static int
1823object_set_class(PyObject *self, PyObject *value, void *closure)
1824{
1825 PyTypeObject *old = self->ob_type;
1826 PyTypeObject *new, *newbase, *oldbase;
1827
Guido van Rossumb6b89422002-04-15 01:03:30 +00001828 if (value == NULL) {
1829 PyErr_SetString(PyExc_TypeError,
1830 "can't delete __class__ attribute");
1831 return -1;
1832 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001833 if (!PyType_Check(value)) {
1834 PyErr_Format(PyExc_TypeError,
1835 "__class__ must be set to new-style class, not '%s' object",
1836 value->ob_type->tp_name);
1837 return -1;
1838 }
1839 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00001840 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
1841 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
1842 {
1843 PyErr_Format(PyExc_TypeError,
1844 "__class__ assignment: only for heap types");
1845 return -1;
1846 }
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001847 if (new->tp_dealloc != old->tp_dealloc ||
1848 new->tp_free != old->tp_free)
1849 {
1850 PyErr_Format(PyExc_TypeError,
1851 "__class__ assignment: "
1852 "'%s' deallocator differs from '%s'",
1853 new->tp_name,
1854 old->tp_name);
1855 return -1;
1856 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001857 newbase = new;
1858 oldbase = old;
1859 while (equiv_structs(newbase, newbase->tp_base))
1860 newbase = newbase->tp_base;
1861 while (equiv_structs(oldbase, oldbase->tp_base))
1862 oldbase = oldbase->tp_base;
1863 if (newbase != oldbase &&
1864 (newbase->tp_base != oldbase->tp_base ||
1865 !same_slots_added(newbase, oldbase))) {
1866 PyErr_Format(PyExc_TypeError,
1867 "__class__ assignment: "
1868 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001869 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001870 old->tp_name);
1871 return -1;
1872 }
Guido van Rossum40af8892002-08-10 05:42:07 +00001873 Py_INCREF(new);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001874 self->ob_type = new;
Guido van Rossum40af8892002-08-10 05:42:07 +00001875 Py_DECREF(old);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001876 return 0;
1877}
1878
1879static PyGetSetDef object_getsets[] = {
1880 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001881 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882 {0}
1883};
1884
Guido van Rossum3926a632001-09-25 16:25:58 +00001885static PyObject *
1886object_reduce(PyObject *self, PyObject *args)
1887{
1888 /* Call copy_reg._reduce(self) */
1889 static PyObject *copy_reg_str;
1890 PyObject *copy_reg, *res;
1891
1892 if (!copy_reg_str) {
1893 copy_reg_str = PyString_InternFromString("copy_reg");
1894 if (copy_reg_str == NULL)
1895 return NULL;
1896 }
1897 copy_reg = PyImport_Import(copy_reg_str);
1898 if (!copy_reg)
1899 return NULL;
1900 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1901 Py_DECREF(copy_reg);
1902 return res;
1903}
1904
1905static PyMethodDef object_methods[] = {
1906 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1907 {0}
1908};
1909
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910PyTypeObject PyBaseObject_Type = {
1911 PyObject_HEAD_INIT(&PyType_Type)
1912 0, /* ob_size */
1913 "object", /* tp_name */
1914 sizeof(PyObject), /* tp_basicsize */
1915 0, /* tp_itemsize */
1916 (destructor)object_dealloc, /* tp_dealloc */
1917 0, /* tp_print */
1918 0, /* tp_getattr */
1919 0, /* tp_setattr */
1920 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001921 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 0, /* tp_as_number */
1923 0, /* tp_as_sequence */
1924 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001925 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001927 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001929 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930 0, /* tp_as_buffer */
1931 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1932 "The most base type", /* tp_doc */
1933 0, /* tp_traverse */
1934 0, /* tp_clear */
1935 0, /* tp_richcompare */
1936 0, /* tp_weaklistoffset */
1937 0, /* tp_iter */
1938 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001939 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001940 0, /* tp_members */
1941 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001942 0, /* tp_base */
1943 0, /* tp_dict */
1944 0, /* tp_descr_get */
1945 0, /* tp_descr_set */
1946 0, /* tp_dictoffset */
1947 object_init, /* tp_init */
1948 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001949 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001950 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951};
1952
1953
1954/* Initialize the __dict__ in a type object */
1955
Fred Drake7bf97152002-03-28 05:33:33 +00001956static PyObject *
1957create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1958{
1959 PyObject *cfunc;
1960 PyObject *result;
1961
1962 cfunc = PyCFunction_New(meth, NULL);
1963 if (cfunc == NULL)
1964 return NULL;
1965 result = func(cfunc);
1966 Py_DECREF(cfunc);
1967 return result;
1968}
1969
Tim Peters6d6c1a32001-08-02 04:15:00 +00001970static int
1971add_methods(PyTypeObject *type, PyMethodDef *meth)
1972{
Guido van Rossum687ae002001-10-15 22:03:32 +00001973 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001974
1975 for (; meth->ml_name != NULL; meth++) {
1976 PyObject *descr;
1977 if (PyDict_GetItemString(dict, meth->ml_name))
1978 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001979 if (meth->ml_flags & METH_CLASS) {
1980 if (meth->ml_flags & METH_STATIC) {
1981 PyErr_SetString(PyExc_ValueError,
1982 "method cannot be both class and static");
1983 return -1;
1984 }
1985 descr = create_specialmethod(meth, PyClassMethod_New);
1986 }
1987 else if (meth->ml_flags & METH_STATIC) {
1988 descr = create_specialmethod(meth, PyStaticMethod_New);
1989 }
1990 else {
1991 descr = PyDescr_NewMethod(type, meth);
1992 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993 if (descr == NULL)
1994 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001995 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996 return -1;
1997 Py_DECREF(descr);
1998 }
1999 return 0;
2000}
2001
2002static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002003add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002004{
Guido van Rossum687ae002001-10-15 22:03:32 +00002005 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006
2007 for (; memb->name != NULL; memb++) {
2008 PyObject *descr;
2009 if (PyDict_GetItemString(dict, memb->name))
2010 continue;
2011 descr = PyDescr_NewMember(type, memb);
2012 if (descr == NULL)
2013 return -1;
2014 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2015 return -1;
2016 Py_DECREF(descr);
2017 }
2018 return 0;
2019}
2020
2021static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002022add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002023{
Guido van Rossum687ae002001-10-15 22:03:32 +00002024 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025
2026 for (; gsp->name != NULL; gsp++) {
2027 PyObject *descr;
2028 if (PyDict_GetItemString(dict, gsp->name))
2029 continue;
2030 descr = PyDescr_NewGetSet(type, gsp);
2031
2032 if (descr == NULL)
2033 return -1;
2034 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2035 return -1;
2036 Py_DECREF(descr);
2037 }
2038 return 0;
2039}
2040
Guido van Rossum13d52f02001-08-10 21:24:08 +00002041static void
2042inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043{
2044 int oldsize, newsize;
2045
Guido van Rossum13d52f02001-08-10 21:24:08 +00002046 /* Special flag magic */
2047 if (!type->tp_as_buffer && base->tp_as_buffer) {
2048 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2049 type->tp_flags |=
2050 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2051 }
2052 if (!type->tp_as_sequence && base->tp_as_sequence) {
2053 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2054 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2055 }
2056 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2057 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2058 if ((!type->tp_as_number && base->tp_as_number) ||
2059 (!type->tp_as_sequence && base->tp_as_sequence)) {
2060 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2061 if (!type->tp_as_number && !type->tp_as_sequence) {
2062 type->tp_flags |= base->tp_flags &
2063 Py_TPFLAGS_HAVE_INPLACEOPS;
2064 }
2065 }
2066 /* Wow */
2067 }
2068 if (!type->tp_as_number && base->tp_as_number) {
2069 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2070 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2071 }
2072
2073 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002074 oldsize = base->tp_basicsize;
2075 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2076 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2077 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002078 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2079 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002080 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002081 if (type->tp_traverse == NULL)
2082 type->tp_traverse = base->tp_traverse;
2083 if (type->tp_clear == NULL)
2084 type->tp_clear = base->tp_clear;
2085 }
2086 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002087 /* The condition below could use some explanation.
2088 It appears that tp_new is not inherited for static types
2089 whose base class is 'object'; this seems to be a precaution
2090 so that old extension types don't suddenly become
2091 callable (object.__new__ wouldn't insure the invariants
2092 that the extension type's own factory function ensures).
2093 Heap types, of course, are under our control, so they do
2094 inherit tp_new; static extension types that specify some
2095 other built-in type as the default are considered
2096 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002097 if (base != &PyBaseObject_Type ||
2098 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2099 if (type->tp_new == NULL)
2100 type->tp_new = base->tp_new;
2101 }
2102 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002103 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002104
2105 /* Copy other non-function slots */
2106
2107#undef COPYVAL
2108#define COPYVAL(SLOT) \
2109 if (type->SLOT == 0) type->SLOT = base->SLOT
2110
2111 COPYVAL(tp_itemsize);
2112 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2113 COPYVAL(tp_weaklistoffset);
2114 }
2115 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2116 COPYVAL(tp_dictoffset);
2117 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002118}
2119
2120static void
2121inherit_slots(PyTypeObject *type, PyTypeObject *base)
2122{
2123 PyTypeObject *basebase;
2124
2125#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126#undef COPYSLOT
2127#undef COPYNUM
2128#undef COPYSEQ
2129#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002130#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002131
2132#define SLOTDEFINED(SLOT) \
2133 (base->SLOT != 0 && \
2134 (basebase == NULL || base->SLOT != basebase->SLOT))
2135
Tim Peters6d6c1a32001-08-02 04:15:00 +00002136#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002137 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138
2139#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2140#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2141#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002142#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002143
Guido van Rossum13d52f02001-08-10 21:24:08 +00002144 /* This won't inherit indirect slots (from tp_as_number etc.)
2145 if type doesn't provide the space. */
2146
2147 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2148 basebase = base->tp_base;
2149 if (basebase->tp_as_number == NULL)
2150 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151 COPYNUM(nb_add);
2152 COPYNUM(nb_subtract);
2153 COPYNUM(nb_multiply);
2154 COPYNUM(nb_divide);
2155 COPYNUM(nb_remainder);
2156 COPYNUM(nb_divmod);
2157 COPYNUM(nb_power);
2158 COPYNUM(nb_negative);
2159 COPYNUM(nb_positive);
2160 COPYNUM(nb_absolute);
2161 COPYNUM(nb_nonzero);
2162 COPYNUM(nb_invert);
2163 COPYNUM(nb_lshift);
2164 COPYNUM(nb_rshift);
2165 COPYNUM(nb_and);
2166 COPYNUM(nb_xor);
2167 COPYNUM(nb_or);
2168 COPYNUM(nb_coerce);
2169 COPYNUM(nb_int);
2170 COPYNUM(nb_long);
2171 COPYNUM(nb_float);
2172 COPYNUM(nb_oct);
2173 COPYNUM(nb_hex);
2174 COPYNUM(nb_inplace_add);
2175 COPYNUM(nb_inplace_subtract);
2176 COPYNUM(nb_inplace_multiply);
2177 COPYNUM(nb_inplace_divide);
2178 COPYNUM(nb_inplace_remainder);
2179 COPYNUM(nb_inplace_power);
2180 COPYNUM(nb_inplace_lshift);
2181 COPYNUM(nb_inplace_rshift);
2182 COPYNUM(nb_inplace_and);
2183 COPYNUM(nb_inplace_xor);
2184 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002185 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2186 COPYNUM(nb_true_divide);
2187 COPYNUM(nb_floor_divide);
2188 COPYNUM(nb_inplace_true_divide);
2189 COPYNUM(nb_inplace_floor_divide);
2190 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002191 }
2192
Guido van Rossum13d52f02001-08-10 21:24:08 +00002193 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2194 basebase = base->tp_base;
2195 if (basebase->tp_as_sequence == NULL)
2196 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197 COPYSEQ(sq_length);
2198 COPYSEQ(sq_concat);
2199 COPYSEQ(sq_repeat);
2200 COPYSEQ(sq_item);
2201 COPYSEQ(sq_slice);
2202 COPYSEQ(sq_ass_item);
2203 COPYSEQ(sq_ass_slice);
2204 COPYSEQ(sq_contains);
2205 COPYSEQ(sq_inplace_concat);
2206 COPYSEQ(sq_inplace_repeat);
2207 }
2208
Guido van Rossum13d52f02001-08-10 21:24:08 +00002209 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2210 basebase = base->tp_base;
2211 if (basebase->tp_as_mapping == NULL)
2212 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002213 COPYMAP(mp_length);
2214 COPYMAP(mp_subscript);
2215 COPYMAP(mp_ass_subscript);
2216 }
2217
Tim Petersfc57ccb2001-10-12 02:38:24 +00002218 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2219 basebase = base->tp_base;
2220 if (basebase->tp_as_buffer == NULL)
2221 basebase = NULL;
2222 COPYBUF(bf_getreadbuffer);
2223 COPYBUF(bf_getwritebuffer);
2224 COPYBUF(bf_getsegcount);
2225 COPYBUF(bf_getcharbuffer);
2226 }
2227
Guido van Rossum13d52f02001-08-10 21:24:08 +00002228 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230 COPYSLOT(tp_dealloc);
2231 COPYSLOT(tp_print);
2232 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2233 type->tp_getattr = base->tp_getattr;
2234 type->tp_getattro = base->tp_getattro;
2235 }
2236 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2237 type->tp_setattr = base->tp_setattr;
2238 type->tp_setattro = base->tp_setattro;
2239 }
2240 /* tp_compare see tp_richcompare */
2241 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002242 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002243 COPYSLOT(tp_call);
2244 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002246 if (type->tp_compare == NULL &&
2247 type->tp_richcompare == NULL &&
2248 type->tp_hash == NULL)
2249 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250 type->tp_compare = base->tp_compare;
2251 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002252 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253 }
2254 }
2255 else {
2256 COPYSLOT(tp_compare);
2257 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2259 COPYSLOT(tp_iter);
2260 COPYSLOT(tp_iternext);
2261 }
2262 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2263 COPYSLOT(tp_descr_get);
2264 COPYSLOT(tp_descr_set);
2265 COPYSLOT(tp_dictoffset);
2266 COPYSLOT(tp_init);
2267 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002268 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002269 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271}
2272
Jeremy Hylton938ace62002-07-17 16:30:39 +00002273static int add_operators(PyTypeObject *);
2274static int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002275
Tim Peters6d6c1a32001-08-02 04:15:00 +00002276int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002277PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002278{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002279 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280 PyTypeObject *base;
2281 int i, n;
2282
Guido van Rossumcab05802002-06-10 15:29:03 +00002283 if (type->tp_flags & Py_TPFLAGS_READY) {
2284 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002285 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002286 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002287 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002288
2289 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290
2291 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2292 base = type->tp_base;
2293 if (base == NULL && type != &PyBaseObject_Type)
2294 base = type->tp_base = &PyBaseObject_Type;
2295
Guido van Rossum0986d822002-04-08 01:38:42 +00002296 /* Initialize ob_type if NULL. This means extensions that want to be
2297 compilable separately on Windows can call PyType_Ready() instead of
2298 initializing the ob_type field of their type objects. */
2299 if (type->ob_type == NULL)
2300 type->ob_type = base->ob_type;
2301
Tim Peters6d6c1a32001-08-02 04:15:00 +00002302 /* Initialize tp_bases */
2303 bases = type->tp_bases;
2304 if (bases == NULL) {
2305 if (base == NULL)
2306 bases = PyTuple_New(0);
2307 else
2308 bases = Py_BuildValue("(O)", base);
2309 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002310 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002311 type->tp_bases = bases;
2312 }
2313
2314 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002315 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002316 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002317 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002318 }
2319
Guido van Rossum687ae002001-10-15 22:03:32 +00002320 /* Initialize tp_dict */
2321 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 if (dict == NULL) {
2323 dict = PyDict_New();
2324 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002325 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002326 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327 }
2328
Guido van Rossum687ae002001-10-15 22:03:32 +00002329 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002331 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332 if (type->tp_methods != NULL) {
2333 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002334 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335 }
2336 if (type->tp_members != NULL) {
2337 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002338 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002339 }
2340 if (type->tp_getset != NULL) {
2341 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002342 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343 }
2344
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345 /* Calculate method resolution order */
2346 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002347 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348 }
2349
Guido van Rossum13d52f02001-08-10 21:24:08 +00002350 /* Inherit special flags from dominant base */
2351 if (type->tp_base != NULL)
2352 inherit_special(type, type->tp_base);
2353
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002355 bases = type->tp_mro;
2356 assert(bases != NULL);
2357 assert(PyTuple_Check(bases));
2358 n = PyTuple_GET_SIZE(bases);
2359 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002360 PyObject *b = PyTuple_GET_ITEM(bases, i);
2361 if (PyType_Check(b))
2362 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002363 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002364
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002365 /* if the type dictionary doesn't contain a __doc__, set it from
2366 the tp_doc slot.
2367 */
2368 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2369 if (type->tp_doc != NULL) {
2370 PyObject *doc = PyString_FromString(type->tp_doc);
2371 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2372 Py_DECREF(doc);
2373 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002374 PyDict_SetItemString(type->tp_dict,
2375 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002376 }
2377 }
2378
Guido van Rossum13d52f02001-08-10 21:24:08 +00002379 /* Some more special stuff */
2380 base = type->tp_base;
2381 if (base != NULL) {
2382 if (type->tp_as_number == NULL)
2383 type->tp_as_number = base->tp_as_number;
2384 if (type->tp_as_sequence == NULL)
2385 type->tp_as_sequence = base->tp_as_sequence;
2386 if (type->tp_as_mapping == NULL)
2387 type->tp_as_mapping = base->tp_as_mapping;
2388 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389
Guido van Rossum1c450732001-10-08 15:18:27 +00002390 /* Link into each base class's list of subclasses */
2391 bases = type->tp_bases;
2392 n = PyTuple_GET_SIZE(bases);
2393 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002394 PyObject *b = PyTuple_GET_ITEM(bases, i);
2395 if (PyType_Check(b) &&
2396 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002397 goto error;
2398 }
2399
Guido van Rossum13d52f02001-08-10 21:24:08 +00002400 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002401 assert(type->tp_dict != NULL);
2402 type->tp_flags =
2403 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002405
2406 error:
2407 type->tp_flags &= ~Py_TPFLAGS_READYING;
2408 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002409}
2410
Guido van Rossum1c450732001-10-08 15:18:27 +00002411static int
2412add_subclass(PyTypeObject *base, PyTypeObject *type)
2413{
2414 int i;
2415 PyObject *list, *ref, *new;
2416
2417 list = base->tp_subclasses;
2418 if (list == NULL) {
2419 base->tp_subclasses = list = PyList_New(0);
2420 if (list == NULL)
2421 return -1;
2422 }
2423 assert(PyList_Check(list));
2424 new = PyWeakref_NewRef((PyObject *)type, NULL);
2425 i = PyList_GET_SIZE(list);
2426 while (--i >= 0) {
2427 ref = PyList_GET_ITEM(list, i);
2428 assert(PyWeakref_CheckRef(ref));
2429 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2430 return PyList_SetItem(list, i, new);
2431 }
2432 i = PyList_Append(list, new);
2433 Py_DECREF(new);
2434 return i;
2435}
2436
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437
2438/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2439
2440/* There's a wrapper *function* for each distinct function typedef used
2441 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2442 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2443 Most tables have only one entry; the tables for binary operators have two
2444 entries, one regular and one with reversed arguments. */
2445
2446static PyObject *
2447wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2448{
2449 inquiry func = (inquiry)wrapped;
2450 int res;
2451
2452 if (!PyArg_ParseTuple(args, ""))
2453 return NULL;
2454 res = (*func)(self);
2455 if (res == -1 && PyErr_Occurred())
2456 return NULL;
2457 return PyInt_FromLong((long)res);
2458}
2459
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460static PyObject *
2461wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2462{
2463 binaryfunc func = (binaryfunc)wrapped;
2464 PyObject *other;
2465
2466 if (!PyArg_ParseTuple(args, "O", &other))
2467 return NULL;
2468 return (*func)(self, other);
2469}
2470
2471static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002472wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2473{
2474 binaryfunc func = (binaryfunc)wrapped;
2475 PyObject *other;
2476
2477 if (!PyArg_ParseTuple(args, "O", &other))
2478 return NULL;
2479 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002480 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002481 Py_INCREF(Py_NotImplemented);
2482 return Py_NotImplemented;
2483 }
2484 return (*func)(self, other);
2485}
2486
2487static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002488wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2489{
2490 binaryfunc func = (binaryfunc)wrapped;
2491 PyObject *other;
2492
2493 if (!PyArg_ParseTuple(args, "O", &other))
2494 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002495 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002496 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002497 Py_INCREF(Py_NotImplemented);
2498 return Py_NotImplemented;
2499 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500 return (*func)(other, self);
2501}
2502
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002503static PyObject *
2504wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2505{
2506 coercion func = (coercion)wrapped;
2507 PyObject *other, *res;
2508 int ok;
2509
2510 if (!PyArg_ParseTuple(args, "O", &other))
2511 return NULL;
2512 ok = func(&self, &other);
2513 if (ok < 0)
2514 return NULL;
2515 if (ok > 0) {
2516 Py_INCREF(Py_NotImplemented);
2517 return Py_NotImplemented;
2518 }
2519 res = PyTuple_New(2);
2520 if (res == NULL) {
2521 Py_DECREF(self);
2522 Py_DECREF(other);
2523 return NULL;
2524 }
2525 PyTuple_SET_ITEM(res, 0, self);
2526 PyTuple_SET_ITEM(res, 1, other);
2527 return res;
2528}
2529
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530static PyObject *
2531wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2532{
2533 ternaryfunc func = (ternaryfunc)wrapped;
2534 PyObject *other;
2535 PyObject *third = Py_None;
2536
2537 /* Note: This wrapper only works for __pow__() */
2538
2539 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2540 return NULL;
2541 return (*func)(self, other, third);
2542}
2543
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002544static PyObject *
2545wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2546{
2547 ternaryfunc func = (ternaryfunc)wrapped;
2548 PyObject *other;
2549 PyObject *third = Py_None;
2550
2551 /* Note: This wrapper only works for __pow__() */
2552
2553 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2554 return NULL;
2555 return (*func)(other, self, third);
2556}
2557
Tim Peters6d6c1a32001-08-02 04:15:00 +00002558static PyObject *
2559wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2560{
2561 unaryfunc func = (unaryfunc)wrapped;
2562
2563 if (!PyArg_ParseTuple(args, ""))
2564 return NULL;
2565 return (*func)(self);
2566}
2567
Tim Peters6d6c1a32001-08-02 04:15:00 +00002568static PyObject *
2569wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2570{
2571 intargfunc func = (intargfunc)wrapped;
2572 int i;
2573
2574 if (!PyArg_ParseTuple(args, "i", &i))
2575 return NULL;
2576 return (*func)(self, i);
2577}
2578
Guido van Rossum5d815f32001-08-17 21:57:47 +00002579static int
2580getindex(PyObject *self, PyObject *arg)
2581{
2582 int i;
2583
2584 i = PyInt_AsLong(arg);
2585 if (i == -1 && PyErr_Occurred())
2586 return -1;
2587 if (i < 0) {
2588 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2589 if (sq && sq->sq_length) {
2590 int n = (*sq->sq_length)(self);
2591 if (n < 0)
2592 return -1;
2593 i += n;
2594 }
2595 }
2596 return i;
2597}
2598
2599static PyObject *
2600wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2601{
2602 intargfunc func = (intargfunc)wrapped;
2603 PyObject *arg;
2604 int i;
2605
Guido van Rossumf4593e02001-10-03 12:09:30 +00002606 if (PyTuple_GET_SIZE(args) == 1) {
2607 arg = PyTuple_GET_ITEM(args, 0);
2608 i = getindex(self, arg);
2609 if (i == -1 && PyErr_Occurred())
2610 return NULL;
2611 return (*func)(self, i);
2612 }
2613 PyArg_ParseTuple(args, "O", &arg);
2614 assert(PyErr_Occurred());
2615 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002616}
2617
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618static PyObject *
2619wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2620{
2621 intintargfunc func = (intintargfunc)wrapped;
2622 int i, j;
2623
2624 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2625 return NULL;
2626 return (*func)(self, i, j);
2627}
2628
Tim Peters6d6c1a32001-08-02 04:15:00 +00002629static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002630wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002631{
2632 intobjargproc func = (intobjargproc)wrapped;
2633 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002634 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002635
Guido van Rossum5d815f32001-08-17 21:57:47 +00002636 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2637 return NULL;
2638 i = getindex(self, arg);
2639 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002640 return NULL;
2641 res = (*func)(self, i, value);
2642 if (res == -1 && PyErr_Occurred())
2643 return NULL;
2644 Py_INCREF(Py_None);
2645 return Py_None;
2646}
2647
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002648static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002649wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002650{
2651 intobjargproc func = (intobjargproc)wrapped;
2652 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002653 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002654
Guido van Rossum5d815f32001-08-17 21:57:47 +00002655 if (!PyArg_ParseTuple(args, "O", &arg))
2656 return NULL;
2657 i = getindex(self, arg);
2658 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002659 return NULL;
2660 res = (*func)(self, i, NULL);
2661 if (res == -1 && PyErr_Occurred())
2662 return NULL;
2663 Py_INCREF(Py_None);
2664 return Py_None;
2665}
2666
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667static PyObject *
2668wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2669{
2670 intintobjargproc func = (intintobjargproc)wrapped;
2671 int i, j, res;
2672 PyObject *value;
2673
2674 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2675 return NULL;
2676 res = (*func)(self, i, j, value);
2677 if (res == -1 && PyErr_Occurred())
2678 return NULL;
2679 Py_INCREF(Py_None);
2680 return Py_None;
2681}
2682
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002683static PyObject *
2684wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2685{
2686 intintobjargproc func = (intintobjargproc)wrapped;
2687 int i, j, res;
2688
2689 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2690 return NULL;
2691 res = (*func)(self, i, j, NULL);
2692 if (res == -1 && PyErr_Occurred())
2693 return NULL;
2694 Py_INCREF(Py_None);
2695 return Py_None;
2696}
2697
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698/* XXX objobjproc is a misnomer; should be objargpred */
2699static PyObject *
2700wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2701{
2702 objobjproc func = (objobjproc)wrapped;
2703 int res;
2704 PyObject *value;
2705
2706 if (!PyArg_ParseTuple(args, "O", &value))
2707 return NULL;
2708 res = (*func)(self, value);
2709 if (res == -1 && PyErr_Occurred())
2710 return NULL;
2711 return PyInt_FromLong((long)res);
2712}
2713
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714static PyObject *
2715wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2716{
2717 objobjargproc func = (objobjargproc)wrapped;
2718 int res;
2719 PyObject *key, *value;
2720
2721 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2722 return NULL;
2723 res = (*func)(self, key, value);
2724 if (res == -1 && PyErr_Occurred())
2725 return NULL;
2726 Py_INCREF(Py_None);
2727 return Py_None;
2728}
2729
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002730static PyObject *
2731wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2732{
2733 objobjargproc func = (objobjargproc)wrapped;
2734 int res;
2735 PyObject *key;
2736
2737 if (!PyArg_ParseTuple(args, "O", &key))
2738 return NULL;
2739 res = (*func)(self, key, NULL);
2740 if (res == -1 && PyErr_Occurred())
2741 return NULL;
2742 Py_INCREF(Py_None);
2743 return Py_None;
2744}
2745
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746static PyObject *
2747wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2748{
2749 cmpfunc func = (cmpfunc)wrapped;
2750 int res;
2751 PyObject *other;
2752
2753 if (!PyArg_ParseTuple(args, "O", &other))
2754 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002755 if (other->ob_type->tp_compare != func &&
2756 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002757 PyErr_Format(
2758 PyExc_TypeError,
2759 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2760 self->ob_type->tp_name,
2761 self->ob_type->tp_name,
2762 other->ob_type->tp_name);
2763 return NULL;
2764 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765 res = (*func)(self, other);
2766 if (PyErr_Occurred())
2767 return NULL;
2768 return PyInt_FromLong((long)res);
2769}
2770
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771static PyObject *
2772wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2773{
2774 setattrofunc func = (setattrofunc)wrapped;
2775 int res;
2776 PyObject *name, *value;
2777
2778 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2779 return NULL;
2780 res = (*func)(self, name, value);
2781 if (res < 0)
2782 return NULL;
2783 Py_INCREF(Py_None);
2784 return Py_None;
2785}
2786
2787static PyObject *
2788wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2789{
2790 setattrofunc func = (setattrofunc)wrapped;
2791 int res;
2792 PyObject *name;
2793
2794 if (!PyArg_ParseTuple(args, "O", &name))
2795 return NULL;
2796 res = (*func)(self, name, NULL);
2797 if (res < 0)
2798 return NULL;
2799 Py_INCREF(Py_None);
2800 return Py_None;
2801}
2802
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803static PyObject *
2804wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2805{
2806 hashfunc func = (hashfunc)wrapped;
2807 long res;
2808
2809 if (!PyArg_ParseTuple(args, ""))
2810 return NULL;
2811 res = (*func)(self);
2812 if (res == -1 && PyErr_Occurred())
2813 return NULL;
2814 return PyInt_FromLong(res);
2815}
2816
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002818wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819{
2820 ternaryfunc func = (ternaryfunc)wrapped;
2821
Guido van Rossumc8e56452001-10-22 00:43:43 +00002822 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823}
2824
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825static PyObject *
2826wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2827{
2828 richcmpfunc func = (richcmpfunc)wrapped;
2829 PyObject *other;
2830
2831 if (!PyArg_ParseTuple(args, "O", &other))
2832 return NULL;
2833 return (*func)(self, other, op);
2834}
2835
2836#undef RICHCMP_WRAPPER
2837#define RICHCMP_WRAPPER(NAME, OP) \
2838static PyObject * \
2839richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2840{ \
2841 return wrap_richcmpfunc(self, args, wrapped, OP); \
2842}
2843
Jack Jansen8e938b42001-08-08 15:29:49 +00002844RICHCMP_WRAPPER(lt, Py_LT)
2845RICHCMP_WRAPPER(le, Py_LE)
2846RICHCMP_WRAPPER(eq, Py_EQ)
2847RICHCMP_WRAPPER(ne, Py_NE)
2848RICHCMP_WRAPPER(gt, Py_GT)
2849RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002850
Tim Peters6d6c1a32001-08-02 04:15:00 +00002851static PyObject *
2852wrap_next(PyObject *self, PyObject *args, void *wrapped)
2853{
2854 unaryfunc func = (unaryfunc)wrapped;
2855 PyObject *res;
2856
2857 if (!PyArg_ParseTuple(args, ""))
2858 return NULL;
2859 res = (*func)(self);
2860 if (res == NULL && !PyErr_Occurred())
2861 PyErr_SetNone(PyExc_StopIteration);
2862 return res;
2863}
2864
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865static PyObject *
2866wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2867{
2868 descrgetfunc func = (descrgetfunc)wrapped;
2869 PyObject *obj;
2870 PyObject *type = NULL;
2871
2872 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2873 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002874 return (*func)(self, obj, type);
2875}
2876
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002878wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002879{
2880 descrsetfunc func = (descrsetfunc)wrapped;
2881 PyObject *obj, *value;
2882 int ret;
2883
2884 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2885 return NULL;
2886 ret = (*func)(self, obj, value);
2887 if (ret < 0)
2888 return NULL;
2889 Py_INCREF(Py_None);
2890 return Py_None;
2891}
Guido van Rossum22b13872002-08-06 21:41:44 +00002892
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002893static PyObject *
2894wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
2895{
2896 descrsetfunc func = (descrsetfunc)wrapped;
2897 PyObject *obj;
2898 int ret;
2899
2900 if (!PyArg_ParseTuple(args, "O", &obj))
2901 return NULL;
2902 ret = (*func)(self, obj, NULL);
2903 if (ret < 0)
2904 return NULL;
2905 Py_INCREF(Py_None);
2906 return Py_None;
2907}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002910wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911{
2912 initproc func = (initproc)wrapped;
2913
Guido van Rossumc8e56452001-10-22 00:43:43 +00002914 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915 return NULL;
2916 Py_INCREF(Py_None);
2917 return Py_None;
2918}
2919
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002921tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002922{
Barry Warsaw60f01882001-08-22 19:24:42 +00002923 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002924 PyObject *arg0, *res;
2925
2926 if (self == NULL || !PyType_Check(self))
2927 Py_FatalError("__new__() called with non-type 'self'");
2928 type = (PyTypeObject *)self;
2929 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002930 PyErr_Format(PyExc_TypeError,
2931 "%s.__new__(): not enough arguments",
2932 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002933 return NULL;
2934 }
2935 arg0 = PyTuple_GET_ITEM(args, 0);
2936 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002937 PyErr_Format(PyExc_TypeError,
2938 "%s.__new__(X): X is not a type object (%s)",
2939 type->tp_name,
2940 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002941 return NULL;
2942 }
2943 subtype = (PyTypeObject *)arg0;
2944 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002945 PyErr_Format(PyExc_TypeError,
2946 "%s.__new__(%s): %s is not a subtype of %s",
2947 type->tp_name,
2948 subtype->tp_name,
2949 subtype->tp_name,
2950 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002951 return NULL;
2952 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002953
2954 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002955 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002956 most derived base that's not a heap type is this type. */
2957 staticbase = subtype;
2958 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2959 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002960 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002961 PyErr_Format(PyExc_TypeError,
2962 "%s.__new__(%s) is not safe, use %s.__new__()",
2963 type->tp_name,
2964 subtype->tp_name,
2965 staticbase == NULL ? "?" : staticbase->tp_name);
2966 return NULL;
2967 }
2968
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002969 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2970 if (args == NULL)
2971 return NULL;
2972 res = type->tp_new(subtype, args, kwds);
2973 Py_DECREF(args);
2974 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002975}
2976
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002977static struct PyMethodDef tp_new_methoddef[] = {
2978 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2979 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002980 {0}
2981};
2982
2983static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002984add_tp_new_wrapper(PyTypeObject *type)
2985{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002986 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002987
Guido van Rossum687ae002001-10-15 22:03:32 +00002988 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002989 return 0;
2990 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002991 if (func == NULL)
2992 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002993 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002994}
2995
Guido van Rossumf040ede2001-08-07 16:40:56 +00002996/* Slot wrappers that call the corresponding __foo__ slot. See comments
2997 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002998
Guido van Rossumdc91b992001-08-08 22:26:22 +00002999#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003000static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003001FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003003 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003004 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005}
3006
Guido van Rossumdc91b992001-08-08 22:26:22 +00003007#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003009FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003011 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003012 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013}
3014
Guido van Rossumdc91b992001-08-08 22:26:22 +00003015
3016#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003018FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003020 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003021 int do_other = self->ob_type != other->ob_type && \
3022 other->ob_type->tp_as_number != NULL && \
3023 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003024 if (self->ob_type->tp_as_number != NULL && \
3025 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3026 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003027 if (do_other && \
3028 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3029 r = call_maybe( \
3030 other, ROPSTR, &rcache_str, "(O)", self); \
3031 if (r != Py_NotImplemented) \
3032 return r; \
3033 Py_DECREF(r); \
3034 do_other = 0; \
3035 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003036 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003037 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003038 if (r != Py_NotImplemented || \
3039 other->ob_type == self->ob_type) \
3040 return r; \
3041 Py_DECREF(r); \
3042 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003043 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003044 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003045 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003046 } \
3047 Py_INCREF(Py_NotImplemented); \
3048 return Py_NotImplemented; \
3049}
3050
3051#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3052 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3053
3054#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3055static PyObject * \
3056FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3057{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003058 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003059 return call_method(self, OPSTR, &cache_str, \
3060 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061}
3062
3063static int
3064slot_sq_length(PyObject *self)
3065{
Guido van Rossum2730b132001-08-28 18:22:14 +00003066 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003067 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003068 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069
3070 if (res == NULL)
3071 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003072 len = (int)PyInt_AsLong(res);
3073 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003074 if (len == -1 && PyErr_Occurred())
3075 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003076 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003077 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003078 "__len__() should return >= 0");
3079 return -1;
3080 }
Guido van Rossum26111622001-10-01 16:42:49 +00003081 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003082}
3083
Guido van Rossumdc91b992001-08-08 22:26:22 +00003084SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3085SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003086
3087/* Super-optimized version of slot_sq_item.
3088 Other slots could do the same... */
3089static PyObject *
3090slot_sq_item(PyObject *self, int i)
3091{
3092 static PyObject *getitem_str;
3093 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3094 descrgetfunc f;
3095
3096 if (getitem_str == NULL) {
3097 getitem_str = PyString_InternFromString("__getitem__");
3098 if (getitem_str == NULL)
3099 return NULL;
3100 }
3101 func = _PyType_Lookup(self->ob_type, getitem_str);
3102 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003103 if ((f = func->ob_type->tp_descr_get) == NULL)
3104 Py_INCREF(func);
3105 else
3106 func = f(func, self, (PyObject *)(self->ob_type));
3107 ival = PyInt_FromLong(i);
3108 if (ival != NULL) {
3109 args = PyTuple_New(1);
3110 if (args != NULL) {
3111 PyTuple_SET_ITEM(args, 0, ival);
3112 retval = PyObject_Call(func, args, NULL);
3113 Py_XDECREF(args);
3114 Py_XDECREF(func);
3115 return retval;
3116 }
3117 }
3118 }
3119 else {
3120 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3121 }
3122 Py_XDECREF(args);
3123 Py_XDECREF(ival);
3124 Py_XDECREF(func);
3125 return NULL;
3126}
3127
Guido van Rossumdc91b992001-08-08 22:26:22 +00003128SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129
3130static int
3131slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3132{
3133 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003134 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003135
3136 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003137 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003138 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003139 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003140 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003141 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142 if (res == NULL)
3143 return -1;
3144 Py_DECREF(res);
3145 return 0;
3146}
3147
3148static int
3149slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3150{
3151 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003152 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153
3154 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003155 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003156 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003158 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003159 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003160 if (res == NULL)
3161 return -1;
3162 Py_DECREF(res);
3163 return 0;
3164}
3165
3166static int
3167slot_sq_contains(PyObject *self, PyObject *value)
3168{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003169 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003170 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171
Guido van Rossum55f20992001-10-01 17:18:22 +00003172 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003173
3174 if (func != NULL) {
3175 args = Py_BuildValue("(O)", value);
3176 if (args == NULL)
3177 res = NULL;
3178 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003179 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003180 Py_DECREF(args);
3181 }
3182 Py_DECREF(func);
3183 if (res == NULL)
3184 return -1;
3185 return PyObject_IsTrue(res);
3186 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003187 else if (PyErr_Occurred())
3188 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003189 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003190 return _PySequence_IterSearch(self, value,
3191 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003192 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193}
3194
Guido van Rossumdc91b992001-08-08 22:26:22 +00003195SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3196SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003197
3198#define slot_mp_length slot_sq_length
3199
Guido van Rossumdc91b992001-08-08 22:26:22 +00003200SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003201
3202static int
3203slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3204{
3205 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003206 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003207
3208 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003209 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003210 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003212 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003213 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003214 if (res == NULL)
3215 return -1;
3216 Py_DECREF(res);
3217 return 0;
3218}
3219
Guido van Rossumdc91b992001-08-08 22:26:22 +00003220SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3221SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3222SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3223SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3224SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3225SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3226
Jeremy Hylton938ace62002-07-17 16:30:39 +00003227static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003228
3229SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3230 nb_power, "__pow__", "__rpow__")
3231
3232static PyObject *
3233slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3234{
Guido van Rossum2730b132001-08-28 18:22:14 +00003235 static PyObject *pow_str;
3236
Guido van Rossumdc91b992001-08-08 22:26:22 +00003237 if (modulus == Py_None)
3238 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003239 /* Three-arg power doesn't use __rpow__. But ternary_op
3240 can call this when the second argument's type uses
3241 slot_nb_power, so check before calling self.__pow__. */
3242 if (self->ob_type->tp_as_number != NULL &&
3243 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3244 return call_method(self, "__pow__", &pow_str,
3245 "(OO)", other, modulus);
3246 }
3247 Py_INCREF(Py_NotImplemented);
3248 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003249}
3250
3251SLOT0(slot_nb_negative, "__neg__")
3252SLOT0(slot_nb_positive, "__pos__")
3253SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003254
3255static int
3256slot_nb_nonzero(PyObject *self)
3257{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003258 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003259 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260
Guido van Rossum55f20992001-10-01 17:18:22 +00003261 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003262 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003263 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003264 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003265 func = lookup_maybe(self, "__len__", &len_str);
3266 if (func == NULL) {
3267 if (PyErr_Occurred())
3268 return -1;
3269 else
3270 return 1;
3271 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003272 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003273 res = PyObject_CallObject(func, NULL);
3274 Py_DECREF(func);
3275 if (res == NULL)
3276 return -1;
3277 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003278}
3279
Guido van Rossumdc91b992001-08-08 22:26:22 +00003280SLOT0(slot_nb_invert, "__invert__")
3281SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3282SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3283SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3284SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3285SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003286
3287static int
3288slot_nb_coerce(PyObject **a, PyObject **b)
3289{
3290 static PyObject *coerce_str;
3291 PyObject *self = *a, *other = *b;
3292
3293 if (self->ob_type->tp_as_number != NULL &&
3294 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3295 PyObject *r;
3296 r = call_maybe(
3297 self, "__coerce__", &coerce_str, "(O)", other);
3298 if (r == NULL)
3299 return -1;
3300 if (r == Py_NotImplemented) {
3301 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003302 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003303 else {
3304 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3305 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003306 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003307 Py_DECREF(r);
3308 return -1;
3309 }
3310 *a = PyTuple_GET_ITEM(r, 0);
3311 Py_INCREF(*a);
3312 *b = PyTuple_GET_ITEM(r, 1);
3313 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003314 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003315 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003316 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003317 }
3318 if (other->ob_type->tp_as_number != NULL &&
3319 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3320 PyObject *r;
3321 r = call_maybe(
3322 other, "__coerce__", &coerce_str, "(O)", self);
3323 if (r == NULL)
3324 return -1;
3325 if (r == Py_NotImplemented) {
3326 Py_DECREF(r);
3327 return 1;
3328 }
3329 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3330 PyErr_SetString(PyExc_TypeError,
3331 "__coerce__ didn't return a 2-tuple");
3332 Py_DECREF(r);
3333 return -1;
3334 }
3335 *a = PyTuple_GET_ITEM(r, 1);
3336 Py_INCREF(*a);
3337 *b = PyTuple_GET_ITEM(r, 0);
3338 Py_INCREF(*b);
3339 Py_DECREF(r);
3340 return 0;
3341 }
3342 return 1;
3343}
3344
Guido van Rossumdc91b992001-08-08 22:26:22 +00003345SLOT0(slot_nb_int, "__int__")
3346SLOT0(slot_nb_long, "__long__")
3347SLOT0(slot_nb_float, "__float__")
3348SLOT0(slot_nb_oct, "__oct__")
3349SLOT0(slot_nb_hex, "__hex__")
3350SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3351SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3352SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3353SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3354SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3355SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3356SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3357SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3358SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3359SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3360SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3361SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3362 "__floordiv__", "__rfloordiv__")
3363SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3364SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3365SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366
3367static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003368half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003370 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003371 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003372 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373
Guido van Rossum60718732001-08-28 17:47:51 +00003374 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003375 if (func == NULL) {
3376 PyErr_Clear();
3377 }
3378 else {
3379 args = Py_BuildValue("(O)", other);
3380 if (args == NULL)
3381 res = NULL;
3382 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003383 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003384 Py_DECREF(args);
3385 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003386 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003387 if (res != Py_NotImplemented) {
3388 if (res == NULL)
3389 return -2;
3390 c = PyInt_AsLong(res);
3391 Py_DECREF(res);
3392 if (c == -1 && PyErr_Occurred())
3393 return -2;
3394 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3395 }
3396 Py_DECREF(res);
3397 }
3398 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399}
3400
Guido van Rossumab3b0342001-09-18 20:38:53 +00003401/* This slot is published for the benefit of try_3way_compare in object.c */
3402int
3403_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003404{
3405 int c;
3406
Guido van Rossumab3b0342001-09-18 20:38:53 +00003407 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003408 c = half_compare(self, other);
3409 if (c <= 1)
3410 return c;
3411 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003412 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003413 c = half_compare(other, self);
3414 if (c < -1)
3415 return -2;
3416 if (c <= 1)
3417 return -c;
3418 }
3419 return (void *)self < (void *)other ? -1 :
3420 (void *)self > (void *)other ? 1 : 0;
3421}
3422
3423static PyObject *
3424slot_tp_repr(PyObject *self)
3425{
3426 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003427 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003428
Guido van Rossum60718732001-08-28 17:47:51 +00003429 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003430 if (func != NULL) {
3431 res = PyEval_CallObject(func, NULL);
3432 Py_DECREF(func);
3433 return res;
3434 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003435 PyErr_Clear();
3436 return PyString_FromFormat("<%s object at %p>",
3437 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003438}
3439
3440static PyObject *
3441slot_tp_str(PyObject *self)
3442{
3443 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003444 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003445
Guido van Rossum60718732001-08-28 17:47:51 +00003446 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003447 if (func != NULL) {
3448 res = PyEval_CallObject(func, NULL);
3449 Py_DECREF(func);
3450 return res;
3451 }
3452 else {
3453 PyErr_Clear();
3454 return slot_tp_repr(self);
3455 }
3456}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003457
3458static long
3459slot_tp_hash(PyObject *self)
3460{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003461 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003462 static PyObject *hash_str, *eq_str, *cmp_str;
3463
Tim Peters6d6c1a32001-08-02 04:15:00 +00003464 long h;
3465
Guido van Rossum60718732001-08-28 17:47:51 +00003466 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003467
3468 if (func != NULL) {
3469 res = PyEval_CallObject(func, NULL);
3470 Py_DECREF(func);
3471 if (res == NULL)
3472 return -1;
3473 h = PyInt_AsLong(res);
3474 }
3475 else {
3476 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003477 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003478 if (func == NULL) {
3479 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003480 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003481 }
3482 if (func != NULL) {
3483 Py_DECREF(func);
3484 PyErr_SetString(PyExc_TypeError, "unhashable type");
3485 return -1;
3486 }
3487 PyErr_Clear();
3488 h = _Py_HashPointer((void *)self);
3489 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003490 if (h == -1 && !PyErr_Occurred())
3491 h = -2;
3492 return h;
3493}
3494
3495static PyObject *
3496slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3497{
Guido van Rossum60718732001-08-28 17:47:51 +00003498 static PyObject *call_str;
3499 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500 PyObject *res;
3501
3502 if (meth == NULL)
3503 return NULL;
3504 res = PyObject_Call(meth, args, kwds);
3505 Py_DECREF(meth);
3506 return res;
3507}
3508
Guido van Rossum14a6f832001-10-17 13:59:09 +00003509/* There are two slot dispatch functions for tp_getattro.
3510
3511 - slot_tp_getattro() is used when __getattribute__ is overridden
3512 but no __getattr__ hook is present;
3513
3514 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3515
Guido van Rossumc334df52002-04-04 23:44:47 +00003516 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3517 detects the absence of __getattr__ and then installs the simpler slot if
3518 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003519
Tim Peters6d6c1a32001-08-02 04:15:00 +00003520static PyObject *
3521slot_tp_getattro(PyObject *self, PyObject *name)
3522{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003523 static PyObject *getattribute_str = NULL;
3524 return call_method(self, "__getattribute__", &getattribute_str,
3525 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003526}
3527
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003528static PyObject *
3529slot_tp_getattr_hook(PyObject *self, PyObject *name)
3530{
3531 PyTypeObject *tp = self->ob_type;
3532 PyObject *getattr, *getattribute, *res;
3533 static PyObject *getattribute_str = NULL;
3534 static PyObject *getattr_str = NULL;
3535
3536 if (getattr_str == NULL) {
3537 getattr_str = PyString_InternFromString("__getattr__");
3538 if (getattr_str == NULL)
3539 return NULL;
3540 }
3541 if (getattribute_str == NULL) {
3542 getattribute_str =
3543 PyString_InternFromString("__getattribute__");
3544 if (getattribute_str == NULL)
3545 return NULL;
3546 }
3547 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003548 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003549 /* No __getattr__ hook: use a simpler dispatcher */
3550 tp->tp_getattro = slot_tp_getattro;
3551 return slot_tp_getattro(self, name);
3552 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003553 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003554 if (getattribute == NULL ||
3555 (getattribute->ob_type == &PyWrapperDescr_Type &&
3556 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3557 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003558 res = PyObject_GenericGetAttr(self, name);
3559 else
3560 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003561 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003562 PyErr_Clear();
3563 res = PyObject_CallFunction(getattr, "OO", self, name);
3564 }
3565 return res;
3566}
3567
Tim Peters6d6c1a32001-08-02 04:15:00 +00003568static int
3569slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3570{
3571 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003572 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003573
3574 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003575 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003576 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003578 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003579 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580 if (res == NULL)
3581 return -1;
3582 Py_DECREF(res);
3583 return 0;
3584}
3585
3586/* Map rich comparison operators to their __xx__ namesakes */
3587static char *name_op[] = {
3588 "__lt__",
3589 "__le__",
3590 "__eq__",
3591 "__ne__",
3592 "__gt__",
3593 "__ge__",
3594};
3595
3596static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003597half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003598{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003599 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003600 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003601
Guido van Rossum60718732001-08-28 17:47:51 +00003602 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003603 if (func == NULL) {
3604 PyErr_Clear();
3605 Py_INCREF(Py_NotImplemented);
3606 return Py_NotImplemented;
3607 }
3608 args = Py_BuildValue("(O)", other);
3609 if (args == NULL)
3610 res = NULL;
3611 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003612 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003613 Py_DECREF(args);
3614 }
3615 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616 return res;
3617}
3618
Guido van Rossumb8f63662001-08-15 23:57:02 +00003619/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3620static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3621
3622static PyObject *
3623slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3624{
3625 PyObject *res;
3626
3627 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3628 res = half_richcompare(self, other, op);
3629 if (res != Py_NotImplemented)
3630 return res;
3631 Py_DECREF(res);
3632 }
3633 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3634 res = half_richcompare(other, self, swapped_op[op]);
3635 if (res != Py_NotImplemented) {
3636 return res;
3637 }
3638 Py_DECREF(res);
3639 }
3640 Py_INCREF(Py_NotImplemented);
3641 return Py_NotImplemented;
3642}
3643
3644static PyObject *
3645slot_tp_iter(PyObject *self)
3646{
3647 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003648 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003649
Guido van Rossum60718732001-08-28 17:47:51 +00003650 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003651 if (func != NULL) {
3652 res = PyObject_CallObject(func, NULL);
3653 Py_DECREF(func);
3654 return res;
3655 }
3656 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003657 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003658 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003659 PyErr_SetString(PyExc_TypeError,
3660 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003661 return NULL;
3662 }
3663 Py_DECREF(func);
3664 return PySeqIter_New(self);
3665}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666
3667static PyObject *
3668slot_tp_iternext(PyObject *self)
3669{
Guido van Rossum2730b132001-08-28 18:22:14 +00003670 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003671 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672}
3673
Guido van Rossum1a493502001-08-17 16:47:50 +00003674static PyObject *
3675slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3676{
3677 PyTypeObject *tp = self->ob_type;
3678 PyObject *get;
3679 static PyObject *get_str = NULL;
3680
3681 if (get_str == NULL) {
3682 get_str = PyString_InternFromString("__get__");
3683 if (get_str == NULL)
3684 return NULL;
3685 }
3686 get = _PyType_Lookup(tp, get_str);
3687 if (get == NULL) {
3688 /* Avoid further slowdowns */
3689 if (tp->tp_descr_get == slot_tp_descr_get)
3690 tp->tp_descr_get = NULL;
3691 Py_INCREF(self);
3692 return self;
3693 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003694 if (obj == NULL)
3695 obj = Py_None;
3696 if (type == NULL)
3697 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003698 return PyObject_CallFunction(get, "OOO", self, obj, type);
3699}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003700
3701static int
3702slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3703{
Guido van Rossum2c252392001-08-24 10:13:31 +00003704 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003705 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003706
3707 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003708 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003709 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003710 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003711 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003712 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003713 if (res == NULL)
3714 return -1;
3715 Py_DECREF(res);
3716 return 0;
3717}
3718
3719static int
3720slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3721{
Guido van Rossum60718732001-08-28 17:47:51 +00003722 static PyObject *init_str;
3723 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724 PyObject *res;
3725
3726 if (meth == NULL)
3727 return -1;
3728 res = PyObject_Call(meth, args, kwds);
3729 Py_DECREF(meth);
3730 if (res == NULL)
3731 return -1;
3732 Py_DECREF(res);
3733 return 0;
3734}
3735
3736static PyObject *
3737slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3738{
Guido van Rossum7bed2132002-08-08 21:57:53 +00003739 static PyObject *new_str;
3740 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003741 PyObject *newargs, *x;
3742 int i, n;
3743
Guido van Rossum7bed2132002-08-08 21:57:53 +00003744 if (new_str == NULL) {
3745 new_str = PyString_InternFromString("__new__");
3746 if (new_str == NULL)
3747 return NULL;
3748 }
3749 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750 if (func == NULL)
3751 return NULL;
3752 assert(PyTuple_Check(args));
3753 n = PyTuple_GET_SIZE(args);
3754 newargs = PyTuple_New(n+1);
3755 if (newargs == NULL)
3756 return NULL;
3757 Py_INCREF(type);
3758 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3759 for (i = 0; i < n; i++) {
3760 x = PyTuple_GET_ITEM(args, i);
3761 Py_INCREF(x);
3762 PyTuple_SET_ITEM(newargs, i+1, x);
3763 }
3764 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003765 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003766 Py_DECREF(func);
3767 return x;
3768}
3769
Guido van Rossumfebd61d2002-08-08 20:55:20 +00003770static void
3771slot_tp_del(PyObject *self)
3772{
3773 static PyObject *del_str = NULL;
3774 PyObject *del, *res;
3775 PyObject *error_type, *error_value, *error_traceback;
3776
3777 /* Temporarily resurrect the object. */
3778 assert(self->ob_refcnt == 0);
3779 self->ob_refcnt = 1;
3780
3781 /* Save the current exception, if any. */
3782 PyErr_Fetch(&error_type, &error_value, &error_traceback);
3783
3784 /* Execute __del__ method, if any. */
3785 del = lookup_maybe(self, "__del__", &del_str);
3786 if (del != NULL) {
3787 res = PyEval_CallObject(del, NULL);
3788 if (res == NULL)
3789 PyErr_WriteUnraisable(del);
3790 else
3791 Py_DECREF(res);
3792 Py_DECREF(del);
3793 }
3794
3795 /* Restore the saved exception. */
3796 PyErr_Restore(error_type, error_value, error_traceback);
3797
3798 /* Undo the temporary resurrection; can't use DECREF here, it would
3799 * cause a recursive call.
3800 */
3801 assert(self->ob_refcnt > 0);
3802 if (--self->ob_refcnt == 0)
3803 return; /* this is the normal path out */
3804
3805 /* __del__ resurrected it! Make it look like the original Py_DECREF
3806 * never happened.
3807 */
3808 {
3809 int refcnt = self->ob_refcnt;
3810 _Py_NewReference(self);
3811 self->ob_refcnt = refcnt;
3812 }
3813 assert(!PyType_IS_GC(self->ob_type) ||
3814 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
3815 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
3816 * _Py_NewReference bumped it again, so that's a wash.
3817 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
3818 * chain, so no more to do there either.
3819 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
3820 * _Py_NewReference bumped tp_allocs: both of those need to be
3821 * undone.
3822 */
3823#ifdef COUNT_ALLOCS
3824 --self->ob_type->tp_frees;
3825 --self->ob_type->tp_allocs;
3826#endif
3827}
3828
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003829
3830/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3831 functions. The offsets here are relative to the 'etype' structure, which
3832 incorporates the additional structures used for numbers, sequences and
3833 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3834 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003835 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3836 terminated with an all-zero entry. (This table is further initialized and
3837 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003838
Guido van Rossum6d204072001-10-21 00:44:31 +00003839typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003840
3841#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003842#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003843#undef ETSLOT
3844#undef SQSLOT
3845#undef MPSLOT
3846#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003847#undef UNSLOT
3848#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003849#undef BINSLOT
3850#undef RBINSLOT
3851
Guido van Rossum6d204072001-10-21 00:44:31 +00003852#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00003853 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3854 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003855#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3856 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00003857 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003858#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00003859 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
3860 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00003861#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3862 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3863#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3864 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3865#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3866 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3867#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3868 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3869 "x." NAME "() <==> " DOC)
3870#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3871 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3872 "x." NAME "(y) <==> x" DOC "y")
3873#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3874 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3875 "x." NAME "(y) <==> x" DOC "y")
3876#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3877 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3878 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003879
3880static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003881 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3882 "x.__len__() <==> len(x)"),
3883 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3884 "x.__add__(y) <==> x+y"),
3885 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3886 "x.__mul__(n) <==> x*n"),
3887 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3888 "x.__rmul__(n) <==> n*x"),
3889 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3890 "x.__getitem__(y) <==> x[y]"),
3891 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3892 "x.__getslice__(i, j) <==> x[i:j]"),
3893 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3894 "x.__setitem__(i, y) <==> x[i]=y"),
3895 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3896 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003897 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003898 wrap_intintobjargproc,
3899 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3900 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3901 "x.__delslice__(i, j) <==> del x[i:j]"),
3902 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3903 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003904 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003905 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003906 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003907 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003908
Guido van Rossum6d204072001-10-21 00:44:31 +00003909 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3910 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003911 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003912 wrap_binaryfunc,
3913 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003914 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003915 wrap_objobjargproc,
3916 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003917 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003918 wrap_delitem,
3919 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003920
Guido van Rossum6d204072001-10-21 00:44:31 +00003921 BINSLOT("__add__", nb_add, slot_nb_add,
3922 "+"),
3923 RBINSLOT("__radd__", nb_add, slot_nb_add,
3924 "+"),
3925 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3926 "-"),
3927 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3928 "-"),
3929 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3930 "*"),
3931 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3932 "*"),
3933 BINSLOT("__div__", nb_divide, slot_nb_divide,
3934 "/"),
3935 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3936 "/"),
3937 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3938 "%"),
3939 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3940 "%"),
3941 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3942 "divmod(x, y)"),
3943 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3944 "divmod(y, x)"),
3945 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3946 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3947 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3948 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3949 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3950 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3951 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3952 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003953 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003954 "x != 0"),
3955 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3956 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3957 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3958 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3959 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3960 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3961 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3962 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3963 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3964 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3965 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3966 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3967 "x.__coerce__(y) <==> coerce(x, y)"),
3968 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3969 "int(x)"),
3970 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3971 "long(x)"),
3972 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3973 "float(x)"),
3974 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3975 "oct(x)"),
3976 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3977 "hex(x)"),
3978 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3979 wrap_binaryfunc, "+"),
3980 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3981 wrap_binaryfunc, "-"),
3982 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3983 wrap_binaryfunc, "*"),
3984 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3985 wrap_binaryfunc, "/"),
3986 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3987 wrap_binaryfunc, "%"),
3988 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3989 wrap_ternaryfunc, "**"),
3990 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3991 wrap_binaryfunc, "<<"),
3992 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3993 wrap_binaryfunc, ">>"),
3994 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3995 wrap_binaryfunc, "&"),
3996 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3997 wrap_binaryfunc, "^"),
3998 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3999 wrap_binaryfunc, "|"),
4000 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4001 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4002 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4003 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4004 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4005 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4006 IBSLOT("__itruediv__", nb_inplace_true_divide,
4007 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004008
Guido van Rossum6d204072001-10-21 00:44:31 +00004009 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4010 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004011 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004012 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4013 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004014 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004015 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4016 "x.__cmp__(y) <==> cmp(x,y)"),
4017 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4018 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004019 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4020 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004021 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004022 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4023 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4024 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4025 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4026 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4027 "x.__setattr__('name', value) <==> x.name = value"),
4028 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4029 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4030 "x.__delattr__('name') <==> del x.name"),
4031 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4032 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4033 "x.__lt__(y) <==> x<y"),
4034 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4035 "x.__le__(y) <==> x<=y"),
4036 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4037 "x.__eq__(y) <==> x==y"),
4038 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4039 "x.__ne__(y) <==> x!=y"),
4040 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4041 "x.__gt__(y) <==> x>y"),
4042 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4043 "x.__ge__(y) <==> x>=y"),
4044 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4045 "x.__iter__() <==> iter(x)"),
4046 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4047 "x.next() -> the next value, or raise StopIteration"),
4048 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4049 "descr.__get__(obj[, type]) -> value"),
4050 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4051 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004052 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4053 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004054 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004055 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004056 "see x.__class__.__doc__ for signature",
4057 PyWrapperFlag_KEYWORDS),
4058 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004059 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004060 {NULL}
4061};
4062
Guido van Rossumc334df52002-04-04 23:44:47 +00004063/* Given a type pointer and an offset gotten from a slotdef entry, return a
4064 pointer to the actual slot. This is not quite the same as simply adding
4065 the offset to the type pointer, since it takes care to indirect through the
4066 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4067 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004068static void **
4069slotptr(PyTypeObject *type, int offset)
4070{
4071 char *ptr;
4072
Guido van Rossum09638c12002-06-13 19:17:46 +00004073 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004074 assert(offset >= 0);
4075 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004076 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004077 ptr = (void *)type->tp_as_sequence;
4078 offset -= offsetof(etype, as_sequence);
4079 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004080 else if (offset >= offsetof(etype, as_mapping)) {
4081 ptr = (void *)type->tp_as_mapping;
4082 offset -= offsetof(etype, as_mapping);
4083 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004084 else if (offset >= offsetof(etype, as_number)) {
4085 ptr = (void *)type->tp_as_number;
4086 offset -= offsetof(etype, as_number);
4087 }
4088 else {
4089 ptr = (void *)type;
4090 }
4091 if (ptr != NULL)
4092 ptr += offset;
4093 return (void **)ptr;
4094}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004095
Guido van Rossumc334df52002-04-04 23:44:47 +00004096/* Length of array of slotdef pointers used to store slots with the
4097 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4098 the same __name__, for any __name__. Since that's a static property, it is
4099 appropriate to declare fixed-size arrays for this. */
4100#define MAX_EQUIV 10
4101
4102/* Return a slot pointer for a given name, but ONLY if the attribute has
4103 exactly one slot function. The name must be an interned string. */
4104static void **
4105resolve_slotdups(PyTypeObject *type, PyObject *name)
4106{
4107 /* XXX Maybe this could be optimized more -- but is it worth it? */
4108
4109 /* pname and ptrs act as a little cache */
4110 static PyObject *pname;
4111 static slotdef *ptrs[MAX_EQUIV];
4112 slotdef *p, **pp;
4113 void **res, **ptr;
4114
4115 if (pname != name) {
4116 /* Collect all slotdefs that match name into ptrs. */
4117 pname = name;
4118 pp = ptrs;
4119 for (p = slotdefs; p->name_strobj; p++) {
4120 if (p->name_strobj == name)
4121 *pp++ = p;
4122 }
4123 *pp = NULL;
4124 }
4125
4126 /* Look in all matching slots of the type; if exactly one of these has
4127 a filled-in slot, return its value. Otherwise return NULL. */
4128 res = NULL;
4129 for (pp = ptrs; *pp; pp++) {
4130 ptr = slotptr(type, (*pp)->offset);
4131 if (ptr == NULL || *ptr == NULL)
4132 continue;
4133 if (res != NULL)
4134 return NULL;
4135 res = ptr;
4136 }
4137 return res;
4138}
4139
4140/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4141 does some incredibly complex thinking and then sticks something into the
4142 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4143 interests, and then stores a generic wrapper or a specific function into
4144 the slot.) Return a pointer to the next slotdef with a different offset,
4145 because that's convenient for fixup_slot_dispatchers(). */
4146static slotdef *
4147update_one_slot(PyTypeObject *type, slotdef *p)
4148{
4149 PyObject *descr;
4150 PyWrapperDescrObject *d;
4151 void *generic = NULL, *specific = NULL;
4152 int use_generic = 0;
4153 int offset = p->offset;
4154 void **ptr = slotptr(type, offset);
4155
4156 if (ptr == NULL) {
4157 do {
4158 ++p;
4159 } while (p->offset == offset);
4160 return p;
4161 }
4162 do {
4163 descr = _PyType_Lookup(type, p->name_strobj);
4164 if (descr == NULL)
4165 continue;
4166 if (descr->ob_type == &PyWrapperDescr_Type) {
4167 void **tptr = resolve_slotdups(type, p->name_strobj);
4168 if (tptr == NULL || tptr == ptr)
4169 generic = p->function;
4170 d = (PyWrapperDescrObject *)descr;
4171 if (d->d_base->wrapper == p->wrapper &&
4172 PyType_IsSubtype(type, d->d_type))
4173 {
4174 if (specific == NULL ||
4175 specific == d->d_wrapped)
4176 specific = d->d_wrapped;
4177 else
4178 use_generic = 1;
4179 }
4180 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004181 else if (descr->ob_type == &PyCFunction_Type &&
4182 PyCFunction_GET_FUNCTION(descr) ==
4183 (PyCFunction)tp_new_wrapper &&
4184 strcmp(p->name, "__new__") == 0)
4185 {
4186 /* The __new__ wrapper is not a wrapper descriptor,
4187 so must be special-cased differently.
4188 If we don't do this, creating an instance will
4189 always use slot_tp_new which will look up
4190 __new__ in the MRO which will call tp_new_wrapper
4191 which will look through the base classes looking
4192 for a static base and call its tp_new (usually
4193 PyType_GenericNew), after performing various
4194 sanity checks and constructing a new argument
4195 list. Cut all that nonsense short -- this speeds
4196 up instance creation tremendously. */
4197 specific = type->tp_new;
4198 /* XXX I'm not 100% sure that there isn't a hole
4199 in this reasoning that requires additional
4200 sanity checks. I'll buy the first person to
4201 point out a bug in this reasoning a beer. */
4202 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004203 else {
4204 use_generic = 1;
4205 generic = p->function;
4206 }
4207 } while ((++p)->offset == offset);
4208 if (specific && !use_generic)
4209 *ptr = specific;
4210 else
4211 *ptr = generic;
4212 return p;
4213}
4214
Guido van Rossum22b13872002-08-06 21:41:44 +00004215static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004216 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004217
Guido van Rossumc334df52002-04-04 23:44:47 +00004218/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4219 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004220static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004221update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004222{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004223 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004224
Guido van Rossumc334df52002-04-04 23:44:47 +00004225 for (pp = pp0; *pp; pp++)
4226 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004227 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004228}
4229
Guido van Rossumc334df52002-04-04 23:44:47 +00004230/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4231 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004232static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004233recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004234{
4235 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004236 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004237 int i, n;
4238
4239 subclasses = type->tp_subclasses;
4240 if (subclasses == NULL)
4241 return 0;
4242 assert(PyList_Check(subclasses));
4243 n = PyList_GET_SIZE(subclasses);
4244 for (i = 0; i < n; i++) {
4245 ref = PyList_GET_ITEM(subclasses, i);
4246 assert(PyWeakref_CheckRef(ref));
4247 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004248 assert(subclass != NULL);
4249 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004250 continue;
4251 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004252 /* Avoid recursing down into unaffected classes */
4253 dict = subclass->tp_dict;
4254 if (dict != NULL && PyDict_Check(dict) &&
4255 PyDict_GetItem(dict, name) != NULL)
4256 continue;
4257 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004258 return -1;
4259 }
4260 return 0;
4261}
4262
Guido van Rossumc334df52002-04-04 23:44:47 +00004263/* Comparison function for qsort() to compare slotdefs by their offset, and
4264 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004265static int
4266slotdef_cmp(const void *aa, const void *bb)
4267{
4268 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4269 int c = a->offset - b->offset;
4270 if (c != 0)
4271 return c;
4272 else
4273 return a - b;
4274}
4275
Guido van Rossumc334df52002-04-04 23:44:47 +00004276/* Initialize the slotdefs table by adding interned string objects for the
4277 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004278static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004279init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004280{
4281 slotdef *p;
4282 static int initialized = 0;
4283
4284 if (initialized)
4285 return;
4286 for (p = slotdefs; p->name; p++) {
4287 p->name_strobj = PyString_InternFromString(p->name);
4288 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004289 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004290 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004291 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4292 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004293 initialized = 1;
4294}
4295
Guido van Rossumc334df52002-04-04 23:44:47 +00004296/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004297static int
4298update_slot(PyTypeObject *type, PyObject *name)
4299{
Guido van Rossumc334df52002-04-04 23:44:47 +00004300 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004301 slotdef *p;
4302 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004303 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004304
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004305 init_slotdefs();
4306 pp = ptrs;
4307 for (p = slotdefs; p->name; p++) {
4308 /* XXX assume name is interned! */
4309 if (p->name_strobj == name)
4310 *pp++ = p;
4311 }
4312 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004313 for (pp = ptrs; *pp; pp++) {
4314 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004315 offset = p->offset;
4316 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004317 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004318 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004319 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004320 if (ptrs[0] == NULL)
4321 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004322 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004323}
4324
Guido van Rossumc334df52002-04-04 23:44:47 +00004325/* Store the proper functions in the slot dispatches at class (type)
4326 definition time, based upon which operations the class overrides in its
4327 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004328static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004329fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004330{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004331 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004333 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004334 for (p = slotdefs; p->name; )
4335 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004337
Guido van Rossum6d204072001-10-21 00:44:31 +00004338/* This function is called by PyType_Ready() to populate the type's
4339 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004340 function slot (like tp_repr) that's defined in the type, one or more
4341 corresponding descriptors are added in the type's tp_dict dictionary
4342 under the appropriate name (like __repr__). Some function slots
4343 cause more than one descriptor to be added (for example, the nb_add
4344 slot adds both __add__ and __radd__ descriptors) and some function
4345 slots compete for the same descriptor (for example both sq_item and
4346 mp_subscript generate a __getitem__ descriptor).
4347
4348 In the latter case, the first slotdef entry encoutered wins. Since
4349 slotdef entries are sorted by the offset of the slot in the etype
4350 struct, this gives us some control over disambiguating between
4351 competing slots: the members of struct etype are listed from most
4352 general to least general, so the most general slot is preferred. In
4353 particular, because as_mapping comes before as_sequence, for a type
4354 that defines both mp_subscript and sq_item, mp_subscript wins.
4355
4356 This only adds new descriptors and doesn't overwrite entries in
4357 tp_dict that were previously defined. The descriptors contain a
4358 reference to the C function they must call, so that it's safe if they
4359 are copied into a subtype's __dict__ and the subtype has a different
4360 C function in its slot -- calling the method defined by the
4361 descriptor will call the C function that was used to create it,
4362 rather than the C function present in the slot when it is called.
4363 (This is important because a subtype may have a C function in the
4364 slot that calls the method from the dictionary, and we want to avoid
4365 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004366
4367static int
4368add_operators(PyTypeObject *type)
4369{
4370 PyObject *dict = type->tp_dict;
4371 slotdef *p;
4372 PyObject *descr;
4373 void **ptr;
4374
4375 init_slotdefs();
4376 for (p = slotdefs; p->name; p++) {
4377 if (p->wrapper == NULL)
4378 continue;
4379 ptr = slotptr(type, p->offset);
4380 if (!ptr || !*ptr)
4381 continue;
4382 if (PyDict_GetItem(dict, p->name_strobj))
4383 continue;
4384 descr = PyDescr_NewWrapper(type, p, *ptr);
4385 if (descr == NULL)
4386 return -1;
4387 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4388 return -1;
4389 Py_DECREF(descr);
4390 }
4391 if (type->tp_new != NULL) {
4392 if (add_tp_new_wrapper(type) < 0)
4393 return -1;
4394 }
4395 return 0;
4396}
4397
Guido van Rossum705f0f52001-08-24 16:47:00 +00004398
4399/* Cooperative 'super' */
4400
4401typedef struct {
4402 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004403 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004404 PyObject *obj;
4405} superobject;
4406
Guido van Rossum6f799372001-09-20 20:46:19 +00004407static PyMemberDef super_members[] = {
4408 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4409 "the class invoking super()"},
4410 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4411 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004412 {0}
4413};
4414
Guido van Rossum705f0f52001-08-24 16:47:00 +00004415static void
4416super_dealloc(PyObject *self)
4417{
4418 superobject *su = (superobject *)self;
4419
Guido van Rossum048eb752001-10-02 21:24:57 +00004420 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004421 Py_XDECREF(su->obj);
4422 Py_XDECREF(su->type);
4423 self->ob_type->tp_free(self);
4424}
4425
4426static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004427super_repr(PyObject *self)
4428{
4429 superobject *su = (superobject *)self;
4430
4431 if (su->obj)
4432 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004433 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004434 su->type ? su->type->tp_name : "NULL",
4435 su->obj->ob_type->tp_name);
4436 else
4437 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004438 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004439 su->type ? su->type->tp_name : "NULL");
4440}
4441
4442static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004443super_getattro(PyObject *self, PyObject *name)
4444{
4445 superobject *su = (superobject *)self;
4446
4447 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004448 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004449 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004450 descrgetfunc f;
4451 int i, n;
4452
Guido van Rossum155db9a2002-04-02 17:53:47 +00004453 starttype = su->obj->ob_type;
4454 mro = starttype->tp_mro;
4455
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004456 if (mro == NULL)
4457 n = 0;
4458 else {
4459 assert(PyTuple_Check(mro));
4460 n = PyTuple_GET_SIZE(mro);
4461 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004462 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004463 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004464 break;
4465 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004466 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004467 starttype = (PyTypeObject *)(su->obj);
4468 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004469 if (mro == NULL)
4470 n = 0;
4471 else {
4472 assert(PyTuple_Check(mro));
4473 n = PyTuple_GET_SIZE(mro);
4474 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004475 for (i = 0; i < n; i++) {
4476 if ((PyObject *)(su->type) ==
4477 PyTuple_GET_ITEM(mro, i))
4478 break;
4479 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004480 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004481 i++;
4482 res = NULL;
4483 for (; i < n; i++) {
4484 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004485 if (PyType_Check(tmp))
4486 dict = ((PyTypeObject *)tmp)->tp_dict;
4487 else if (PyClass_Check(tmp))
4488 dict = ((PyClassObject *)tmp)->cl_dict;
4489 else
4490 continue;
4491 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004492 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004493 Py_INCREF(res);
4494 f = res->ob_type->tp_descr_get;
4495 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004496 tmp = f(res, su->obj,
4497 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004498 Py_DECREF(res);
4499 res = tmp;
4500 }
4501 return res;
4502 }
4503 }
4504 }
4505 return PyObject_GenericGetAttr(self, name);
4506}
4507
Guido van Rossum5b443c62001-12-03 15:38:28 +00004508static int
4509supercheck(PyTypeObject *type, PyObject *obj)
4510{
4511 if (!PyType_IsSubtype(obj->ob_type, type) &&
4512 !(PyType_Check(obj) &&
4513 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4514 PyErr_SetString(PyExc_TypeError,
4515 "super(type, obj): "
4516 "obj must be an instance or subtype of type");
4517 return -1;
4518 }
4519 else
4520 return 0;
4521}
4522
Guido van Rossum705f0f52001-08-24 16:47:00 +00004523static PyObject *
4524super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4525{
4526 superobject *su = (superobject *)self;
4527 superobject *new;
4528
4529 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4530 /* Not binding to an object, or already bound */
4531 Py_INCREF(self);
4532 return self;
4533 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004534 if (su->ob_type != &PySuper_Type)
4535 /* If su is an instance of a subclass of super,
4536 call its type */
4537 return PyObject_CallFunction((PyObject *)su->ob_type,
4538 "OO", su->type, obj);
4539 else {
4540 /* Inline the common case */
4541 if (supercheck(su->type, obj) < 0)
4542 return NULL;
4543 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4544 NULL, NULL);
4545 if (new == NULL)
4546 return NULL;
4547 Py_INCREF(su->type);
4548 Py_INCREF(obj);
4549 new->type = su->type;
4550 new->obj = obj;
4551 return (PyObject *)new;
4552 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004553}
4554
4555static int
4556super_init(PyObject *self, PyObject *args, PyObject *kwds)
4557{
4558 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004559 PyTypeObject *type;
4560 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004561
4562 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4563 return -1;
4564 if (obj == Py_None)
4565 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004566 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004567 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004568 Py_INCREF(type);
4569 Py_XINCREF(obj);
4570 su->type = type;
4571 su->obj = obj;
4572 return 0;
4573}
4574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004575PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004576"super(type) -> unbound super object\n"
4577"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004578"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004579"Typical use to call a cooperative superclass method:\n"
4580"class C(B):\n"
4581" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004582" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004583
Guido van Rossum048eb752001-10-02 21:24:57 +00004584static int
4585super_traverse(PyObject *self, visitproc visit, void *arg)
4586{
4587 superobject *su = (superobject *)self;
4588 int err;
4589
4590#define VISIT(SLOT) \
4591 if (SLOT) { \
4592 err = visit((PyObject *)(SLOT), arg); \
4593 if (err) \
4594 return err; \
4595 }
4596
4597 VISIT(su->obj);
4598 VISIT(su->type);
4599
4600#undef VISIT
4601
4602 return 0;
4603}
4604
Guido van Rossum705f0f52001-08-24 16:47:00 +00004605PyTypeObject PySuper_Type = {
4606 PyObject_HEAD_INIT(&PyType_Type)
4607 0, /* ob_size */
4608 "super", /* tp_name */
4609 sizeof(superobject), /* tp_basicsize */
4610 0, /* tp_itemsize */
4611 /* methods */
4612 super_dealloc, /* tp_dealloc */
4613 0, /* tp_print */
4614 0, /* tp_getattr */
4615 0, /* tp_setattr */
4616 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004617 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004618 0, /* tp_as_number */
4619 0, /* tp_as_sequence */
4620 0, /* tp_as_mapping */
4621 0, /* tp_hash */
4622 0, /* tp_call */
4623 0, /* tp_str */
4624 super_getattro, /* tp_getattro */
4625 0, /* tp_setattro */
4626 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004627 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4628 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004629 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004630 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004631 0, /* tp_clear */
4632 0, /* tp_richcompare */
4633 0, /* tp_weaklistoffset */
4634 0, /* tp_iter */
4635 0, /* tp_iternext */
4636 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004637 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004638 0, /* tp_getset */
4639 0, /* tp_base */
4640 0, /* tp_dict */
4641 super_descr_get, /* tp_descr_get */
4642 0, /* tp_descr_set */
4643 0, /* tp_dictoffset */
4644 super_init, /* tp_init */
4645 PyType_GenericAlloc, /* tp_alloc */
4646 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004647 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004648};