blob: edf4e7044d6d66e75ccf10c91c387baadfa6dc56 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
35 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
36 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
37 {0}
38};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000039
Guido van Rossumc0b618a1997-05-02 03:12:38 +000040static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000041type_name(PyTypeObject *type, void *context)
42{
43 char *s;
44
45 s = strrchr(type->tp_name, '.');
46 if (s == NULL)
47 s = type->tp_name;
48 else
49 s++;
50 return PyString_FromString(s);
51}
52
53static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000054type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000055{
Guido van Rossumc3542212001-08-16 09:18:56 +000056 PyObject *mod;
57 char *s;
58
59 s = strrchr(type->tp_name, '.');
60 if (s != NULL)
61 return PyString_FromStringAndSize(type->tp_name,
62 (int)(s - type->tp_name));
63 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
64 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000065 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000066 if (mod != NULL && PyString_Check(mod)) {
67 Py_INCREF(mod);
68 return mod;
69 }
70 PyErr_SetString(PyExc_AttributeError, "__module__");
71 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000072}
73
Guido van Rossum3926a632001-09-25 16:25:58 +000074static int
75type_set_module(PyTypeObject *type, PyObject *value, void *context)
76{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000077 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000078 strrchr(type->tp_name, '.')) {
79 PyErr_Format(PyExc_TypeError,
80 "can't set %s.__module__", type->tp_name);
81 return -1;
82 }
83 if (!value) {
84 PyErr_Format(PyExc_TypeError,
85 "can't delete %s.__module__", type->tp_name);
86 return -1;
87 }
88 return PyDict_SetItemString(type->tp_dict, "__module__", value);
89}
90
Tim Peters6d6c1a32001-08-02 04:15:00 +000091static PyObject *
92type_dict(PyTypeObject *type, void *context)
93{
94 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095 Py_INCREF(Py_None);
96 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000098 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000099}
100
Tim Peters24008312002-03-17 18:56:20 +0000101static PyObject *
102type_get_doc(PyTypeObject *type, void *context)
103{
104 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000106 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000107 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000108 if (result == NULL) {
109 result = Py_None;
110 Py_INCREF(result);
111 }
112 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000113 result = result->ob_type->tp_descr_get(result, NULL,
114 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000115 }
116 else {
117 Py_INCREF(result);
118 }
Tim Peters24008312002-03-17 18:56:20 +0000119 return result;
120}
121
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000122static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000123 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000125 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000126 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000127 {0}
128};
129
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000130static int
131type_compare(PyObject *v, PyObject *w)
132{
133 /* This is called with type objects only. So we
134 can just compare the addresses. */
135 Py_uintptr_t vv = (Py_uintptr_t)v;
136 Py_uintptr_t ww = (Py_uintptr_t)w;
137 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
138}
139
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000140static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000141type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000143 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000144 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000145
146 mod = type_module(type, NULL);
147 if (mod == NULL)
148 PyErr_Clear();
149 else if (!PyString_Check(mod)) {
150 Py_DECREF(mod);
151 mod = NULL;
152 }
153 name = type_name(type, NULL);
154 if (name == NULL)
155 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000156
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000157 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
158 kind = "class";
159 else
160 kind = "type";
161
Barry Warsaw7ce36942001-08-24 18:34:26 +0000162 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000163 rtn = PyString_FromFormat("<%s '%s.%s'>",
164 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000165 PyString_AS_STRING(mod),
166 PyString_AS_STRING(name));
167 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000168 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000169 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000170
Guido van Rossumc3542212001-08-16 09:18:56 +0000171 Py_XDECREF(mod);
172 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000173 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Tim Peters6d6c1a32001-08-02 04:15:00 +0000176static PyObject *
177type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
178{
179 PyObject *obj;
180
181 if (type->tp_new == NULL) {
182 PyErr_Format(PyExc_TypeError,
183 "cannot create '%.100s' instances",
184 type->tp_name);
185 return NULL;
186 }
187
Tim Peters3f996e72001-09-13 19:18:27 +0000188 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000189 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000190 /* Ugly exception: when the call was type(something),
191 don't call tp_init on the result. */
192 if (type == &PyType_Type &&
193 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
194 (kwds == NULL ||
195 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
196 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000197 /* If the returned object is not an instance of type,
198 it won't be initialized. */
199 if (!PyType_IsSubtype(obj->ob_type, type))
200 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000202 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
203 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000204 type->tp_init(obj, args, kwds) < 0) {
205 Py_DECREF(obj);
206 obj = NULL;
207 }
208 }
209 return obj;
210}
211
212PyObject *
213PyType_GenericAlloc(PyTypeObject *type, int nitems)
214{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000216 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000217
218 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000219 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000220 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000221 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000222
Neil Schemenauerc806c882001-08-29 23:54:54 +0000223 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000224 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000225
Neil Schemenauerc806c882001-08-29 23:54:54 +0000226 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000227
Tim Peters6d6c1a32001-08-02 04:15:00 +0000228 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
229 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000230
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231 if (type->tp_itemsize == 0)
232 PyObject_INIT(obj, type);
233 else
234 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000235
Tim Peters6d6c1a32001-08-02 04:15:00 +0000236 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000237 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000238 return obj;
239}
240
241PyObject *
242PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
243{
244 return type->tp_alloc(type, 0);
245}
246
Guido van Rossum9475a232001-10-05 20:51:39 +0000247/* Helpers for subtyping */
248
249static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000250traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
251{
252 int i, n;
253 PyMemberDef *mp;
254
255 n = type->ob_size;
256 mp = ((etype *)type)->members;
257 for (i = 0; i < n; i++, mp++) {
258 if (mp->type == T_OBJECT_EX) {
259 char *addr = (char *)self + mp->offset;
260 PyObject *obj = *(PyObject **)addr;
261 if (obj != NULL) {
262 int err = visit(obj, arg);
263 if (err)
264 return err;
265 }
266 }
267 }
268 return 0;
269}
270
271static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000272subtype_traverse(PyObject *self, visitproc visit, void *arg)
273{
274 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000275 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000276
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000277 /* Find the nearest base with a different tp_traverse,
278 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000279 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000280 base = type;
281 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
282 if (base->ob_size) {
283 int err = traverse_slots(base, self, visit, arg);
284 if (err)
285 return err;
286 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000287 base = base->tp_base;
288 assert(base);
289 }
290
291 if (type->tp_dictoffset != base->tp_dictoffset) {
292 PyObject **dictptr = _PyObject_GetDictPtr(self);
293 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000294 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000295 if (err)
296 return err;
297 }
298 }
299
Guido van Rossuma3862092002-06-10 15:24:42 +0000300 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
301 /* For a heaptype, the instances count as references
302 to the type. Traverse the type so the collector
303 can find cycles involving this link. */
304 int err = visit((PyObject *)type, arg);
305 if (err)
306 return err;
307 }
308
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000309 if (basetraverse)
310 return basetraverse(self, visit, arg);
311 return 0;
312}
313
314static void
315clear_slots(PyTypeObject *type, PyObject *self)
316{
317 int i, n;
318 PyMemberDef *mp;
319
320 n = type->ob_size;
321 mp = ((etype *)type)->members;
322 for (i = 0; i < n; i++, mp++) {
323 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
324 char *addr = (char *)self + mp->offset;
325 PyObject *obj = *(PyObject **)addr;
326 if (obj != NULL) {
327 Py_DECREF(obj);
328 *(PyObject **)addr = NULL;
329 }
330 }
331 }
332}
333
334static int
335subtype_clear(PyObject *self)
336{
337 PyTypeObject *type, *base;
338 inquiry baseclear;
339
340 /* Find the nearest base with a different tp_clear
341 and clear slots while we're at it */
342 type = self->ob_type;
343 base = type;
344 while ((baseclear = base->tp_clear) == subtype_clear) {
345 if (base->ob_size)
346 clear_slots(base, self);
347 base = base->tp_base;
348 assert(base);
349 }
350
Guido van Rossuma3862092002-06-10 15:24:42 +0000351 /* There's no need to clear the instance dict (if any);
352 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000353
354 if (baseclear)
355 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000356 return 0;
357}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000358
359static void
360subtype_dealloc(PyObject *self)
361{
Guido van Rossum14227b42001-12-06 02:35:58 +0000362 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000363 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000364
Guido van Rossum22b13872002-08-06 21:41:44 +0000365 /* Extract the type; we expect it to be a heap type */
366 type = self->ob_type;
367 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368
Guido van Rossum22b13872002-08-06 21:41:44 +0000369 /* Test whether the type has GC exactly once */
370
371 if (!PyType_IS_GC(type)) {
372 /* It's really rare to find a dynamic type that doesn't have
373 GC; it can only happen when deriving from 'object' and not
374 adding any slots or instance variables. This allows
375 certain simplifications: there's no need to call
376 clear_slots(), or DECREF the dict, or clear weakrefs. */
377
378 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000379 if (type->tp_del) {
380 type->tp_del(self);
381 if (self->ob_refcnt > 0)
382 return;
383 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000384
385 /* Find the nearest base with a different tp_dealloc */
386 base = type;
387 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
388 assert(base->ob_size == 0);
389 base = base->tp_base;
390 assert(base);
391 }
392
393 /* Call the base tp_dealloc() */
394 assert(basedealloc);
395 basedealloc(self);
396
397 /* Can't reference self beyond this point */
398 Py_DECREF(type);
399
400 /* Done */
401 return;
402 }
403
404 /* We get here only if the type has GC */
405
406 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000407 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000408 Py_TRASHCAN_SAFE_BEGIN(self);
409 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
410
411 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000412 if (type->tp_del) {
413 type->tp_del(self);
414 if (self->ob_refcnt > 0)
415 goto endlabel;
416 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000417
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000418 /* Find the nearest base with a different tp_dealloc
419 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000420 base = type;
421 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
422 if (base->ob_size)
423 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 base = base->tp_base;
425 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000426 }
427
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000429 if (type->tp_dictoffset && !base->tp_dictoffset) {
430 PyObject **dictptr = _PyObject_GetDictPtr(self);
431 if (dictptr != NULL) {
432 PyObject *dict = *dictptr;
433 if (dict != NULL) {
434 Py_DECREF(dict);
435 *dictptr = NULL;
436 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 }
438 }
439
Guido van Rossum9676b222001-08-17 20:32:36 +0000440 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000441 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000442 PyObject_ClearWeakRefs(self);
443
Tim Peters6d6c1a32001-08-02 04:15:00 +0000444 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000445 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000446 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447
448 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000449 assert(basedealloc);
450 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451
452 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000453 Py_DECREF(type);
454
Guido van Rossum0906e072002-08-07 20:42:09 +0000455 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000456 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000457}
458
Jeremy Hylton938ace62002-07-17 16:30:39 +0000459static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461/* type test with subclassing support */
462
463int
464PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
465{
466 PyObject *mro;
467
Guido van Rossum9478d072001-09-07 18:52:13 +0000468 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
469 return b == a || b == &PyBaseObject_Type;
470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471 mro = a->tp_mro;
472 if (mro != NULL) {
473 /* Deal with multiple inheritance without recursion
474 by walking the MRO tuple */
475 int i, n;
476 assert(PyTuple_Check(mro));
477 n = PyTuple_GET_SIZE(mro);
478 for (i = 0; i < n; i++) {
479 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
480 return 1;
481 }
482 return 0;
483 }
484 else {
485 /* a is not completely initilized yet; follow tp_base */
486 do {
487 if (a == b)
488 return 1;
489 a = a->tp_base;
490 } while (a != NULL);
491 return b == &PyBaseObject_Type;
492 }
493}
494
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000495/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000496 without looking in the instance dictionary
497 (so we can't use PyObject_GetAttr) but still binding
498 it to the instance. The arguments are the object,
499 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000500 static variable used to cache the interned Python string.
501
502 Two variants:
503
504 - lookup_maybe() returns NULL without raising an exception
505 when the _PyType_Lookup() call fails;
506
507 - lookup_method() always raises an exception upon errors.
508*/
Guido van Rossum60718732001-08-28 17:47:51 +0000509
510static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000511lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000512{
513 PyObject *res;
514
515 if (*attrobj == NULL) {
516 *attrobj = PyString_InternFromString(attrstr);
517 if (*attrobj == NULL)
518 return NULL;
519 }
520 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000521 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000522 descrgetfunc f;
523 if ((f = res->ob_type->tp_descr_get) == NULL)
524 Py_INCREF(res);
525 else
526 res = f(res, self, (PyObject *)(self->ob_type));
527 }
528 return res;
529}
530
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000531static PyObject *
532lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
533{
534 PyObject *res = lookup_maybe(self, attrstr, attrobj);
535 if (res == NULL && !PyErr_Occurred())
536 PyErr_SetObject(PyExc_AttributeError, *attrobj);
537 return res;
538}
539
Guido van Rossum2730b132001-08-28 18:22:14 +0000540/* A variation of PyObject_CallMethod that uses lookup_method()
541 instead of PyObject_GetAttrString(). This uses the same convention
542 as lookup_method to cache the interned name string object. */
543
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000544static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000545call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
546{
547 va_list va;
548 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000549 va_start(va, format);
550
Guido van Rossumda21c012001-10-03 00:50:18 +0000551 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000552 if (func == NULL) {
553 va_end(va);
554 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000555 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000556 return NULL;
557 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000558
559 if (format && *format)
560 args = Py_VaBuildValue(format, va);
561 else
562 args = PyTuple_New(0);
563
564 va_end(va);
565
566 if (args == NULL)
567 return NULL;
568
569 assert(PyTuple_Check(args));
570 retval = PyObject_Call(func, args, NULL);
571
572 Py_DECREF(args);
573 Py_DECREF(func);
574
575 return retval;
576}
577
578/* Clone of call_method() that returns NotImplemented when the lookup fails. */
579
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000580static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000581call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
582{
583 va_list va;
584 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000585 va_start(va, format);
586
Guido van Rossumda21c012001-10-03 00:50:18 +0000587 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000588 if (func == NULL) {
589 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000590 if (!PyErr_Occurred()) {
591 Py_INCREF(Py_NotImplemented);
592 return Py_NotImplemented;
593 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000594 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000595 }
596
597 if (format && *format)
598 args = Py_VaBuildValue(format, va);
599 else
600 args = PyTuple_New(0);
601
602 va_end(va);
603
Guido van Rossum717ce002001-09-14 16:58:08 +0000604 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000605 return NULL;
606
Guido van Rossum717ce002001-09-14 16:58:08 +0000607 assert(PyTuple_Check(args));
608 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000609
610 Py_DECREF(args);
611 Py_DECREF(func);
612
613 return retval;
614}
615
Tim Peters6d6c1a32001-08-02 04:15:00 +0000616/* Method resolution order algorithm from "Putting Metaclasses to Work"
617 by Forman and Danforth (Addison-Wesley 1999). */
618
619static int
620conservative_merge(PyObject *left, PyObject *right)
621{
622 int left_size;
623 int right_size;
624 int i, j, r, ok;
625 PyObject *temp, *rr;
626
627 assert(PyList_Check(left));
628 assert(PyList_Check(right));
629
630 again:
631 left_size = PyList_GET_SIZE(left);
632 right_size = PyList_GET_SIZE(right);
633 for (i = 0; i < left_size; i++) {
634 for (j = 0; j < right_size; j++) {
635 if (PyList_GET_ITEM(left, i) ==
636 PyList_GET_ITEM(right, j)) {
637 /* found a merge point */
638 temp = PyList_New(0);
639 if (temp == NULL)
640 return -1;
641 for (r = 0; r < j; r++) {
642 rr = PyList_GET_ITEM(right, r);
643 ok = PySequence_Contains(left, rr);
644 if (ok < 0) {
645 Py_DECREF(temp);
646 return -1;
647 }
648 if (!ok) {
649 ok = PyList_Append(temp, rr);
650 if (ok < 0) {
651 Py_DECREF(temp);
652 return -1;
653 }
654 }
655 }
656 ok = PyList_SetSlice(left, i, i, temp);
657 Py_DECREF(temp);
658 if (ok < 0)
659 return -1;
660 ok = PyList_SetSlice(right, 0, j+1, NULL);
661 if (ok < 0)
662 return -1;
663 goto again;
664 }
665 }
666 }
667 return PyList_SetSlice(left, left_size, left_size, right);
668}
669
670static int
671serious_order_disagreements(PyObject *left, PyObject *right)
672{
673 return 0; /* XXX later -- for now, we cheat: "don't do that" */
674}
675
Tim Petersa91e9642001-11-14 23:32:33 +0000676static int
677fill_classic_mro(PyObject *mro, PyObject *cls)
678{
679 PyObject *bases, *base;
680 int i, n;
681
682 assert(PyList_Check(mro));
683 assert(PyClass_Check(cls));
684 i = PySequence_Contains(mro, cls);
685 if (i < 0)
686 return -1;
687 if (!i) {
688 if (PyList_Append(mro, cls) < 0)
689 return -1;
690 }
691 bases = ((PyClassObject *)cls)->cl_bases;
692 assert(bases && PyTuple_Check(bases));
693 n = PyTuple_GET_SIZE(bases);
694 for (i = 0; i < n; i++) {
695 base = PyTuple_GET_ITEM(bases, i);
696 if (fill_classic_mro(mro, base) < 0)
697 return -1;
698 }
699 return 0;
700}
701
702static PyObject *
703classic_mro(PyObject *cls)
704{
705 PyObject *mro;
706
707 assert(PyClass_Check(cls));
708 mro = PyList_New(0);
709 if (mro != NULL) {
710 if (fill_classic_mro(mro, cls) == 0)
711 return mro;
712 Py_DECREF(mro);
713 }
714 return NULL;
715}
716
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717static PyObject *
718mro_implementation(PyTypeObject *type)
719{
720 int i, n, ok;
721 PyObject *bases, *result;
722
Guido van Rossum63517572002-06-18 16:44:57 +0000723 if(type->tp_dict == NULL) {
724 if(PyType_Ready(type) < 0)
725 return NULL;
726 }
727
Tim Peters6d6c1a32001-08-02 04:15:00 +0000728 bases = type->tp_bases;
729 n = PyTuple_GET_SIZE(bases);
730 result = Py_BuildValue("[O]", (PyObject *)type);
731 if (result == NULL)
732 return NULL;
733 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000734 PyObject *base = PyTuple_GET_ITEM(bases, i);
735 PyObject *parentMRO;
736 if (PyType_Check(base))
737 parentMRO = PySequence_List(
738 ((PyTypeObject*)base)->tp_mro);
739 else
740 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 if (parentMRO == NULL) {
742 Py_DECREF(result);
743 return NULL;
744 }
745 if (serious_order_disagreements(result, parentMRO)) {
746 Py_DECREF(result);
747 return NULL;
748 }
749 ok = conservative_merge(result, parentMRO);
750 Py_DECREF(parentMRO);
751 if (ok < 0) {
752 Py_DECREF(result);
753 return NULL;
754 }
755 }
756 return result;
757}
758
759static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000760mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761{
762 PyTypeObject *type = (PyTypeObject *)self;
763
Tim Peters6d6c1a32001-08-02 04:15:00 +0000764 return mro_implementation(type);
765}
766
767static int
768mro_internal(PyTypeObject *type)
769{
770 PyObject *mro, *result, *tuple;
771
772 if (type->ob_type == &PyType_Type) {
773 result = mro_implementation(type);
774 }
775 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000776 static PyObject *mro_str;
777 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 if (mro == NULL)
779 return -1;
780 result = PyObject_CallObject(mro, NULL);
781 Py_DECREF(mro);
782 }
783 if (result == NULL)
784 return -1;
785 tuple = PySequence_Tuple(result);
786 Py_DECREF(result);
787 type->tp_mro = tuple;
788 return 0;
789}
790
791
792/* Calculate the best base amongst multiple base classes.
793 This is the first one that's on the path to the "solid base". */
794
795static PyTypeObject *
796best_base(PyObject *bases)
797{
798 int i, n;
799 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000800 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000801
802 assert(PyTuple_Check(bases));
803 n = PyTuple_GET_SIZE(bases);
804 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000805 base = NULL;
806 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000808 base_proto = PyTuple_GET_ITEM(bases, i);
809 if (PyClass_Check(base_proto))
810 continue;
811 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812 PyErr_SetString(
813 PyExc_TypeError,
814 "bases must be types");
815 return NULL;
816 }
Tim Petersa91e9642001-11-14 23:32:33 +0000817 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000819 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820 return NULL;
821 }
822 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000823 if (winner == NULL) {
824 winner = candidate;
825 base = base_i;
826 }
827 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828 ;
829 else if (PyType_IsSubtype(candidate, winner)) {
830 winner = candidate;
831 base = base_i;
832 }
833 else {
834 PyErr_SetString(
835 PyExc_TypeError,
836 "multiple bases have "
837 "instance lay-out conflict");
838 return NULL;
839 }
840 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000841 if (base == NULL)
842 PyErr_SetString(PyExc_TypeError,
843 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844 return base;
845}
846
847static int
848extra_ivars(PyTypeObject *type, PyTypeObject *base)
849{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000850 size_t t_size = type->tp_basicsize;
851 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
Guido van Rossum9676b222001-08-17 20:32:36 +0000853 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854 if (type->tp_itemsize || base->tp_itemsize) {
855 /* If itemsize is involved, stricter rules */
856 return t_size != b_size ||
857 type->tp_itemsize != base->tp_itemsize;
858 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000859 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
860 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
861 t_size -= sizeof(PyObject *);
862 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
863 type->tp_dictoffset + sizeof(PyObject *) == t_size)
864 t_size -= sizeof(PyObject *);
865
866 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867}
868
869static PyTypeObject *
870solid_base(PyTypeObject *type)
871{
872 PyTypeObject *base;
873
874 if (type->tp_base)
875 base = solid_base(type->tp_base);
876 else
877 base = &PyBaseObject_Type;
878 if (extra_ivars(type, base))
879 return type;
880 else
881 return base;
882}
883
Jeremy Hylton938ace62002-07-17 16:30:39 +0000884static void object_dealloc(PyObject *);
885static int object_init(PyObject *, PyObject *, PyObject *);
886static int update_slot(PyTypeObject *, PyObject *);
887static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000888
889static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000890subtype_dict(PyObject *obj, void *context)
891{
892 PyObject **dictptr = _PyObject_GetDictPtr(obj);
893 PyObject *dict;
894
895 if (dictptr == NULL) {
896 PyErr_SetString(PyExc_AttributeError,
897 "This object has no __dict__");
898 return NULL;
899 }
900 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000901 if (dict == NULL)
902 *dictptr = dict = PyDict_New();
903 Py_XINCREF(dict);
904 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000905}
906
Guido van Rossum6661be32001-10-26 04:26:12 +0000907static int
908subtype_setdict(PyObject *obj, PyObject *value, void *context)
909{
910 PyObject **dictptr = _PyObject_GetDictPtr(obj);
911 PyObject *dict;
912
913 if (dictptr == NULL) {
914 PyErr_SetString(PyExc_AttributeError,
915 "This object has no __dict__");
916 return -1;
917 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000918 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000919 PyErr_SetString(PyExc_TypeError,
920 "__dict__ must be set to a dictionary");
921 return -1;
922 }
923 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000924 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000925 *dictptr = value;
926 Py_XDECREF(dict);
927 return 0;
928}
929
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000930static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000931 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000932 {0},
933};
934
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000935/* bozo: __getstate__ that raises TypeError */
936
937static PyObject *
938bozo_func(PyObject *self, PyObject *args)
939{
940 PyErr_SetString(PyExc_TypeError,
941 "a class that defines __slots__ without "
942 "defining __getstate__ cannot be pickled");
943 return NULL;
944}
945
Neal Norwitz93c1e232002-03-31 16:06:11 +0000946static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000947
948static PyObject *bozo_obj = NULL;
949
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000950static int
951valid_identifier(PyObject *s)
952{
Guido van Rossum03013a02002-07-16 14:30:28 +0000953 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000954 int i, n;
955
956 if (!PyString_Check(s)) {
957 PyErr_SetString(PyExc_TypeError,
958 "__slots__ must be strings");
959 return 0;
960 }
Guido van Rossum03013a02002-07-16 14:30:28 +0000961 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000962 n = PyString_GET_SIZE(s);
963 /* We must reject an empty name. As a hack, we bump the
964 length to 1 so that the loop will balk on the trailing \0. */
965 if (n == 0)
966 n = 1;
967 for (i = 0; i < n; i++, p++) {
968 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
969 PyErr_SetString(PyExc_TypeError,
970 "__slots__ must be identifiers");
971 return 0;
972 }
973 }
974 return 1;
975}
976
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000977static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000978type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
979{
980 PyObject *name, *bases, *dict;
981 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +0000982 static char buffer[256];
983 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000984 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000986 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000987 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000988
Tim Peters3abca122001-10-27 19:37:48 +0000989 assert(args != NULL && PyTuple_Check(args));
990 assert(kwds == NULL || PyDict_Check(kwds));
991
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000992 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000993 {
994 const int nargs = PyTuple_GET_SIZE(args);
995 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
996
997 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
998 PyObject *x = PyTuple_GET_ITEM(args, 0);
999 Py_INCREF(x->ob_type);
1000 return (PyObject *) x->ob_type;
1001 }
1002
1003 /* SF bug 475327 -- if that didn't trigger, we need 3
1004 arguments. but PyArg_ParseTupleAndKeywords below may give
1005 a msg saying type() needs exactly 3. */
1006 if (nargs + nkwds != 3) {
1007 PyErr_SetString(PyExc_TypeError,
1008 "type() takes 1 or 3 arguments");
1009 return NULL;
1010 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011 }
1012
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001013 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1015 &name,
1016 &PyTuple_Type, &bases,
1017 &PyDict_Type, &dict))
1018 return NULL;
1019
1020 /* Determine the proper metatype to deal with this,
1021 and check for metatype conflicts while we're at it.
1022 Note that if some other metatype wins to contract,
1023 it's possible that its instances are not types. */
1024 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001025 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001026 for (i = 0; i < nbases; i++) {
1027 tmp = PyTuple_GET_ITEM(bases, i);
1028 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001029 if (tmptype == &PyClass_Type)
1030 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001031 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001033 if (PyType_IsSubtype(tmptype, winner)) {
1034 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 continue;
1036 }
1037 PyErr_SetString(PyExc_TypeError,
1038 "metatype conflict among bases");
1039 return NULL;
1040 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001041 if (winner != metatype) {
1042 if (winner->tp_new != type_new) /* Pass it to the winner */
1043 return winner->tp_new(winner, args, kwds);
1044 metatype = winner;
1045 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046
1047 /* Adjust for empty tuple bases */
1048 if (nbases == 0) {
1049 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1050 if (bases == NULL)
1051 return NULL;
1052 nbases = 1;
1053 }
1054 else
1055 Py_INCREF(bases);
1056
1057 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1058
1059 /* Calculate best base, and check that all bases are type objects */
1060 base = best_base(bases);
1061 if (base == NULL)
1062 return NULL;
1063 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1064 PyErr_Format(PyExc_TypeError,
1065 "type '%.100s' is not an acceptable base type",
1066 base->tp_name);
1067 return NULL;
1068 }
1069
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070 /* Check for a __slots__ sequence variable in dict, and count it */
1071 slots = PyDict_GetItemString(dict, "__slots__");
1072 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001073 add_dict = 0;
1074 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 if (slots != NULL) {
1076 /* Make it into a tuple */
1077 if (PyString_Check(slots))
1078 slots = Py_BuildValue("(O)", slots);
1079 else
1080 slots = PySequence_Tuple(slots);
1081 if (slots == NULL)
1082 return NULL;
1083 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001084 if (nslots > 0 && base->tp_itemsize != 0) {
1085 PyErr_Format(PyExc_TypeError,
1086 "nonempty __slots__ "
1087 "not supported for subtype of '%s'",
1088 base->tp_name);
1089 return NULL;
1090 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001092 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 Py_DECREF(slots);
1094 return NULL;
1095 }
1096 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001097
1098 newslots = PyTuple_New(nslots);
1099 if (newslots == NULL)
1100 return NULL;
1101 for (i = 0; i < nslots; i++) {
1102 tmp = PyTuple_GET_ITEM(slots, i);
1103 if (_Py_Mangle(PyString_AS_STRING(name),
1104 PyString_AS_STRING(tmp),
1105 buffer, sizeof(buffer)))
1106 {
1107 tmp = PyString_FromString(buffer);
1108 } else {
1109 Py_INCREF(tmp);
1110 }
1111 PyTuple_SET_ITEM(newslots, i, tmp);
1112 }
1113 Py_DECREF(slots);
1114 slots = newslots;
1115
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001117 if (slots != NULL) {
1118 /* See if *this* class defines __getstate__ */
1119 PyObject *getstate = PyDict_GetItemString(dict,
1120 "__getstate__");
1121 if (getstate == NULL) {
1122 /* If not, provide a bozo that raises TypeError */
1123 if (bozo_obj == NULL) {
1124 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1125 if (bozo_obj == NULL) {
1126 /* XXX decref various things */
1127 return NULL;
1128 }
1129 }
1130 if (PyDict_SetItemString(dict,
1131 "__getstate__",
1132 bozo_obj) < 0) {
1133 /* XXX decref various things */
1134 return NULL;
1135 }
1136 }
1137 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138 if (slots == NULL && base->tp_dictoffset == 0 &&
1139 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001140 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001141 add_dict++;
1142 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001143 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1144 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001145 nslots++;
1146 add_weak++;
1147 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148
1149 /* XXX From here until type is safely allocated,
1150 "return NULL" may leak slots! */
1151
1152 /* Allocate the type object */
1153 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1154 if (type == NULL)
1155 return NULL;
1156
1157 /* Keep name and slots alive in the extended type object */
1158 et = (etype *)type;
1159 Py_INCREF(name);
1160 et->name = name;
1161 et->slots = slots;
1162
Guido van Rossumdc91b992001-08-08 22:26:22 +00001163 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1165 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001166 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1167 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001168
1169 /* It's a new-style number unless it specifically inherits any
1170 old-style numeric behavior */
1171 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1172 (base->tp_as_number == NULL))
1173 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1174
1175 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 type->tp_as_number = &et->as_number;
1177 type->tp_as_sequence = &et->as_sequence;
1178 type->tp_as_mapping = &et->as_mapping;
1179 type->tp_as_buffer = &et->as_buffer;
1180 type->tp_name = PyString_AS_STRING(name);
1181
1182 /* Set tp_base and tp_bases */
1183 type->tp_bases = bases;
1184 Py_INCREF(base);
1185 type->tp_base = base;
1186
Guido van Rossum687ae002001-10-15 22:03:32 +00001187 /* Initialize tp_dict from passed-in dict */
1188 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 if (dict == NULL) {
1190 Py_DECREF(type);
1191 return NULL;
1192 }
1193
Guido van Rossumc3542212001-08-16 09:18:56 +00001194 /* Set __module__ in the dict */
1195 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1196 tmp = PyEval_GetGlobals();
1197 if (tmp != NULL) {
1198 tmp = PyDict_GetItemString(tmp, "__name__");
1199 if (tmp != NULL) {
1200 if (PyDict_SetItemString(dict, "__module__",
1201 tmp) < 0)
1202 return NULL;
1203 }
1204 }
1205 }
1206
Tim Peters2f93e282001-10-04 05:27:00 +00001207 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001208 and is a string. The __doc__ accessor will first look for tp_doc;
1209 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001210 */
1211 {
1212 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1213 if (doc != NULL && PyString_Check(doc)) {
1214 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001215 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001216 if (type->tp_doc == NULL) {
1217 Py_DECREF(type);
1218 return NULL;
1219 }
1220 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1221 }
1222 }
1223
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224 /* Special-case __new__: if it's a plain function,
1225 make it a static function */
1226 tmp = PyDict_GetItemString(dict, "__new__");
1227 if (tmp != NULL && PyFunction_Check(tmp)) {
1228 tmp = PyStaticMethod_New(tmp);
1229 if (tmp == NULL) {
1230 Py_DECREF(type);
1231 return NULL;
1232 }
1233 PyDict_SetItemString(dict, "__new__", tmp);
1234 Py_DECREF(tmp);
1235 }
1236
1237 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1238 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001239 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 if (slots != NULL) {
1241 for (i = 0; i < nslots; i++, mp++) {
1242 mp->name = PyString_AS_STRING(
1243 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001244 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001246 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001247 strcmp(mp->name, "__weakref__") == 0) {
1248 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001249 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001250 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001251 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 slotoffset += sizeof(PyObject *);
1253 }
1254 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001255 else {
1256 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001257 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001258 type->tp_dictoffset =
1259 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001260 else
1261 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001262 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001263 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001264 }
1265 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001266 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001267 type->tp_weaklistoffset = slotoffset;
1268 mp->name = "__weakref__";
1269 mp->type = T_OBJECT;
1270 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001271 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001272 mp++;
1273 slotoffset += sizeof(PyObject *);
1274 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 }
1276 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001277 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001278 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001279
1280 /* Special case some slots */
1281 if (type->tp_dictoffset != 0 || nslots > 0) {
1282 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1283 type->tp_getattro = PyObject_GenericGetAttr;
1284 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1285 type->tp_setattro = PyObject_GenericSetAttr;
1286 }
1287 type->tp_dealloc = subtype_dealloc;
1288
Guido van Rossum9475a232001-10-05 20:51:39 +00001289 /* Enable GC unless there are really no instance variables possible */
1290 if (!(type->tp_basicsize == sizeof(PyObject) &&
1291 type->tp_itemsize == 0))
1292 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1293
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 /* Always override allocation strategy to use regular heap */
1295 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001296 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001297 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001298 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001299 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001300 }
1301 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001302 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303
1304 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001305 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 Py_DECREF(type);
1307 return NULL;
1308 }
1309
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001310 /* Put the proper slots in place */
1311 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001312
Tim Peters6d6c1a32001-08-02 04:15:00 +00001313 return (PyObject *)type;
1314}
1315
1316/* Internal API to look for a name through the MRO.
1317 This returns a borrowed reference, and doesn't set an exception! */
1318PyObject *
1319_PyType_Lookup(PyTypeObject *type, PyObject *name)
1320{
1321 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001322 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323
Guido van Rossum687ae002001-10-15 22:03:32 +00001324 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001326
1327 /* If mro is NULL, the type is either not yet initialized
1328 by PyType_Ready(), or already cleared by type_clear().
1329 Either way the safest thing to do is to return NULL. */
1330 if (mro == NULL)
1331 return NULL;
1332
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333 assert(PyTuple_Check(mro));
1334 n = PyTuple_GET_SIZE(mro);
1335 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001336 base = PyTuple_GET_ITEM(mro, i);
1337 if (PyClass_Check(base))
1338 dict = ((PyClassObject *)base)->cl_dict;
1339 else {
1340 assert(PyType_Check(base));
1341 dict = ((PyTypeObject *)base)->tp_dict;
1342 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343 assert(dict && PyDict_Check(dict));
1344 res = PyDict_GetItem(dict, name);
1345 if (res != NULL)
1346 return res;
1347 }
1348 return NULL;
1349}
1350
1351/* This is similar to PyObject_GenericGetAttr(),
1352 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1353static PyObject *
1354type_getattro(PyTypeObject *type, PyObject *name)
1355{
1356 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001357 PyObject *meta_attribute, *attribute;
1358 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359
1360 /* Initialize this type (we'll assume the metatype is initialized) */
1361 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001362 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001363 return NULL;
1364 }
1365
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001366 /* No readable descriptor found yet */
1367 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001368
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001369 /* Look for the attribute in the metatype */
1370 meta_attribute = _PyType_Lookup(metatype, name);
1371
1372 if (meta_attribute != NULL) {
1373 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001374
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001375 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1376 /* Data descriptors implement tp_descr_set to intercept
1377 * writes. Assume the attribute is not overridden in
1378 * type's tp_dict (and bases): call the descriptor now.
1379 */
1380 return meta_get(meta_attribute, (PyObject *)type,
1381 (PyObject *)metatype);
1382 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 }
1384
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001385 /* No data descriptor found on metatype. Look in tp_dict of this
1386 * type and its bases */
1387 attribute = _PyType_Lookup(type, name);
1388 if (attribute != NULL) {
1389 /* Implement descriptor functionality, if any */
1390 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1391 if (local_get != NULL) {
1392 /* NULL 2nd argument indicates the descriptor was
1393 * found on the target object itself (or a base) */
1394 return local_get(attribute, (PyObject *)NULL,
1395 (PyObject *)type);
1396 }
Tim Peters34592512002-07-11 06:23:50 +00001397
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001398 Py_INCREF(attribute);
1399 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001400 }
1401
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001402 /* No attribute found in local __dict__ (or bases): use the
1403 * descriptor from the metatype, if any */
1404 if (meta_get != NULL)
1405 return meta_get(meta_attribute, (PyObject *)type,
1406 (PyObject *)metatype);
1407
1408 /* If an ordinary attribute was found on the metatype, return it now */
1409 if (meta_attribute != NULL) {
1410 Py_INCREF(meta_attribute);
1411 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 }
1413
1414 /* Give up */
1415 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001416 "type object '%.50s' has no attribute '%.400s'",
1417 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 return NULL;
1419}
1420
1421static int
1422type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1423{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001424 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1425 PyErr_Format(
1426 PyExc_TypeError,
1427 "can't set attributes of built-in/extension type '%s'",
1428 type->tp_name);
1429 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001430 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001431 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1432 return -1;
1433 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434}
1435
1436static void
1437type_dealloc(PyTypeObject *type)
1438{
1439 etype *et;
1440
1441 /* Assert this is a heap-allocated type object */
1442 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001443 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001444 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 et = (etype *)type;
1446 Py_XDECREF(type->tp_base);
1447 Py_XDECREF(type->tp_dict);
1448 Py_XDECREF(type->tp_bases);
1449 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001450 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001451 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001452 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453 Py_XDECREF(et->name);
1454 Py_XDECREF(et->slots);
1455 type->ob_type->tp_free((PyObject *)type);
1456}
1457
Guido van Rossum1c450732001-10-08 15:18:27 +00001458static PyObject *
1459type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1460{
1461 PyObject *list, *raw, *ref;
1462 int i, n;
1463
1464 list = PyList_New(0);
1465 if (list == NULL)
1466 return NULL;
1467 raw = type->tp_subclasses;
1468 if (raw == NULL)
1469 return list;
1470 assert(PyList_Check(raw));
1471 n = PyList_GET_SIZE(raw);
1472 for (i = 0; i < n; i++) {
1473 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001474 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001475 ref = PyWeakref_GET_OBJECT(ref);
1476 if (ref != Py_None) {
1477 if (PyList_Append(list, ref) < 0) {
1478 Py_DECREF(list);
1479 return NULL;
1480 }
1481 }
1482 }
1483 return list;
1484}
1485
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001487 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001489 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1490 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001491 {0}
1492};
1493
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001494PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001496"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001497
Guido van Rossum048eb752001-10-02 21:24:57 +00001498static int
1499type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1500{
Guido van Rossum048eb752001-10-02 21:24:57 +00001501 int err;
1502
Guido van Rossuma3862092002-06-10 15:24:42 +00001503 /* Because of type_is_gc(), the collector only calls this
1504 for heaptypes. */
1505 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001506
1507#define VISIT(SLOT) \
1508 if (SLOT) { \
1509 err = visit((PyObject *)(SLOT), arg); \
1510 if (err) \
1511 return err; \
1512 }
1513
1514 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001515 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001516 VISIT(type->tp_mro);
1517 VISIT(type->tp_bases);
1518 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001519
1520 /* There's no need to visit type->tp_subclasses or
1521 ((etype *)type)->slots, because they can't be involved
1522 in cycles; tp_subclasses is a list of weak references,
1523 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001524
1525#undef VISIT
1526
1527 return 0;
1528}
1529
1530static int
1531type_clear(PyTypeObject *type)
1532{
Guido van Rossum048eb752001-10-02 21:24:57 +00001533 PyObject *tmp;
1534
Guido van Rossuma3862092002-06-10 15:24:42 +00001535 /* Because of type_is_gc(), the collector only calls this
1536 for heaptypes. */
1537 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001538
1539#define CLEAR(SLOT) \
1540 if (SLOT) { \
1541 tmp = (PyObject *)(SLOT); \
1542 SLOT = NULL; \
1543 Py_DECREF(tmp); \
1544 }
1545
Guido van Rossuma3862092002-06-10 15:24:42 +00001546 /* The only field we need to clear is tp_mro, which is part of a
1547 hard cycle (its first element is the class itself) that won't
1548 be broken otherwise (it's a tuple and tuples don't have a
1549 tp_clear handler). None of the other fields need to be
1550 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001551
Guido van Rossuma3862092002-06-10 15:24:42 +00001552 tp_dict:
1553 It is a dict, so the collector will call its tp_clear.
1554
1555 tp_cache:
1556 Not used; if it were, it would be a dict.
1557
1558 tp_bases, tp_base:
1559 If these are involved in a cycle, there must be at least
1560 one other, mutable object in the cycle, e.g. a base
1561 class's dict; the cycle will be broken that way.
1562
1563 tp_subclasses:
1564 A list of weak references can't be part of a cycle; and
1565 lists have their own tp_clear.
1566
1567 slots (in etype):
1568 A tuple of strings can't be part of a cycle.
1569 */
1570
1571 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001572
Guido van Rossum048eb752001-10-02 21:24:57 +00001573#undef CLEAR
1574
1575 return 0;
1576}
1577
1578static int
1579type_is_gc(PyTypeObject *type)
1580{
1581 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1582}
1583
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001584PyTypeObject PyType_Type = {
1585 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 0, /* ob_size */
1587 "type", /* tp_name */
1588 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001589 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001590 (destructor)type_dealloc, /* tp_dealloc */
1591 0, /* tp_print */
1592 0, /* tp_getattr */
1593 0, /* tp_setattr */
1594 type_compare, /* tp_compare */
1595 (reprfunc)type_repr, /* tp_repr */
1596 0, /* tp_as_number */
1597 0, /* tp_as_sequence */
1598 0, /* tp_as_mapping */
1599 (hashfunc)_Py_HashPointer, /* tp_hash */
1600 (ternaryfunc)type_call, /* tp_call */
1601 0, /* tp_str */
1602 (getattrofunc)type_getattro, /* tp_getattro */
1603 (setattrofunc)type_setattro, /* tp_setattro */
1604 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001605 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1606 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001608 (traverseproc)type_traverse, /* tp_traverse */
1609 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001610 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001611 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001612 0, /* tp_iter */
1613 0, /* tp_iternext */
1614 type_methods, /* tp_methods */
1615 type_members, /* tp_members */
1616 type_getsets, /* tp_getset */
1617 0, /* tp_base */
1618 0, /* tp_dict */
1619 0, /* tp_descr_get */
1620 0, /* tp_descr_set */
1621 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1622 0, /* tp_init */
1623 0, /* tp_alloc */
1624 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001625 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001626 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001627};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628
1629
1630/* The base type of all types (eventually)... except itself. */
1631
1632static int
1633object_init(PyObject *self, PyObject *args, PyObject *kwds)
1634{
1635 return 0;
1636}
1637
1638static void
1639object_dealloc(PyObject *self)
1640{
1641 self->ob_type->tp_free(self);
1642}
1643
Guido van Rossum8e248182001-08-12 05:17:56 +00001644static PyObject *
1645object_repr(PyObject *self)
1646{
Guido van Rossum76e69632001-08-16 18:52:43 +00001647 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001648 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001649
Guido van Rossum76e69632001-08-16 18:52:43 +00001650 type = self->ob_type;
1651 mod = type_module(type, NULL);
1652 if (mod == NULL)
1653 PyErr_Clear();
1654 else if (!PyString_Check(mod)) {
1655 Py_DECREF(mod);
1656 mod = NULL;
1657 }
1658 name = type_name(type, NULL);
1659 if (name == NULL)
1660 return NULL;
1661 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001662 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001663 PyString_AS_STRING(mod),
1664 PyString_AS_STRING(name),
1665 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001666 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001667 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001668 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001669 Py_XDECREF(mod);
1670 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001671 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001672}
1673
Guido van Rossumb8f63662001-08-15 23:57:02 +00001674static PyObject *
1675object_str(PyObject *self)
1676{
1677 unaryfunc f;
1678
1679 f = self->ob_type->tp_repr;
1680 if (f == NULL)
1681 f = object_repr;
1682 return f(self);
1683}
1684
Guido van Rossum8e248182001-08-12 05:17:56 +00001685static long
1686object_hash(PyObject *self)
1687{
1688 return _Py_HashPointer(self);
1689}
Guido van Rossum8e248182001-08-12 05:17:56 +00001690
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001691static PyObject *
1692object_get_class(PyObject *self, void *closure)
1693{
1694 Py_INCREF(self->ob_type);
1695 return (PyObject *)(self->ob_type);
1696}
1697
1698static int
1699equiv_structs(PyTypeObject *a, PyTypeObject *b)
1700{
1701 return a == b ||
1702 (a != NULL &&
1703 b != NULL &&
1704 a->tp_basicsize == b->tp_basicsize &&
1705 a->tp_itemsize == b->tp_itemsize &&
1706 a->tp_dictoffset == b->tp_dictoffset &&
1707 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1708 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1709 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1710}
1711
1712static int
1713same_slots_added(PyTypeObject *a, PyTypeObject *b)
1714{
1715 PyTypeObject *base = a->tp_base;
1716 int size;
1717
1718 if (base != b->tp_base)
1719 return 0;
1720 if (equiv_structs(a, base) && equiv_structs(b, base))
1721 return 1;
1722 size = base->tp_basicsize;
1723 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1724 size += sizeof(PyObject *);
1725 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1726 size += sizeof(PyObject *);
1727 return size == a->tp_basicsize && size == b->tp_basicsize;
1728}
1729
1730static int
1731object_set_class(PyObject *self, PyObject *value, void *closure)
1732{
1733 PyTypeObject *old = self->ob_type;
1734 PyTypeObject *new, *newbase, *oldbase;
1735
Guido van Rossumb6b89422002-04-15 01:03:30 +00001736 if (value == NULL) {
1737 PyErr_SetString(PyExc_TypeError,
1738 "can't delete __class__ attribute");
1739 return -1;
1740 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001741 if (!PyType_Check(value)) {
1742 PyErr_Format(PyExc_TypeError,
1743 "__class__ must be set to new-style class, not '%s' object",
1744 value->ob_type->tp_name);
1745 return -1;
1746 }
1747 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001748 if (new->tp_dealloc != old->tp_dealloc ||
1749 new->tp_free != old->tp_free)
1750 {
1751 PyErr_Format(PyExc_TypeError,
1752 "__class__ assignment: "
1753 "'%s' deallocator differs from '%s'",
1754 new->tp_name,
1755 old->tp_name);
1756 return -1;
1757 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001758 newbase = new;
1759 oldbase = old;
1760 while (equiv_structs(newbase, newbase->tp_base))
1761 newbase = newbase->tp_base;
1762 while (equiv_structs(oldbase, oldbase->tp_base))
1763 oldbase = oldbase->tp_base;
1764 if (newbase != oldbase &&
1765 (newbase->tp_base != oldbase->tp_base ||
1766 !same_slots_added(newbase, oldbase))) {
1767 PyErr_Format(PyExc_TypeError,
1768 "__class__ assignment: "
1769 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001770 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001771 old->tp_name);
1772 return -1;
1773 }
1774 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1775 Py_INCREF(new);
1776 }
1777 self->ob_type = new;
1778 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1779 Py_DECREF(old);
1780 }
1781 return 0;
1782}
1783
1784static PyGetSetDef object_getsets[] = {
1785 {"__class__", object_get_class, object_set_class,
1786 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 {0}
1788};
1789
Guido van Rossum3926a632001-09-25 16:25:58 +00001790static PyObject *
1791object_reduce(PyObject *self, PyObject *args)
1792{
1793 /* Call copy_reg._reduce(self) */
1794 static PyObject *copy_reg_str;
1795 PyObject *copy_reg, *res;
1796
1797 if (!copy_reg_str) {
1798 copy_reg_str = PyString_InternFromString("copy_reg");
1799 if (copy_reg_str == NULL)
1800 return NULL;
1801 }
1802 copy_reg = PyImport_Import(copy_reg_str);
1803 if (!copy_reg)
1804 return NULL;
1805 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1806 Py_DECREF(copy_reg);
1807 return res;
1808}
1809
1810static PyMethodDef object_methods[] = {
1811 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1812 {0}
1813};
1814
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815PyTypeObject PyBaseObject_Type = {
1816 PyObject_HEAD_INIT(&PyType_Type)
1817 0, /* ob_size */
1818 "object", /* tp_name */
1819 sizeof(PyObject), /* tp_basicsize */
1820 0, /* tp_itemsize */
1821 (destructor)object_dealloc, /* tp_dealloc */
1822 0, /* tp_print */
1823 0, /* tp_getattr */
1824 0, /* tp_setattr */
1825 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001826 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001827 0, /* tp_as_number */
1828 0, /* tp_as_sequence */
1829 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001830 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001832 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001833 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001834 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001835 0, /* tp_as_buffer */
1836 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1837 "The most base type", /* tp_doc */
1838 0, /* tp_traverse */
1839 0, /* tp_clear */
1840 0, /* tp_richcompare */
1841 0, /* tp_weaklistoffset */
1842 0, /* tp_iter */
1843 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001844 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001845 0, /* tp_members */
1846 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 0, /* tp_base */
1848 0, /* tp_dict */
1849 0, /* tp_descr_get */
1850 0, /* tp_descr_set */
1851 0, /* tp_dictoffset */
1852 object_init, /* tp_init */
1853 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001854 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001855 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856};
1857
1858
1859/* Initialize the __dict__ in a type object */
1860
Fred Drake7bf97152002-03-28 05:33:33 +00001861static PyObject *
1862create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1863{
1864 PyObject *cfunc;
1865 PyObject *result;
1866
1867 cfunc = PyCFunction_New(meth, NULL);
1868 if (cfunc == NULL)
1869 return NULL;
1870 result = func(cfunc);
1871 Py_DECREF(cfunc);
1872 return result;
1873}
1874
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875static int
1876add_methods(PyTypeObject *type, PyMethodDef *meth)
1877{
Guido van Rossum687ae002001-10-15 22:03:32 +00001878 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879
1880 for (; meth->ml_name != NULL; meth++) {
1881 PyObject *descr;
1882 if (PyDict_GetItemString(dict, meth->ml_name))
1883 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001884 if (meth->ml_flags & METH_CLASS) {
1885 if (meth->ml_flags & METH_STATIC) {
1886 PyErr_SetString(PyExc_ValueError,
1887 "method cannot be both class and static");
1888 return -1;
1889 }
1890 descr = create_specialmethod(meth, PyClassMethod_New);
1891 }
1892 else if (meth->ml_flags & METH_STATIC) {
1893 descr = create_specialmethod(meth, PyStaticMethod_New);
1894 }
1895 else {
1896 descr = PyDescr_NewMethod(type, meth);
1897 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898 if (descr == NULL)
1899 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001900 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901 return -1;
1902 Py_DECREF(descr);
1903 }
1904 return 0;
1905}
1906
1907static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001908add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909{
Guido van Rossum687ae002001-10-15 22:03:32 +00001910 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001911
1912 for (; memb->name != NULL; memb++) {
1913 PyObject *descr;
1914 if (PyDict_GetItemString(dict, memb->name))
1915 continue;
1916 descr = PyDescr_NewMember(type, memb);
1917 if (descr == NULL)
1918 return -1;
1919 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1920 return -1;
1921 Py_DECREF(descr);
1922 }
1923 return 0;
1924}
1925
1926static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001927add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928{
Guido van Rossum687ae002001-10-15 22:03:32 +00001929 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930
1931 for (; gsp->name != NULL; gsp++) {
1932 PyObject *descr;
1933 if (PyDict_GetItemString(dict, gsp->name))
1934 continue;
1935 descr = PyDescr_NewGetSet(type, gsp);
1936
1937 if (descr == NULL)
1938 return -1;
1939 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1940 return -1;
1941 Py_DECREF(descr);
1942 }
1943 return 0;
1944}
1945
Guido van Rossum13d52f02001-08-10 21:24:08 +00001946static void
1947inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948{
1949 int oldsize, newsize;
1950
Guido van Rossum13d52f02001-08-10 21:24:08 +00001951 /* Special flag magic */
1952 if (!type->tp_as_buffer && base->tp_as_buffer) {
1953 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1954 type->tp_flags |=
1955 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1956 }
1957 if (!type->tp_as_sequence && base->tp_as_sequence) {
1958 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1959 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1960 }
1961 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1962 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1963 if ((!type->tp_as_number && base->tp_as_number) ||
1964 (!type->tp_as_sequence && base->tp_as_sequence)) {
1965 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1966 if (!type->tp_as_number && !type->tp_as_sequence) {
1967 type->tp_flags |= base->tp_flags &
1968 Py_TPFLAGS_HAVE_INPLACEOPS;
1969 }
1970 }
1971 /* Wow */
1972 }
1973 if (!type->tp_as_number && base->tp_as_number) {
1974 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1975 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1976 }
1977
1978 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001979 oldsize = base->tp_basicsize;
1980 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1981 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1982 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001983 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1984 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001985 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001986 if (type->tp_traverse == NULL)
1987 type->tp_traverse = base->tp_traverse;
1988 if (type->tp_clear == NULL)
1989 type->tp_clear = base->tp_clear;
1990 }
1991 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001992 /* The condition below could use some explanation.
1993 It appears that tp_new is not inherited for static types
1994 whose base class is 'object'; this seems to be a precaution
1995 so that old extension types don't suddenly become
1996 callable (object.__new__ wouldn't insure the invariants
1997 that the extension type's own factory function ensures).
1998 Heap types, of course, are under our control, so they do
1999 inherit tp_new; static extension types that specify some
2000 other built-in type as the default are considered
2001 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002002 if (base != &PyBaseObject_Type ||
2003 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2004 if (type->tp_new == NULL)
2005 type->tp_new = base->tp_new;
2006 }
2007 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002008 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002009
2010 /* Copy other non-function slots */
2011
2012#undef COPYVAL
2013#define COPYVAL(SLOT) \
2014 if (type->SLOT == 0) type->SLOT = base->SLOT
2015
2016 COPYVAL(tp_itemsize);
2017 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2018 COPYVAL(tp_weaklistoffset);
2019 }
2020 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2021 COPYVAL(tp_dictoffset);
2022 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002023}
2024
2025static void
2026inherit_slots(PyTypeObject *type, PyTypeObject *base)
2027{
2028 PyTypeObject *basebase;
2029
2030#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031#undef COPYSLOT
2032#undef COPYNUM
2033#undef COPYSEQ
2034#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002035#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002036
2037#define SLOTDEFINED(SLOT) \
2038 (base->SLOT != 0 && \
2039 (basebase == NULL || base->SLOT != basebase->SLOT))
2040
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002042 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043
2044#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2045#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2046#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002047#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048
Guido van Rossum13d52f02001-08-10 21:24:08 +00002049 /* This won't inherit indirect slots (from tp_as_number etc.)
2050 if type doesn't provide the space. */
2051
2052 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2053 basebase = base->tp_base;
2054 if (basebase->tp_as_number == NULL)
2055 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 COPYNUM(nb_add);
2057 COPYNUM(nb_subtract);
2058 COPYNUM(nb_multiply);
2059 COPYNUM(nb_divide);
2060 COPYNUM(nb_remainder);
2061 COPYNUM(nb_divmod);
2062 COPYNUM(nb_power);
2063 COPYNUM(nb_negative);
2064 COPYNUM(nb_positive);
2065 COPYNUM(nb_absolute);
2066 COPYNUM(nb_nonzero);
2067 COPYNUM(nb_invert);
2068 COPYNUM(nb_lshift);
2069 COPYNUM(nb_rshift);
2070 COPYNUM(nb_and);
2071 COPYNUM(nb_xor);
2072 COPYNUM(nb_or);
2073 COPYNUM(nb_coerce);
2074 COPYNUM(nb_int);
2075 COPYNUM(nb_long);
2076 COPYNUM(nb_float);
2077 COPYNUM(nb_oct);
2078 COPYNUM(nb_hex);
2079 COPYNUM(nb_inplace_add);
2080 COPYNUM(nb_inplace_subtract);
2081 COPYNUM(nb_inplace_multiply);
2082 COPYNUM(nb_inplace_divide);
2083 COPYNUM(nb_inplace_remainder);
2084 COPYNUM(nb_inplace_power);
2085 COPYNUM(nb_inplace_lshift);
2086 COPYNUM(nb_inplace_rshift);
2087 COPYNUM(nb_inplace_and);
2088 COPYNUM(nb_inplace_xor);
2089 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002090 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2091 COPYNUM(nb_true_divide);
2092 COPYNUM(nb_floor_divide);
2093 COPYNUM(nb_inplace_true_divide);
2094 COPYNUM(nb_inplace_floor_divide);
2095 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002096 }
2097
Guido van Rossum13d52f02001-08-10 21:24:08 +00002098 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2099 basebase = base->tp_base;
2100 if (basebase->tp_as_sequence == NULL)
2101 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 COPYSEQ(sq_length);
2103 COPYSEQ(sq_concat);
2104 COPYSEQ(sq_repeat);
2105 COPYSEQ(sq_item);
2106 COPYSEQ(sq_slice);
2107 COPYSEQ(sq_ass_item);
2108 COPYSEQ(sq_ass_slice);
2109 COPYSEQ(sq_contains);
2110 COPYSEQ(sq_inplace_concat);
2111 COPYSEQ(sq_inplace_repeat);
2112 }
2113
Guido van Rossum13d52f02001-08-10 21:24:08 +00002114 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2115 basebase = base->tp_base;
2116 if (basebase->tp_as_mapping == NULL)
2117 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118 COPYMAP(mp_length);
2119 COPYMAP(mp_subscript);
2120 COPYMAP(mp_ass_subscript);
2121 }
2122
Tim Petersfc57ccb2001-10-12 02:38:24 +00002123 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2124 basebase = base->tp_base;
2125 if (basebase->tp_as_buffer == NULL)
2126 basebase = NULL;
2127 COPYBUF(bf_getreadbuffer);
2128 COPYBUF(bf_getwritebuffer);
2129 COPYBUF(bf_getsegcount);
2130 COPYBUF(bf_getcharbuffer);
2131 }
2132
Guido van Rossum13d52f02001-08-10 21:24:08 +00002133 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002134
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135 COPYSLOT(tp_dealloc);
2136 COPYSLOT(tp_print);
2137 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2138 type->tp_getattr = base->tp_getattr;
2139 type->tp_getattro = base->tp_getattro;
2140 }
2141 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2142 type->tp_setattr = base->tp_setattr;
2143 type->tp_setattro = base->tp_setattro;
2144 }
2145 /* tp_compare see tp_richcompare */
2146 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002147 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002148 COPYSLOT(tp_call);
2149 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002150 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002151 if (type->tp_compare == NULL &&
2152 type->tp_richcompare == NULL &&
2153 type->tp_hash == NULL)
2154 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002155 type->tp_compare = base->tp_compare;
2156 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002157 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002158 }
2159 }
2160 else {
2161 COPYSLOT(tp_compare);
2162 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2164 COPYSLOT(tp_iter);
2165 COPYSLOT(tp_iternext);
2166 }
2167 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2168 COPYSLOT(tp_descr_get);
2169 COPYSLOT(tp_descr_set);
2170 COPYSLOT(tp_dictoffset);
2171 COPYSLOT(tp_init);
2172 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002174 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176}
2177
Jeremy Hylton938ace62002-07-17 16:30:39 +00002178static int add_operators(PyTypeObject *);
2179static int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002180
Tim Peters6d6c1a32001-08-02 04:15:00 +00002181int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002182PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002184 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185 PyTypeObject *base;
2186 int i, n;
2187
Guido van Rossumcab05802002-06-10 15:29:03 +00002188 if (type->tp_flags & Py_TPFLAGS_READY) {
2189 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002190 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002191 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002192 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002193
2194 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195
2196 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2197 base = type->tp_base;
2198 if (base == NULL && type != &PyBaseObject_Type)
2199 base = type->tp_base = &PyBaseObject_Type;
2200
Guido van Rossum0986d822002-04-08 01:38:42 +00002201 /* Initialize ob_type if NULL. This means extensions that want to be
2202 compilable separately on Windows can call PyType_Ready() instead of
2203 initializing the ob_type field of their type objects. */
2204 if (type->ob_type == NULL)
2205 type->ob_type = base->ob_type;
2206
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207 /* Initialize tp_bases */
2208 bases = type->tp_bases;
2209 if (bases == NULL) {
2210 if (base == NULL)
2211 bases = PyTuple_New(0);
2212 else
2213 bases = Py_BuildValue("(O)", base);
2214 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002215 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002216 type->tp_bases = bases;
2217 }
2218
2219 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002220 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002221 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002222 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 }
2224
Guido van Rossum687ae002001-10-15 22:03:32 +00002225 /* Initialize tp_dict */
2226 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227 if (dict == NULL) {
2228 dict = PyDict_New();
2229 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002230 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002231 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232 }
2233
Guido van Rossum687ae002001-10-15 22:03:32 +00002234 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002236 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237 if (type->tp_methods != NULL) {
2238 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002239 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240 }
2241 if (type->tp_members != NULL) {
2242 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002243 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244 }
2245 if (type->tp_getset != NULL) {
2246 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002247 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002248 }
2249
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250 /* Calculate method resolution order */
2251 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002252 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253 }
2254
Guido van Rossum13d52f02001-08-10 21:24:08 +00002255 /* Inherit special flags from dominant base */
2256 if (type->tp_base != NULL)
2257 inherit_special(type, type->tp_base);
2258
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002260 bases = type->tp_mro;
2261 assert(bases != NULL);
2262 assert(PyTuple_Check(bases));
2263 n = PyTuple_GET_SIZE(bases);
2264 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002265 PyObject *b = PyTuple_GET_ITEM(bases, i);
2266 if (PyType_Check(b))
2267 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002268 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002270 /* if the type dictionary doesn't contain a __doc__, set it from
2271 the tp_doc slot.
2272 */
2273 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2274 if (type->tp_doc != NULL) {
2275 PyObject *doc = PyString_FromString(type->tp_doc);
2276 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2277 Py_DECREF(doc);
2278 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002279 PyDict_SetItemString(type->tp_dict,
2280 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002281 }
2282 }
2283
Guido van Rossum13d52f02001-08-10 21:24:08 +00002284 /* Some more special stuff */
2285 base = type->tp_base;
2286 if (base != NULL) {
2287 if (type->tp_as_number == NULL)
2288 type->tp_as_number = base->tp_as_number;
2289 if (type->tp_as_sequence == NULL)
2290 type->tp_as_sequence = base->tp_as_sequence;
2291 if (type->tp_as_mapping == NULL)
2292 type->tp_as_mapping = base->tp_as_mapping;
2293 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002294
Guido van Rossum1c450732001-10-08 15:18:27 +00002295 /* Link into each base class's list of subclasses */
2296 bases = type->tp_bases;
2297 n = PyTuple_GET_SIZE(bases);
2298 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002299 PyObject *b = PyTuple_GET_ITEM(bases, i);
2300 if (PyType_Check(b) &&
2301 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002302 goto error;
2303 }
2304
Guido van Rossum13d52f02001-08-10 21:24:08 +00002305 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002306 assert(type->tp_dict != NULL);
2307 type->tp_flags =
2308 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002309 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002310
2311 error:
2312 type->tp_flags &= ~Py_TPFLAGS_READYING;
2313 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314}
2315
Guido van Rossum1c450732001-10-08 15:18:27 +00002316static int
2317add_subclass(PyTypeObject *base, PyTypeObject *type)
2318{
2319 int i;
2320 PyObject *list, *ref, *new;
2321
2322 list = base->tp_subclasses;
2323 if (list == NULL) {
2324 base->tp_subclasses = list = PyList_New(0);
2325 if (list == NULL)
2326 return -1;
2327 }
2328 assert(PyList_Check(list));
2329 new = PyWeakref_NewRef((PyObject *)type, NULL);
2330 i = PyList_GET_SIZE(list);
2331 while (--i >= 0) {
2332 ref = PyList_GET_ITEM(list, i);
2333 assert(PyWeakref_CheckRef(ref));
2334 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2335 return PyList_SetItem(list, i, new);
2336 }
2337 i = PyList_Append(list, new);
2338 Py_DECREF(new);
2339 return i;
2340}
2341
Tim Peters6d6c1a32001-08-02 04:15:00 +00002342
2343/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2344
2345/* There's a wrapper *function* for each distinct function typedef used
2346 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2347 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2348 Most tables have only one entry; the tables for binary operators have two
2349 entries, one regular and one with reversed arguments. */
2350
2351static PyObject *
2352wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2353{
2354 inquiry func = (inquiry)wrapped;
2355 int res;
2356
2357 if (!PyArg_ParseTuple(args, ""))
2358 return NULL;
2359 res = (*func)(self);
2360 if (res == -1 && PyErr_Occurred())
2361 return NULL;
2362 return PyInt_FromLong((long)res);
2363}
2364
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365static PyObject *
2366wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2367{
2368 binaryfunc func = (binaryfunc)wrapped;
2369 PyObject *other;
2370
2371 if (!PyArg_ParseTuple(args, "O", &other))
2372 return NULL;
2373 return (*func)(self, other);
2374}
2375
2376static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002377wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2378{
2379 binaryfunc func = (binaryfunc)wrapped;
2380 PyObject *other;
2381
2382 if (!PyArg_ParseTuple(args, "O", &other))
2383 return NULL;
2384 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002385 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002386 Py_INCREF(Py_NotImplemented);
2387 return Py_NotImplemented;
2388 }
2389 return (*func)(self, other);
2390}
2391
2392static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2394{
2395 binaryfunc func = (binaryfunc)wrapped;
2396 PyObject *other;
2397
2398 if (!PyArg_ParseTuple(args, "O", &other))
2399 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002400 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002401 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002402 Py_INCREF(Py_NotImplemented);
2403 return Py_NotImplemented;
2404 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002405 return (*func)(other, self);
2406}
2407
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002408static PyObject *
2409wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2410{
2411 coercion func = (coercion)wrapped;
2412 PyObject *other, *res;
2413 int ok;
2414
2415 if (!PyArg_ParseTuple(args, "O", &other))
2416 return NULL;
2417 ok = func(&self, &other);
2418 if (ok < 0)
2419 return NULL;
2420 if (ok > 0) {
2421 Py_INCREF(Py_NotImplemented);
2422 return Py_NotImplemented;
2423 }
2424 res = PyTuple_New(2);
2425 if (res == NULL) {
2426 Py_DECREF(self);
2427 Py_DECREF(other);
2428 return NULL;
2429 }
2430 PyTuple_SET_ITEM(res, 0, self);
2431 PyTuple_SET_ITEM(res, 1, other);
2432 return res;
2433}
2434
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435static PyObject *
2436wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2437{
2438 ternaryfunc func = (ternaryfunc)wrapped;
2439 PyObject *other;
2440 PyObject *third = Py_None;
2441
2442 /* Note: This wrapper only works for __pow__() */
2443
2444 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2445 return NULL;
2446 return (*func)(self, other, third);
2447}
2448
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002449static PyObject *
2450wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2451{
2452 ternaryfunc func = (ternaryfunc)wrapped;
2453 PyObject *other;
2454 PyObject *third = Py_None;
2455
2456 /* Note: This wrapper only works for __pow__() */
2457
2458 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2459 return NULL;
2460 return (*func)(other, self, third);
2461}
2462
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463static PyObject *
2464wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2465{
2466 unaryfunc func = (unaryfunc)wrapped;
2467
2468 if (!PyArg_ParseTuple(args, ""))
2469 return NULL;
2470 return (*func)(self);
2471}
2472
Tim Peters6d6c1a32001-08-02 04:15:00 +00002473static PyObject *
2474wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2475{
2476 intargfunc func = (intargfunc)wrapped;
2477 int i;
2478
2479 if (!PyArg_ParseTuple(args, "i", &i))
2480 return NULL;
2481 return (*func)(self, i);
2482}
2483
Guido van Rossum5d815f32001-08-17 21:57:47 +00002484static int
2485getindex(PyObject *self, PyObject *arg)
2486{
2487 int i;
2488
2489 i = PyInt_AsLong(arg);
2490 if (i == -1 && PyErr_Occurred())
2491 return -1;
2492 if (i < 0) {
2493 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2494 if (sq && sq->sq_length) {
2495 int n = (*sq->sq_length)(self);
2496 if (n < 0)
2497 return -1;
2498 i += n;
2499 }
2500 }
2501 return i;
2502}
2503
2504static PyObject *
2505wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2506{
2507 intargfunc func = (intargfunc)wrapped;
2508 PyObject *arg;
2509 int i;
2510
Guido van Rossumf4593e02001-10-03 12:09:30 +00002511 if (PyTuple_GET_SIZE(args) == 1) {
2512 arg = PyTuple_GET_ITEM(args, 0);
2513 i = getindex(self, arg);
2514 if (i == -1 && PyErr_Occurred())
2515 return NULL;
2516 return (*func)(self, i);
2517 }
2518 PyArg_ParseTuple(args, "O", &arg);
2519 assert(PyErr_Occurred());
2520 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002521}
2522
Tim Peters6d6c1a32001-08-02 04:15:00 +00002523static PyObject *
2524wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2525{
2526 intintargfunc func = (intintargfunc)wrapped;
2527 int i, j;
2528
2529 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2530 return NULL;
2531 return (*func)(self, i, j);
2532}
2533
Tim Peters6d6c1a32001-08-02 04:15:00 +00002534static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002535wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002536{
2537 intobjargproc func = (intobjargproc)wrapped;
2538 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002539 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002540
Guido van Rossum5d815f32001-08-17 21:57:47 +00002541 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2542 return NULL;
2543 i = getindex(self, arg);
2544 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002545 return NULL;
2546 res = (*func)(self, i, value);
2547 if (res == -1 && PyErr_Occurred())
2548 return NULL;
2549 Py_INCREF(Py_None);
2550 return Py_None;
2551}
2552
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002553static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002554wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002555{
2556 intobjargproc func = (intobjargproc)wrapped;
2557 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002558 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002559
Guido van Rossum5d815f32001-08-17 21:57:47 +00002560 if (!PyArg_ParseTuple(args, "O", &arg))
2561 return NULL;
2562 i = getindex(self, arg);
2563 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002564 return NULL;
2565 res = (*func)(self, i, NULL);
2566 if (res == -1 && PyErr_Occurred())
2567 return NULL;
2568 Py_INCREF(Py_None);
2569 return Py_None;
2570}
2571
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572static PyObject *
2573wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2574{
2575 intintobjargproc func = (intintobjargproc)wrapped;
2576 int i, j, res;
2577 PyObject *value;
2578
2579 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2580 return NULL;
2581 res = (*func)(self, i, j, value);
2582 if (res == -1 && PyErr_Occurred())
2583 return NULL;
2584 Py_INCREF(Py_None);
2585 return Py_None;
2586}
2587
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002588static PyObject *
2589wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2590{
2591 intintobjargproc func = (intintobjargproc)wrapped;
2592 int i, j, res;
2593
2594 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2595 return NULL;
2596 res = (*func)(self, i, j, NULL);
2597 if (res == -1 && PyErr_Occurred())
2598 return NULL;
2599 Py_INCREF(Py_None);
2600 return Py_None;
2601}
2602
Tim Peters6d6c1a32001-08-02 04:15:00 +00002603/* XXX objobjproc is a misnomer; should be objargpred */
2604static PyObject *
2605wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2606{
2607 objobjproc func = (objobjproc)wrapped;
2608 int res;
2609 PyObject *value;
2610
2611 if (!PyArg_ParseTuple(args, "O", &value))
2612 return NULL;
2613 res = (*func)(self, value);
2614 if (res == -1 && PyErr_Occurred())
2615 return NULL;
2616 return PyInt_FromLong((long)res);
2617}
2618
Tim Peters6d6c1a32001-08-02 04:15:00 +00002619static PyObject *
2620wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2621{
2622 objobjargproc func = (objobjargproc)wrapped;
2623 int res;
2624 PyObject *key, *value;
2625
2626 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2627 return NULL;
2628 res = (*func)(self, key, value);
2629 if (res == -1 && PyErr_Occurred())
2630 return NULL;
2631 Py_INCREF(Py_None);
2632 return Py_None;
2633}
2634
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002635static PyObject *
2636wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2637{
2638 objobjargproc func = (objobjargproc)wrapped;
2639 int res;
2640 PyObject *key;
2641
2642 if (!PyArg_ParseTuple(args, "O", &key))
2643 return NULL;
2644 res = (*func)(self, key, NULL);
2645 if (res == -1 && PyErr_Occurred())
2646 return NULL;
2647 Py_INCREF(Py_None);
2648 return Py_None;
2649}
2650
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651static PyObject *
2652wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2653{
2654 cmpfunc func = (cmpfunc)wrapped;
2655 int res;
2656 PyObject *other;
2657
2658 if (!PyArg_ParseTuple(args, "O", &other))
2659 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002660 if (other->ob_type->tp_compare != func &&
2661 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002662 PyErr_Format(
2663 PyExc_TypeError,
2664 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2665 self->ob_type->tp_name,
2666 self->ob_type->tp_name,
2667 other->ob_type->tp_name);
2668 return NULL;
2669 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670 res = (*func)(self, other);
2671 if (PyErr_Occurred())
2672 return NULL;
2673 return PyInt_FromLong((long)res);
2674}
2675
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676static PyObject *
2677wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2678{
2679 setattrofunc func = (setattrofunc)wrapped;
2680 int res;
2681 PyObject *name, *value;
2682
2683 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2684 return NULL;
2685 res = (*func)(self, name, value);
2686 if (res < 0)
2687 return NULL;
2688 Py_INCREF(Py_None);
2689 return Py_None;
2690}
2691
2692static PyObject *
2693wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2694{
2695 setattrofunc func = (setattrofunc)wrapped;
2696 int res;
2697 PyObject *name;
2698
2699 if (!PyArg_ParseTuple(args, "O", &name))
2700 return NULL;
2701 res = (*func)(self, name, NULL);
2702 if (res < 0)
2703 return NULL;
2704 Py_INCREF(Py_None);
2705 return Py_None;
2706}
2707
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708static PyObject *
2709wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2710{
2711 hashfunc func = (hashfunc)wrapped;
2712 long res;
2713
2714 if (!PyArg_ParseTuple(args, ""))
2715 return NULL;
2716 res = (*func)(self);
2717 if (res == -1 && PyErr_Occurred())
2718 return NULL;
2719 return PyInt_FromLong(res);
2720}
2721
Tim Peters6d6c1a32001-08-02 04:15:00 +00002722static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002723wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724{
2725 ternaryfunc func = (ternaryfunc)wrapped;
2726
Guido van Rossumc8e56452001-10-22 00:43:43 +00002727 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728}
2729
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730static PyObject *
2731wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2732{
2733 richcmpfunc func = (richcmpfunc)wrapped;
2734 PyObject *other;
2735
2736 if (!PyArg_ParseTuple(args, "O", &other))
2737 return NULL;
2738 return (*func)(self, other, op);
2739}
2740
2741#undef RICHCMP_WRAPPER
2742#define RICHCMP_WRAPPER(NAME, OP) \
2743static PyObject * \
2744richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2745{ \
2746 return wrap_richcmpfunc(self, args, wrapped, OP); \
2747}
2748
Jack Jansen8e938b42001-08-08 15:29:49 +00002749RICHCMP_WRAPPER(lt, Py_LT)
2750RICHCMP_WRAPPER(le, Py_LE)
2751RICHCMP_WRAPPER(eq, Py_EQ)
2752RICHCMP_WRAPPER(ne, Py_NE)
2753RICHCMP_WRAPPER(gt, Py_GT)
2754RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756static PyObject *
2757wrap_next(PyObject *self, PyObject *args, void *wrapped)
2758{
2759 unaryfunc func = (unaryfunc)wrapped;
2760 PyObject *res;
2761
2762 if (!PyArg_ParseTuple(args, ""))
2763 return NULL;
2764 res = (*func)(self);
2765 if (res == NULL && !PyErr_Occurred())
2766 PyErr_SetNone(PyExc_StopIteration);
2767 return res;
2768}
2769
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770static PyObject *
2771wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2772{
2773 descrgetfunc func = (descrgetfunc)wrapped;
2774 PyObject *obj;
2775 PyObject *type = NULL;
2776
2777 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2778 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779 return (*func)(self, obj, type);
2780}
2781
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002783wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784{
2785 descrsetfunc func = (descrsetfunc)wrapped;
2786 PyObject *obj, *value;
2787 int ret;
2788
2789 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2790 return NULL;
2791 ret = (*func)(self, obj, value);
2792 if (ret < 0)
2793 return NULL;
2794 Py_INCREF(Py_None);
2795 return Py_None;
2796}
Guido van Rossum22b13872002-08-06 21:41:44 +00002797
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00002798static PyObject *
2799wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
2800{
2801 descrsetfunc func = (descrsetfunc)wrapped;
2802 PyObject *obj;
2803 int ret;
2804
2805 if (!PyArg_ParseTuple(args, "O", &obj))
2806 return NULL;
2807 ret = (*func)(self, obj, NULL);
2808 if (ret < 0)
2809 return NULL;
2810 Py_INCREF(Py_None);
2811 return Py_None;
2812}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002813
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002815wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816{
2817 initproc func = (initproc)wrapped;
2818
Guido van Rossumc8e56452001-10-22 00:43:43 +00002819 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820 return NULL;
2821 Py_INCREF(Py_None);
2822 return Py_None;
2823}
2824
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002826tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002827{
Barry Warsaw60f01882001-08-22 19:24:42 +00002828 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002829 PyObject *arg0, *res;
2830
2831 if (self == NULL || !PyType_Check(self))
2832 Py_FatalError("__new__() called with non-type 'self'");
2833 type = (PyTypeObject *)self;
2834 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002835 PyErr_Format(PyExc_TypeError,
2836 "%s.__new__(): not enough arguments",
2837 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002838 return NULL;
2839 }
2840 arg0 = PyTuple_GET_ITEM(args, 0);
2841 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002842 PyErr_Format(PyExc_TypeError,
2843 "%s.__new__(X): X is not a type object (%s)",
2844 type->tp_name,
2845 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002846 return NULL;
2847 }
2848 subtype = (PyTypeObject *)arg0;
2849 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002850 PyErr_Format(PyExc_TypeError,
2851 "%s.__new__(%s): %s is not a subtype of %s",
2852 type->tp_name,
2853 subtype->tp_name,
2854 subtype->tp_name,
2855 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002856 return NULL;
2857 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002858
2859 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002860 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002861 most derived base that's not a heap type is this type. */
2862 staticbase = subtype;
2863 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2864 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002865 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002866 PyErr_Format(PyExc_TypeError,
2867 "%s.__new__(%s) is not safe, use %s.__new__()",
2868 type->tp_name,
2869 subtype->tp_name,
2870 staticbase == NULL ? "?" : staticbase->tp_name);
2871 return NULL;
2872 }
2873
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002874 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2875 if (args == NULL)
2876 return NULL;
2877 res = type->tp_new(subtype, args, kwds);
2878 Py_DECREF(args);
2879 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002880}
2881
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002882static struct PyMethodDef tp_new_methoddef[] = {
2883 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2884 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002885 {0}
2886};
2887
2888static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002889add_tp_new_wrapper(PyTypeObject *type)
2890{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002891 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002892
Guido van Rossum687ae002001-10-15 22:03:32 +00002893 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002894 return 0;
2895 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002896 if (func == NULL)
2897 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002898 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002899}
2900
Guido van Rossumf040ede2001-08-07 16:40:56 +00002901/* Slot wrappers that call the corresponding __foo__ slot. See comments
2902 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903
Guido van Rossumdc91b992001-08-08 22:26:22 +00002904#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002905static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002906FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002908 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002909 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910}
2911
Guido van Rossumdc91b992001-08-08 22:26:22 +00002912#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002913static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002914FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002916 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002917 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918}
2919
Guido van Rossumdc91b992001-08-08 22:26:22 +00002920
2921#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002922static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002923FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002924{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002925 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002926 int do_other = self->ob_type != other->ob_type && \
2927 other->ob_type->tp_as_number != NULL && \
2928 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002929 if (self->ob_type->tp_as_number != NULL && \
2930 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2931 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002932 if (do_other && \
2933 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2934 r = call_maybe( \
2935 other, ROPSTR, &rcache_str, "(O)", self); \
2936 if (r != Py_NotImplemented) \
2937 return r; \
2938 Py_DECREF(r); \
2939 do_other = 0; \
2940 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002941 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002942 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002943 if (r != Py_NotImplemented || \
2944 other->ob_type == self->ob_type) \
2945 return r; \
2946 Py_DECREF(r); \
2947 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002948 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002949 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002950 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002951 } \
2952 Py_INCREF(Py_NotImplemented); \
2953 return Py_NotImplemented; \
2954}
2955
2956#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2957 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2958
2959#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2960static PyObject * \
2961FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2962{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002963 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002964 return call_method(self, OPSTR, &cache_str, \
2965 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002966}
2967
2968static int
2969slot_sq_length(PyObject *self)
2970{
Guido van Rossum2730b132001-08-28 18:22:14 +00002971 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002972 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002973 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974
2975 if (res == NULL)
2976 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002977 len = (int)PyInt_AsLong(res);
2978 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00002979 if (len == -1 && PyErr_Occurred())
2980 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00002981 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00002982 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00002983 "__len__() should return >= 0");
2984 return -1;
2985 }
Guido van Rossum26111622001-10-01 16:42:49 +00002986 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987}
2988
Guido van Rossumdc91b992001-08-08 22:26:22 +00002989SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2990SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002991
2992/* Super-optimized version of slot_sq_item.
2993 Other slots could do the same... */
2994static PyObject *
2995slot_sq_item(PyObject *self, int i)
2996{
2997 static PyObject *getitem_str;
2998 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2999 descrgetfunc f;
3000
3001 if (getitem_str == NULL) {
3002 getitem_str = PyString_InternFromString("__getitem__");
3003 if (getitem_str == NULL)
3004 return NULL;
3005 }
3006 func = _PyType_Lookup(self->ob_type, getitem_str);
3007 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003008 if ((f = func->ob_type->tp_descr_get) == NULL)
3009 Py_INCREF(func);
3010 else
3011 func = f(func, self, (PyObject *)(self->ob_type));
3012 ival = PyInt_FromLong(i);
3013 if (ival != NULL) {
3014 args = PyTuple_New(1);
3015 if (args != NULL) {
3016 PyTuple_SET_ITEM(args, 0, ival);
3017 retval = PyObject_Call(func, args, NULL);
3018 Py_XDECREF(args);
3019 Py_XDECREF(func);
3020 return retval;
3021 }
3022 }
3023 }
3024 else {
3025 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3026 }
3027 Py_XDECREF(args);
3028 Py_XDECREF(ival);
3029 Py_XDECREF(func);
3030 return NULL;
3031}
3032
Guido van Rossumdc91b992001-08-08 22:26:22 +00003033SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003034
3035static int
3036slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3037{
3038 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003039 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040
3041 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003042 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003043 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003045 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003046 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003047 if (res == NULL)
3048 return -1;
3049 Py_DECREF(res);
3050 return 0;
3051}
3052
3053static int
3054slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3055{
3056 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003057 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058
3059 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003060 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003061 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003062 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003063 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003064 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065 if (res == NULL)
3066 return -1;
3067 Py_DECREF(res);
3068 return 0;
3069}
3070
3071static int
3072slot_sq_contains(PyObject *self, PyObject *value)
3073{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003074 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003075 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003076
Guido van Rossum55f20992001-10-01 17:18:22 +00003077 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003078
3079 if (func != NULL) {
3080 args = Py_BuildValue("(O)", value);
3081 if (args == NULL)
3082 res = NULL;
3083 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003084 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003085 Py_DECREF(args);
3086 }
3087 Py_DECREF(func);
3088 if (res == NULL)
3089 return -1;
3090 return PyObject_IsTrue(res);
3091 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003092 else if (PyErr_Occurred())
3093 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003094 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003095 return _PySequence_IterSearch(self, value,
3096 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098}
3099
Guido van Rossumdc91b992001-08-08 22:26:22 +00003100SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3101SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102
3103#define slot_mp_length slot_sq_length
3104
Guido van Rossumdc91b992001-08-08 22:26:22 +00003105SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106
3107static int
3108slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3109{
3110 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003111 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112
3113 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003114 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003115 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003117 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003118 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119 if (res == NULL)
3120 return -1;
3121 Py_DECREF(res);
3122 return 0;
3123}
3124
Guido van Rossumdc91b992001-08-08 22:26:22 +00003125SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3126SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3127SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3128SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3129SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3130SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3131
Jeremy Hylton938ace62002-07-17 16:30:39 +00003132static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003133
3134SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3135 nb_power, "__pow__", "__rpow__")
3136
3137static PyObject *
3138slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3139{
Guido van Rossum2730b132001-08-28 18:22:14 +00003140 static PyObject *pow_str;
3141
Guido van Rossumdc91b992001-08-08 22:26:22 +00003142 if (modulus == Py_None)
3143 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003144 /* Three-arg power doesn't use __rpow__. But ternary_op
3145 can call this when the second argument's type uses
3146 slot_nb_power, so check before calling self.__pow__. */
3147 if (self->ob_type->tp_as_number != NULL &&
3148 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3149 return call_method(self, "__pow__", &pow_str,
3150 "(OO)", other, modulus);
3151 }
3152 Py_INCREF(Py_NotImplemented);
3153 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003154}
3155
3156SLOT0(slot_nb_negative, "__neg__")
3157SLOT0(slot_nb_positive, "__pos__")
3158SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003159
3160static int
3161slot_nb_nonzero(PyObject *self)
3162{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003163 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003164 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165
Guido van Rossum55f20992001-10-01 17:18:22 +00003166 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003167 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003168 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003169 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003170 func = lookup_maybe(self, "__len__", &len_str);
3171 if (func == NULL) {
3172 if (PyErr_Occurred())
3173 return -1;
3174 else
3175 return 1;
3176 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003177 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003178 res = PyObject_CallObject(func, NULL);
3179 Py_DECREF(func);
3180 if (res == NULL)
3181 return -1;
3182 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183}
3184
Guido van Rossumdc91b992001-08-08 22:26:22 +00003185SLOT0(slot_nb_invert, "__invert__")
3186SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3187SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3188SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3189SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3190SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003191
3192static int
3193slot_nb_coerce(PyObject **a, PyObject **b)
3194{
3195 static PyObject *coerce_str;
3196 PyObject *self = *a, *other = *b;
3197
3198 if (self->ob_type->tp_as_number != NULL &&
3199 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3200 PyObject *r;
3201 r = call_maybe(
3202 self, "__coerce__", &coerce_str, "(O)", other);
3203 if (r == NULL)
3204 return -1;
3205 if (r == Py_NotImplemented) {
3206 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003207 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003208 else {
3209 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3210 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003211 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003212 Py_DECREF(r);
3213 return -1;
3214 }
3215 *a = PyTuple_GET_ITEM(r, 0);
3216 Py_INCREF(*a);
3217 *b = PyTuple_GET_ITEM(r, 1);
3218 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003219 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003220 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003221 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003222 }
3223 if (other->ob_type->tp_as_number != NULL &&
3224 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3225 PyObject *r;
3226 r = call_maybe(
3227 other, "__coerce__", &coerce_str, "(O)", self);
3228 if (r == NULL)
3229 return -1;
3230 if (r == Py_NotImplemented) {
3231 Py_DECREF(r);
3232 return 1;
3233 }
3234 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3235 PyErr_SetString(PyExc_TypeError,
3236 "__coerce__ didn't return a 2-tuple");
3237 Py_DECREF(r);
3238 return -1;
3239 }
3240 *a = PyTuple_GET_ITEM(r, 1);
3241 Py_INCREF(*a);
3242 *b = PyTuple_GET_ITEM(r, 0);
3243 Py_INCREF(*b);
3244 Py_DECREF(r);
3245 return 0;
3246 }
3247 return 1;
3248}
3249
Guido van Rossumdc91b992001-08-08 22:26:22 +00003250SLOT0(slot_nb_int, "__int__")
3251SLOT0(slot_nb_long, "__long__")
3252SLOT0(slot_nb_float, "__float__")
3253SLOT0(slot_nb_oct, "__oct__")
3254SLOT0(slot_nb_hex, "__hex__")
3255SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3256SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3257SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3258SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3259SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3260SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3261SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3262SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3263SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3264SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3265SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3266SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3267 "__floordiv__", "__rfloordiv__")
3268SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3269SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3270SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003271
3272static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003275 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003276 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003277 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003278
Guido van Rossum60718732001-08-28 17:47:51 +00003279 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003280 if (func == NULL) {
3281 PyErr_Clear();
3282 }
3283 else {
3284 args = Py_BuildValue("(O)", other);
3285 if (args == NULL)
3286 res = NULL;
3287 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003288 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003289 Py_DECREF(args);
3290 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003291 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003292 if (res != Py_NotImplemented) {
3293 if (res == NULL)
3294 return -2;
3295 c = PyInt_AsLong(res);
3296 Py_DECREF(res);
3297 if (c == -1 && PyErr_Occurred())
3298 return -2;
3299 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3300 }
3301 Py_DECREF(res);
3302 }
3303 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304}
3305
Guido van Rossumab3b0342001-09-18 20:38:53 +00003306/* This slot is published for the benefit of try_3way_compare in object.c */
3307int
3308_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003309{
3310 int c;
3311
Guido van Rossumab3b0342001-09-18 20:38:53 +00003312 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003313 c = half_compare(self, other);
3314 if (c <= 1)
3315 return c;
3316 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003317 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003318 c = half_compare(other, self);
3319 if (c < -1)
3320 return -2;
3321 if (c <= 1)
3322 return -c;
3323 }
3324 return (void *)self < (void *)other ? -1 :
3325 (void *)self > (void *)other ? 1 : 0;
3326}
3327
3328static PyObject *
3329slot_tp_repr(PyObject *self)
3330{
3331 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003332 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003333
Guido van Rossum60718732001-08-28 17:47:51 +00003334 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003335 if (func != NULL) {
3336 res = PyEval_CallObject(func, NULL);
3337 Py_DECREF(func);
3338 return res;
3339 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003340 PyErr_Clear();
3341 return PyString_FromFormat("<%s object at %p>",
3342 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003343}
3344
3345static PyObject *
3346slot_tp_str(PyObject *self)
3347{
3348 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003349 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003350
Guido van Rossum60718732001-08-28 17:47:51 +00003351 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003352 if (func != NULL) {
3353 res = PyEval_CallObject(func, NULL);
3354 Py_DECREF(func);
3355 return res;
3356 }
3357 else {
3358 PyErr_Clear();
3359 return slot_tp_repr(self);
3360 }
3361}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362
3363static long
3364slot_tp_hash(PyObject *self)
3365{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003366 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003367 static PyObject *hash_str, *eq_str, *cmp_str;
3368
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369 long h;
3370
Guido van Rossum60718732001-08-28 17:47:51 +00003371 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003372
3373 if (func != NULL) {
3374 res = PyEval_CallObject(func, NULL);
3375 Py_DECREF(func);
3376 if (res == NULL)
3377 return -1;
3378 h = PyInt_AsLong(res);
3379 }
3380 else {
3381 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003382 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003383 if (func == NULL) {
3384 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003385 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003386 }
3387 if (func != NULL) {
3388 Py_DECREF(func);
3389 PyErr_SetString(PyExc_TypeError, "unhashable type");
3390 return -1;
3391 }
3392 PyErr_Clear();
3393 h = _Py_HashPointer((void *)self);
3394 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395 if (h == -1 && !PyErr_Occurred())
3396 h = -2;
3397 return h;
3398}
3399
3400static PyObject *
3401slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3402{
Guido van Rossum60718732001-08-28 17:47:51 +00003403 static PyObject *call_str;
3404 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003405 PyObject *res;
3406
3407 if (meth == NULL)
3408 return NULL;
3409 res = PyObject_Call(meth, args, kwds);
3410 Py_DECREF(meth);
3411 return res;
3412}
3413
Guido van Rossum14a6f832001-10-17 13:59:09 +00003414/* There are two slot dispatch functions for tp_getattro.
3415
3416 - slot_tp_getattro() is used when __getattribute__ is overridden
3417 but no __getattr__ hook is present;
3418
3419 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3420
Guido van Rossumc334df52002-04-04 23:44:47 +00003421 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3422 detects the absence of __getattr__ and then installs the simpler slot if
3423 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003424
Tim Peters6d6c1a32001-08-02 04:15:00 +00003425static PyObject *
3426slot_tp_getattro(PyObject *self, PyObject *name)
3427{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003428 static PyObject *getattribute_str = NULL;
3429 return call_method(self, "__getattribute__", &getattribute_str,
3430 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431}
3432
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003433static PyObject *
3434slot_tp_getattr_hook(PyObject *self, PyObject *name)
3435{
3436 PyTypeObject *tp = self->ob_type;
3437 PyObject *getattr, *getattribute, *res;
3438 static PyObject *getattribute_str = NULL;
3439 static PyObject *getattr_str = NULL;
3440
3441 if (getattr_str == NULL) {
3442 getattr_str = PyString_InternFromString("__getattr__");
3443 if (getattr_str == NULL)
3444 return NULL;
3445 }
3446 if (getattribute_str == NULL) {
3447 getattribute_str =
3448 PyString_InternFromString("__getattribute__");
3449 if (getattribute_str == NULL)
3450 return NULL;
3451 }
3452 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003453 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003454 /* No __getattr__ hook: use a simpler dispatcher */
3455 tp->tp_getattro = slot_tp_getattro;
3456 return slot_tp_getattro(self, name);
3457 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003458 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003459 if (getattribute == NULL ||
3460 (getattribute->ob_type == &PyWrapperDescr_Type &&
3461 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3462 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003463 res = PyObject_GenericGetAttr(self, name);
3464 else
3465 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003466 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003467 PyErr_Clear();
3468 res = PyObject_CallFunction(getattr, "OO", self, name);
3469 }
3470 return res;
3471}
3472
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473static int
3474slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3475{
3476 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003477 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478
3479 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003480 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003481 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003483 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003484 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485 if (res == NULL)
3486 return -1;
3487 Py_DECREF(res);
3488 return 0;
3489}
3490
3491/* Map rich comparison operators to their __xx__ namesakes */
3492static char *name_op[] = {
3493 "__lt__",
3494 "__le__",
3495 "__eq__",
3496 "__ne__",
3497 "__gt__",
3498 "__ge__",
3499};
3500
3501static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003502half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003503{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003504 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003505 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506
Guido van Rossum60718732001-08-28 17:47:51 +00003507 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003508 if (func == NULL) {
3509 PyErr_Clear();
3510 Py_INCREF(Py_NotImplemented);
3511 return Py_NotImplemented;
3512 }
3513 args = Py_BuildValue("(O)", other);
3514 if (args == NULL)
3515 res = NULL;
3516 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003517 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003518 Py_DECREF(args);
3519 }
3520 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521 return res;
3522}
3523
Guido van Rossumb8f63662001-08-15 23:57:02 +00003524/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3525static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3526
3527static PyObject *
3528slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3529{
3530 PyObject *res;
3531
3532 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3533 res = half_richcompare(self, other, op);
3534 if (res != Py_NotImplemented)
3535 return res;
3536 Py_DECREF(res);
3537 }
3538 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3539 res = half_richcompare(other, self, swapped_op[op]);
3540 if (res != Py_NotImplemented) {
3541 return res;
3542 }
3543 Py_DECREF(res);
3544 }
3545 Py_INCREF(Py_NotImplemented);
3546 return Py_NotImplemented;
3547}
3548
3549static PyObject *
3550slot_tp_iter(PyObject *self)
3551{
3552 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003553 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003554
Guido van Rossum60718732001-08-28 17:47:51 +00003555 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003556 if (func != NULL) {
3557 res = PyObject_CallObject(func, NULL);
3558 Py_DECREF(func);
3559 return res;
3560 }
3561 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003562 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003563 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003564 PyErr_SetString(PyExc_TypeError,
3565 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003566 return NULL;
3567 }
3568 Py_DECREF(func);
3569 return PySeqIter_New(self);
3570}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003571
3572static PyObject *
3573slot_tp_iternext(PyObject *self)
3574{
Guido van Rossum2730b132001-08-28 18:22:14 +00003575 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003576 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577}
3578
Guido van Rossum1a493502001-08-17 16:47:50 +00003579static PyObject *
3580slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3581{
3582 PyTypeObject *tp = self->ob_type;
3583 PyObject *get;
3584 static PyObject *get_str = NULL;
3585
3586 if (get_str == NULL) {
3587 get_str = PyString_InternFromString("__get__");
3588 if (get_str == NULL)
3589 return NULL;
3590 }
3591 get = _PyType_Lookup(tp, get_str);
3592 if (get == NULL) {
3593 /* Avoid further slowdowns */
3594 if (tp->tp_descr_get == slot_tp_descr_get)
3595 tp->tp_descr_get = NULL;
3596 Py_INCREF(self);
3597 return self;
3598 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003599 if (obj == NULL)
3600 obj = Py_None;
3601 if (type == NULL)
3602 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003603 return PyObject_CallFunction(get, "OOO", self, obj, type);
3604}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003605
3606static int
3607slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3608{
Guido van Rossum2c252392001-08-24 10:13:31 +00003609 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003610 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003611
3612 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003613 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003614 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003615 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003616 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003617 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618 if (res == NULL)
3619 return -1;
3620 Py_DECREF(res);
3621 return 0;
3622}
3623
3624static int
3625slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3626{
Guido van Rossum60718732001-08-28 17:47:51 +00003627 static PyObject *init_str;
3628 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629 PyObject *res;
3630
3631 if (meth == NULL)
3632 return -1;
3633 res = PyObject_Call(meth, args, kwds);
3634 Py_DECREF(meth);
3635 if (res == NULL)
3636 return -1;
3637 Py_DECREF(res);
3638 return 0;
3639}
3640
3641static PyObject *
3642slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3643{
3644 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3645 PyObject *newargs, *x;
3646 int i, n;
3647
3648 if (func == NULL)
3649 return NULL;
3650 assert(PyTuple_Check(args));
3651 n = PyTuple_GET_SIZE(args);
3652 newargs = PyTuple_New(n+1);
3653 if (newargs == NULL)
3654 return NULL;
3655 Py_INCREF(type);
3656 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3657 for (i = 0; i < n; i++) {
3658 x = PyTuple_GET_ITEM(args, i);
3659 Py_INCREF(x);
3660 PyTuple_SET_ITEM(newargs, i+1, x);
3661 }
3662 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003663 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003664 Py_DECREF(func);
3665 return x;
3666}
3667
Guido van Rossumfebd61d2002-08-08 20:55:20 +00003668static void
3669slot_tp_del(PyObject *self)
3670{
3671 static PyObject *del_str = NULL;
3672 PyObject *del, *res;
3673 PyObject *error_type, *error_value, *error_traceback;
3674
3675 /* Temporarily resurrect the object. */
3676 assert(self->ob_refcnt == 0);
3677 self->ob_refcnt = 1;
3678
3679 /* Save the current exception, if any. */
3680 PyErr_Fetch(&error_type, &error_value, &error_traceback);
3681
3682 /* Execute __del__ method, if any. */
3683 del = lookup_maybe(self, "__del__", &del_str);
3684 if (del != NULL) {
3685 res = PyEval_CallObject(del, NULL);
3686 if (res == NULL)
3687 PyErr_WriteUnraisable(del);
3688 else
3689 Py_DECREF(res);
3690 Py_DECREF(del);
3691 }
3692
3693 /* Restore the saved exception. */
3694 PyErr_Restore(error_type, error_value, error_traceback);
3695
3696 /* Undo the temporary resurrection; can't use DECREF here, it would
3697 * cause a recursive call.
3698 */
3699 assert(self->ob_refcnt > 0);
3700 if (--self->ob_refcnt == 0)
3701 return; /* this is the normal path out */
3702
3703 /* __del__ resurrected it! Make it look like the original Py_DECREF
3704 * never happened.
3705 */
3706 {
3707 int refcnt = self->ob_refcnt;
3708 _Py_NewReference(self);
3709 self->ob_refcnt = refcnt;
3710 }
3711 assert(!PyType_IS_GC(self->ob_type) ||
3712 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
3713 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
3714 * _Py_NewReference bumped it again, so that's a wash.
3715 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
3716 * chain, so no more to do there either.
3717 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
3718 * _Py_NewReference bumped tp_allocs: both of those need to be
3719 * undone.
3720 */
3721#ifdef COUNT_ALLOCS
3722 --self->ob_type->tp_frees;
3723 --self->ob_type->tp_allocs;
3724#endif
3725}
3726
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003727
3728/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3729 functions. The offsets here are relative to the 'etype' structure, which
3730 incorporates the additional structures used for numbers, sequences and
3731 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3732 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003733 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3734 terminated with an all-zero entry. (This table is further initialized and
3735 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003736
Guido van Rossum6d204072001-10-21 00:44:31 +00003737typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003738
3739#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003740#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003741#undef ETSLOT
3742#undef SQSLOT
3743#undef MPSLOT
3744#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003745#undef UNSLOT
3746#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003747#undef BINSLOT
3748#undef RBINSLOT
3749
Guido van Rossum6d204072001-10-21 00:44:31 +00003750#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3751 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003752#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3753 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3754 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003755#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3756 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3757#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3758 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3759#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3760 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3761#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3762 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3763#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3764 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3765 "x." NAME "() <==> " DOC)
3766#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3767 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3768 "x." NAME "(y) <==> x" DOC "y")
3769#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3770 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3771 "x." NAME "(y) <==> x" DOC "y")
3772#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3773 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3774 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003775
3776static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003777 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3778 "x.__len__() <==> len(x)"),
3779 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3780 "x.__add__(y) <==> x+y"),
3781 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3782 "x.__mul__(n) <==> x*n"),
3783 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3784 "x.__rmul__(n) <==> n*x"),
3785 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3786 "x.__getitem__(y) <==> x[y]"),
3787 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3788 "x.__getslice__(i, j) <==> x[i:j]"),
3789 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3790 "x.__setitem__(i, y) <==> x[i]=y"),
3791 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3792 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003793 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003794 wrap_intintobjargproc,
3795 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3796 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3797 "x.__delslice__(i, j) <==> del x[i:j]"),
3798 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3799 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003800 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003801 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003802 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003803 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003804
Guido van Rossum6d204072001-10-21 00:44:31 +00003805 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3806 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003807 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003808 wrap_binaryfunc,
3809 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003810 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003811 wrap_objobjargproc,
3812 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003813 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003814 wrap_delitem,
3815 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003816
Guido van Rossum6d204072001-10-21 00:44:31 +00003817 BINSLOT("__add__", nb_add, slot_nb_add,
3818 "+"),
3819 RBINSLOT("__radd__", nb_add, slot_nb_add,
3820 "+"),
3821 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3822 "-"),
3823 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3824 "-"),
3825 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3826 "*"),
3827 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3828 "*"),
3829 BINSLOT("__div__", nb_divide, slot_nb_divide,
3830 "/"),
3831 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3832 "/"),
3833 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3834 "%"),
3835 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3836 "%"),
3837 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3838 "divmod(x, y)"),
3839 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3840 "divmod(y, x)"),
3841 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3842 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3843 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3844 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3845 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3846 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3847 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3848 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003849 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003850 "x != 0"),
3851 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3852 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3853 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3854 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3855 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3856 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3857 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3858 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3859 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3860 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3861 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3862 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3863 "x.__coerce__(y) <==> coerce(x, y)"),
3864 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3865 "int(x)"),
3866 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3867 "long(x)"),
3868 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3869 "float(x)"),
3870 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3871 "oct(x)"),
3872 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3873 "hex(x)"),
3874 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3875 wrap_binaryfunc, "+"),
3876 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3877 wrap_binaryfunc, "-"),
3878 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3879 wrap_binaryfunc, "*"),
3880 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3881 wrap_binaryfunc, "/"),
3882 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3883 wrap_binaryfunc, "%"),
3884 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3885 wrap_ternaryfunc, "**"),
3886 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3887 wrap_binaryfunc, "<<"),
3888 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3889 wrap_binaryfunc, ">>"),
3890 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3891 wrap_binaryfunc, "&"),
3892 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3893 wrap_binaryfunc, "^"),
3894 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3895 wrap_binaryfunc, "|"),
3896 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3897 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3898 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3899 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3900 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3901 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3902 IBSLOT("__itruediv__", nb_inplace_true_divide,
3903 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003904
Guido van Rossum6d204072001-10-21 00:44:31 +00003905 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3906 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003907 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003908 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3909 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003910 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003911 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3912 "x.__cmp__(y) <==> cmp(x,y)"),
3913 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3914 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003915 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3916 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003917 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003918 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3919 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3920 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3921 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3922 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3923 "x.__setattr__('name', value) <==> x.name = value"),
3924 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3925 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3926 "x.__delattr__('name') <==> del x.name"),
3927 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3928 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3929 "x.__lt__(y) <==> x<y"),
3930 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3931 "x.__le__(y) <==> x<=y"),
3932 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3933 "x.__eq__(y) <==> x==y"),
3934 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3935 "x.__ne__(y) <==> x!=y"),
3936 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3937 "x.__gt__(y) <==> x>y"),
3938 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3939 "x.__ge__(y) <==> x>=y"),
3940 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3941 "x.__iter__() <==> iter(x)"),
3942 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3943 "x.next() -> the next value, or raise StopIteration"),
3944 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3945 "descr.__get__(obj[, type]) -> value"),
3946 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3947 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003948 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
3949 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003950 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003951 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003952 "see x.__class__.__doc__ for signature",
3953 PyWrapperFlag_KEYWORDS),
3954 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00003955 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003956 {NULL}
3957};
3958
Guido van Rossumc334df52002-04-04 23:44:47 +00003959/* Given a type pointer and an offset gotten from a slotdef entry, return a
3960 pointer to the actual slot. This is not quite the same as simply adding
3961 the offset to the type pointer, since it takes care to indirect through the
3962 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3963 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003964static void **
3965slotptr(PyTypeObject *type, int offset)
3966{
3967 char *ptr;
3968
Guido van Rossum09638c12002-06-13 19:17:46 +00003969 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003970 assert(offset >= 0);
3971 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003972 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003973 ptr = (void *)type->tp_as_sequence;
3974 offset -= offsetof(etype, as_sequence);
3975 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003976 else if (offset >= offsetof(etype, as_mapping)) {
3977 ptr = (void *)type->tp_as_mapping;
3978 offset -= offsetof(etype, as_mapping);
3979 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003980 else if (offset >= offsetof(etype, as_number)) {
3981 ptr = (void *)type->tp_as_number;
3982 offset -= offsetof(etype, as_number);
3983 }
3984 else {
3985 ptr = (void *)type;
3986 }
3987 if (ptr != NULL)
3988 ptr += offset;
3989 return (void **)ptr;
3990}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003991
Guido van Rossumc334df52002-04-04 23:44:47 +00003992/* Length of array of slotdef pointers used to store slots with the
3993 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3994 the same __name__, for any __name__. Since that's a static property, it is
3995 appropriate to declare fixed-size arrays for this. */
3996#define MAX_EQUIV 10
3997
3998/* Return a slot pointer for a given name, but ONLY if the attribute has
3999 exactly one slot function. The name must be an interned string. */
4000static void **
4001resolve_slotdups(PyTypeObject *type, PyObject *name)
4002{
4003 /* XXX Maybe this could be optimized more -- but is it worth it? */
4004
4005 /* pname and ptrs act as a little cache */
4006 static PyObject *pname;
4007 static slotdef *ptrs[MAX_EQUIV];
4008 slotdef *p, **pp;
4009 void **res, **ptr;
4010
4011 if (pname != name) {
4012 /* Collect all slotdefs that match name into ptrs. */
4013 pname = name;
4014 pp = ptrs;
4015 for (p = slotdefs; p->name_strobj; p++) {
4016 if (p->name_strobj == name)
4017 *pp++ = p;
4018 }
4019 *pp = NULL;
4020 }
4021
4022 /* Look in all matching slots of the type; if exactly one of these has
4023 a filled-in slot, return its value. Otherwise return NULL. */
4024 res = NULL;
4025 for (pp = ptrs; *pp; pp++) {
4026 ptr = slotptr(type, (*pp)->offset);
4027 if (ptr == NULL || *ptr == NULL)
4028 continue;
4029 if (res != NULL)
4030 return NULL;
4031 res = ptr;
4032 }
4033 return res;
4034}
4035
4036/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4037 does some incredibly complex thinking and then sticks something into the
4038 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4039 interests, and then stores a generic wrapper or a specific function into
4040 the slot.) Return a pointer to the next slotdef with a different offset,
4041 because that's convenient for fixup_slot_dispatchers(). */
4042static slotdef *
4043update_one_slot(PyTypeObject *type, slotdef *p)
4044{
4045 PyObject *descr;
4046 PyWrapperDescrObject *d;
4047 void *generic = NULL, *specific = NULL;
4048 int use_generic = 0;
4049 int offset = p->offset;
4050 void **ptr = slotptr(type, offset);
4051
4052 if (ptr == NULL) {
4053 do {
4054 ++p;
4055 } while (p->offset == offset);
4056 return p;
4057 }
4058 do {
4059 descr = _PyType_Lookup(type, p->name_strobj);
4060 if (descr == NULL)
4061 continue;
4062 if (descr->ob_type == &PyWrapperDescr_Type) {
4063 void **tptr = resolve_slotdups(type, p->name_strobj);
4064 if (tptr == NULL || tptr == ptr)
4065 generic = p->function;
4066 d = (PyWrapperDescrObject *)descr;
4067 if (d->d_base->wrapper == p->wrapper &&
4068 PyType_IsSubtype(type, d->d_type))
4069 {
4070 if (specific == NULL ||
4071 specific == d->d_wrapped)
4072 specific = d->d_wrapped;
4073 else
4074 use_generic = 1;
4075 }
4076 }
4077 else {
4078 use_generic = 1;
4079 generic = p->function;
4080 }
4081 } while ((++p)->offset == offset);
4082 if (specific && !use_generic)
4083 *ptr = specific;
4084 else
4085 *ptr = generic;
4086 return p;
4087}
4088
Guido van Rossum22b13872002-08-06 21:41:44 +00004089static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004090 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004091
Guido van Rossumc334df52002-04-04 23:44:47 +00004092/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4093 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004094static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004095update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004096{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004097 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004098
Guido van Rossumc334df52002-04-04 23:44:47 +00004099 for (pp = pp0; *pp; pp++)
4100 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004101 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004102}
4103
Guido van Rossumc334df52002-04-04 23:44:47 +00004104/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4105 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004106static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004107recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004108{
4109 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004110 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004111 int i, n;
4112
4113 subclasses = type->tp_subclasses;
4114 if (subclasses == NULL)
4115 return 0;
4116 assert(PyList_Check(subclasses));
4117 n = PyList_GET_SIZE(subclasses);
4118 for (i = 0; i < n; i++) {
4119 ref = PyList_GET_ITEM(subclasses, i);
4120 assert(PyWeakref_CheckRef(ref));
4121 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004122 assert(subclass != NULL);
4123 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004124 continue;
4125 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004126 /* Avoid recursing down into unaffected classes */
4127 dict = subclass->tp_dict;
4128 if (dict != NULL && PyDict_Check(dict) &&
4129 PyDict_GetItem(dict, name) != NULL)
4130 continue;
4131 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004132 return -1;
4133 }
4134 return 0;
4135}
4136
Guido van Rossumc334df52002-04-04 23:44:47 +00004137/* Comparison function for qsort() to compare slotdefs by their offset, and
4138 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004139static int
4140slotdef_cmp(const void *aa, const void *bb)
4141{
4142 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4143 int c = a->offset - b->offset;
4144 if (c != 0)
4145 return c;
4146 else
4147 return a - b;
4148}
4149
Guido van Rossumc334df52002-04-04 23:44:47 +00004150/* Initialize the slotdefs table by adding interned string objects for the
4151 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004152static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004153init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004154{
4155 slotdef *p;
4156 static int initialized = 0;
4157
4158 if (initialized)
4159 return;
4160 for (p = slotdefs; p->name; p++) {
4161 p->name_strobj = PyString_InternFromString(p->name);
4162 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004163 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004164 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004165 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4166 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004167 initialized = 1;
4168}
4169
Guido van Rossumc334df52002-04-04 23:44:47 +00004170/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004171static int
4172update_slot(PyTypeObject *type, PyObject *name)
4173{
Guido van Rossumc334df52002-04-04 23:44:47 +00004174 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004175 slotdef *p;
4176 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004177 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004178
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004179 init_slotdefs();
4180 pp = ptrs;
4181 for (p = slotdefs; p->name; p++) {
4182 /* XXX assume name is interned! */
4183 if (p->name_strobj == name)
4184 *pp++ = p;
4185 }
4186 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004187 for (pp = ptrs; *pp; pp++) {
4188 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004189 offset = p->offset;
4190 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004191 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004192 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004193 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004194 if (ptrs[0] == NULL)
4195 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004196 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004197}
4198
Guido van Rossumc334df52002-04-04 23:44:47 +00004199/* Store the proper functions in the slot dispatches at class (type)
4200 definition time, based upon which operations the class overrides in its
4201 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004203fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004205 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004207 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004208 for (p = slotdefs; p->name; )
4209 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004210}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004211
Guido van Rossum6d204072001-10-21 00:44:31 +00004212/* This function is called by PyType_Ready() to populate the type's
4213 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004214 function slot (like tp_repr) that's defined in the type, one or more
4215 corresponding descriptors are added in the type's tp_dict dictionary
4216 under the appropriate name (like __repr__). Some function slots
4217 cause more than one descriptor to be added (for example, the nb_add
4218 slot adds both __add__ and __radd__ descriptors) and some function
4219 slots compete for the same descriptor (for example both sq_item and
4220 mp_subscript generate a __getitem__ descriptor).
4221
4222 In the latter case, the first slotdef entry encoutered wins. Since
4223 slotdef entries are sorted by the offset of the slot in the etype
4224 struct, this gives us some control over disambiguating between
4225 competing slots: the members of struct etype are listed from most
4226 general to least general, so the most general slot is preferred. In
4227 particular, because as_mapping comes before as_sequence, for a type
4228 that defines both mp_subscript and sq_item, mp_subscript wins.
4229
4230 This only adds new descriptors and doesn't overwrite entries in
4231 tp_dict that were previously defined. The descriptors contain a
4232 reference to the C function they must call, so that it's safe if they
4233 are copied into a subtype's __dict__ and the subtype has a different
4234 C function in its slot -- calling the method defined by the
4235 descriptor will call the C function that was used to create it,
4236 rather than the C function present in the slot when it is called.
4237 (This is important because a subtype may have a C function in the
4238 slot that calls the method from the dictionary, and we want to avoid
4239 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004240
4241static int
4242add_operators(PyTypeObject *type)
4243{
4244 PyObject *dict = type->tp_dict;
4245 slotdef *p;
4246 PyObject *descr;
4247 void **ptr;
4248
4249 init_slotdefs();
4250 for (p = slotdefs; p->name; p++) {
4251 if (p->wrapper == NULL)
4252 continue;
4253 ptr = slotptr(type, p->offset);
4254 if (!ptr || !*ptr)
4255 continue;
4256 if (PyDict_GetItem(dict, p->name_strobj))
4257 continue;
4258 descr = PyDescr_NewWrapper(type, p, *ptr);
4259 if (descr == NULL)
4260 return -1;
4261 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4262 return -1;
4263 Py_DECREF(descr);
4264 }
4265 if (type->tp_new != NULL) {
4266 if (add_tp_new_wrapper(type) < 0)
4267 return -1;
4268 }
4269 return 0;
4270}
4271
Guido van Rossum705f0f52001-08-24 16:47:00 +00004272
4273/* Cooperative 'super' */
4274
4275typedef struct {
4276 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004277 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004278 PyObject *obj;
4279} superobject;
4280
Guido van Rossum6f799372001-09-20 20:46:19 +00004281static PyMemberDef super_members[] = {
4282 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4283 "the class invoking super()"},
4284 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4285 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004286 {0}
4287};
4288
Guido van Rossum705f0f52001-08-24 16:47:00 +00004289static void
4290super_dealloc(PyObject *self)
4291{
4292 superobject *su = (superobject *)self;
4293
Guido van Rossum048eb752001-10-02 21:24:57 +00004294 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004295 Py_XDECREF(su->obj);
4296 Py_XDECREF(su->type);
4297 self->ob_type->tp_free(self);
4298}
4299
4300static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004301super_repr(PyObject *self)
4302{
4303 superobject *su = (superobject *)self;
4304
4305 if (su->obj)
4306 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004307 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004308 su->type ? su->type->tp_name : "NULL",
4309 su->obj->ob_type->tp_name);
4310 else
4311 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004312 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004313 su->type ? su->type->tp_name : "NULL");
4314}
4315
4316static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004317super_getattro(PyObject *self, PyObject *name)
4318{
4319 superobject *su = (superobject *)self;
4320
4321 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004322 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004323 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004324 descrgetfunc f;
4325 int i, n;
4326
Guido van Rossum155db9a2002-04-02 17:53:47 +00004327 starttype = su->obj->ob_type;
4328 mro = starttype->tp_mro;
4329
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004330 if (mro == NULL)
4331 n = 0;
4332 else {
4333 assert(PyTuple_Check(mro));
4334 n = PyTuple_GET_SIZE(mro);
4335 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004336 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004337 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004338 break;
4339 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004340 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004341 starttype = (PyTypeObject *)(su->obj);
4342 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004343 if (mro == NULL)
4344 n = 0;
4345 else {
4346 assert(PyTuple_Check(mro));
4347 n = PyTuple_GET_SIZE(mro);
4348 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004349 for (i = 0; i < n; i++) {
4350 if ((PyObject *)(su->type) ==
4351 PyTuple_GET_ITEM(mro, i))
4352 break;
4353 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004354 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004355 i++;
4356 res = NULL;
4357 for (; i < n; i++) {
4358 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004359 if (PyType_Check(tmp))
4360 dict = ((PyTypeObject *)tmp)->tp_dict;
4361 else if (PyClass_Check(tmp))
4362 dict = ((PyClassObject *)tmp)->cl_dict;
4363 else
4364 continue;
4365 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004366 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004367 Py_INCREF(res);
4368 f = res->ob_type->tp_descr_get;
4369 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004370 tmp = f(res, su->obj,
4371 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004372 Py_DECREF(res);
4373 res = tmp;
4374 }
4375 return res;
4376 }
4377 }
4378 }
4379 return PyObject_GenericGetAttr(self, name);
4380}
4381
Guido van Rossum5b443c62001-12-03 15:38:28 +00004382static int
4383supercheck(PyTypeObject *type, PyObject *obj)
4384{
4385 if (!PyType_IsSubtype(obj->ob_type, type) &&
4386 !(PyType_Check(obj) &&
4387 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4388 PyErr_SetString(PyExc_TypeError,
4389 "super(type, obj): "
4390 "obj must be an instance or subtype of type");
4391 return -1;
4392 }
4393 else
4394 return 0;
4395}
4396
Guido van Rossum705f0f52001-08-24 16:47:00 +00004397static PyObject *
4398super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4399{
4400 superobject *su = (superobject *)self;
4401 superobject *new;
4402
4403 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4404 /* Not binding to an object, or already bound */
4405 Py_INCREF(self);
4406 return self;
4407 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004408 if (su->ob_type != &PySuper_Type)
4409 /* If su is an instance of a subclass of super,
4410 call its type */
4411 return PyObject_CallFunction((PyObject *)su->ob_type,
4412 "OO", su->type, obj);
4413 else {
4414 /* Inline the common case */
4415 if (supercheck(su->type, obj) < 0)
4416 return NULL;
4417 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4418 NULL, NULL);
4419 if (new == NULL)
4420 return NULL;
4421 Py_INCREF(su->type);
4422 Py_INCREF(obj);
4423 new->type = su->type;
4424 new->obj = obj;
4425 return (PyObject *)new;
4426 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004427}
4428
4429static int
4430super_init(PyObject *self, PyObject *args, PyObject *kwds)
4431{
4432 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004433 PyTypeObject *type;
4434 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004435
4436 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4437 return -1;
4438 if (obj == Py_None)
4439 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004440 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004441 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004442 Py_INCREF(type);
4443 Py_XINCREF(obj);
4444 su->type = type;
4445 su->obj = obj;
4446 return 0;
4447}
4448
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004449PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004450"super(type) -> unbound super object\n"
4451"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004452"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004453"Typical use to call a cooperative superclass method:\n"
4454"class C(B):\n"
4455" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004456" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004457
Guido van Rossum048eb752001-10-02 21:24:57 +00004458static int
4459super_traverse(PyObject *self, visitproc visit, void *arg)
4460{
4461 superobject *su = (superobject *)self;
4462 int err;
4463
4464#define VISIT(SLOT) \
4465 if (SLOT) { \
4466 err = visit((PyObject *)(SLOT), arg); \
4467 if (err) \
4468 return err; \
4469 }
4470
4471 VISIT(su->obj);
4472 VISIT(su->type);
4473
4474#undef VISIT
4475
4476 return 0;
4477}
4478
Guido van Rossum705f0f52001-08-24 16:47:00 +00004479PyTypeObject PySuper_Type = {
4480 PyObject_HEAD_INIT(&PyType_Type)
4481 0, /* ob_size */
4482 "super", /* tp_name */
4483 sizeof(superobject), /* tp_basicsize */
4484 0, /* tp_itemsize */
4485 /* methods */
4486 super_dealloc, /* tp_dealloc */
4487 0, /* tp_print */
4488 0, /* tp_getattr */
4489 0, /* tp_setattr */
4490 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004491 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004492 0, /* tp_as_number */
4493 0, /* tp_as_sequence */
4494 0, /* tp_as_mapping */
4495 0, /* tp_hash */
4496 0, /* tp_call */
4497 0, /* tp_str */
4498 super_getattro, /* tp_getattro */
4499 0, /* tp_setattro */
4500 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004501 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4502 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004503 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004504 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004505 0, /* tp_clear */
4506 0, /* tp_richcompare */
4507 0, /* tp_weaklistoffset */
4508 0, /* tp_iter */
4509 0, /* tp_iternext */
4510 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004511 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004512 0, /* tp_getset */
4513 0, /* tp_base */
4514 0, /* tp_dict */
4515 super_descr_get, /* tp_descr_get */
4516 0, /* tp_descr_set */
4517 0, /* tp_dictoffset */
4518 super_init, /* tp_init */
4519 PyType_GenericAlloc, /* tp_alloc */
4520 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004521 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004522};