blob: 3def1343c05a4f6d133819b4908278be979cd5f2 [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
Jeremy Hylton938ace62002-07-17 16:30:39 +0000359static PyObject *lookup_maybe(PyObject *, char *, PyObject **);
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000360
361static int
362call_finalizer(PyObject *self)
363{
364 static PyObject *del_str = NULL;
365 PyObject *del, *res;
366 PyObject *error_type, *error_value, *error_traceback;
367
368 /* Temporarily resurrect the object. */
Tim Peters34592512002-07-11 06:23:50 +0000369 assert(self->ob_refcnt == 0);
370 self->ob_refcnt = 1;
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000371
372 /* Save the current exception, if any. */
373 PyErr_Fetch(&error_type, &error_value, &error_traceback);
374
375 /* Execute __del__ method, if any. */
376 del = lookup_maybe(self, "__del__", &del_str);
377 if (del != NULL) {
378 res = PyEval_CallObject(del, NULL);
379 if (res == NULL)
380 PyErr_WriteUnraisable(del);
381 else
382 Py_DECREF(res);
383 Py_DECREF(del);
384 }
385
386 /* Restore the saved exception. */
387 PyErr_Restore(error_type, error_value, error_traceback);
388
389 /* Undo the temporary resurrection; can't use DECREF here, it would
390 * cause a recursive call.
391 */
Tim Peters34592512002-07-11 06:23:50 +0000392 assert(self->ob_refcnt > 0);
393 if (--self->ob_refcnt == 0)
394 return 0; /* this is the normal path out */
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000395
Tim Peters34592512002-07-11 06:23:50 +0000396 /* __del__ resurrected it! Make it look like the original Py_DECREF
397 * never happened.
398 */
399 {
400 int refcnt = self->ob_refcnt;
401 _Py_NewReference(self);
402 self->ob_refcnt = refcnt;
403 }
404 assert(_Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
405 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
406 * _Py_NewReference bumped it again, so that's a wash.
407 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
408 * chain, so no more to do there either.
409 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
410 * _Py_NewReference bumped tp_allocs: both of those need to be
411 * undone.
412 */
413#ifdef COUNT_ALLOCS
414 --self->ob_type->tp_frees;
415 --self->ob_type->tp_allocs;
416#endif
417 return -1; /* __del__ added a reference; don't delete now */
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000418}
419
Tim Peters6d6c1a32001-08-02 04:15:00 +0000420static void
421subtype_dealloc(PyObject *self)
422{
Guido van Rossum14227b42001-12-06 02:35:58 +0000423 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000424 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000425
426 /* This exists so we can DECREF self->ob_type */
427
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000428 if (call_finalizer(self) < 0)
429 return;
430
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000431 /* Find the nearest base with a different tp_dealloc
432 and clear slots while we're at it */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000434 base = type;
435 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
436 if (base->ob_size)
437 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438 base = base->tp_base;
439 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000440 }
441
Tim Peters6d6c1a32001-08-02 04:15:00 +0000442 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000443 if (type->tp_dictoffset && !base->tp_dictoffset) {
444 PyObject **dictptr = _PyObject_GetDictPtr(self);
445 if (dictptr != NULL) {
446 PyObject *dict = *dictptr;
447 if (dict != NULL) {
448 Py_DECREF(dict);
449 *dictptr = NULL;
450 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 }
452 }
453
Guido van Rossum9676b222001-08-17 20:32:36 +0000454 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000455 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000456 PyObject_ClearWeakRefs(self);
457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 /* Finalize GC if the base doesn't do GC and we do */
459 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000460 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461
462 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000463 assert(basedealloc);
464 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465
466 /* Can't reference self beyond this point */
467 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
468 Py_DECREF(type);
469 }
470}
471
Jeremy Hylton938ace62002-07-17 16:30:39 +0000472static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000473
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474/* type test with subclassing support */
475
476int
477PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
478{
479 PyObject *mro;
480
Guido van Rossum9478d072001-09-07 18:52:13 +0000481 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
482 return b == a || b == &PyBaseObject_Type;
483
Tim Peters6d6c1a32001-08-02 04:15:00 +0000484 mro = a->tp_mro;
485 if (mro != NULL) {
486 /* Deal with multiple inheritance without recursion
487 by walking the MRO tuple */
488 int i, n;
489 assert(PyTuple_Check(mro));
490 n = PyTuple_GET_SIZE(mro);
491 for (i = 0; i < n; i++) {
492 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
493 return 1;
494 }
495 return 0;
496 }
497 else {
498 /* a is not completely initilized yet; follow tp_base */
499 do {
500 if (a == b)
501 return 1;
502 a = a->tp_base;
503 } while (a != NULL);
504 return b == &PyBaseObject_Type;
505 }
506}
507
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000508/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000509 without looking in the instance dictionary
510 (so we can't use PyObject_GetAttr) but still binding
511 it to the instance. The arguments are the object,
512 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000513 static variable used to cache the interned Python string.
514
515 Two variants:
516
517 - lookup_maybe() returns NULL without raising an exception
518 when the _PyType_Lookup() call fails;
519
520 - lookup_method() always raises an exception upon errors.
521*/
Guido van Rossum60718732001-08-28 17:47:51 +0000522
523static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000524lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000525{
526 PyObject *res;
527
528 if (*attrobj == NULL) {
529 *attrobj = PyString_InternFromString(attrstr);
530 if (*attrobj == NULL)
531 return NULL;
532 }
533 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000534 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000535 descrgetfunc f;
536 if ((f = res->ob_type->tp_descr_get) == NULL)
537 Py_INCREF(res);
538 else
539 res = f(res, self, (PyObject *)(self->ob_type));
540 }
541 return res;
542}
543
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000544static PyObject *
545lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
546{
547 PyObject *res = lookup_maybe(self, attrstr, attrobj);
548 if (res == NULL && !PyErr_Occurred())
549 PyErr_SetObject(PyExc_AttributeError, *attrobj);
550 return res;
551}
552
Guido van Rossum2730b132001-08-28 18:22:14 +0000553/* A variation of PyObject_CallMethod that uses lookup_method()
554 instead of PyObject_GetAttrString(). This uses the same convention
555 as lookup_method to cache the interned name string object. */
556
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000557static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000558call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
559{
560 va_list va;
561 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000562 va_start(va, format);
563
Guido van Rossumda21c012001-10-03 00:50:18 +0000564 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000565 if (func == NULL) {
566 va_end(va);
567 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000568 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000569 return NULL;
570 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000571
572 if (format && *format)
573 args = Py_VaBuildValue(format, va);
574 else
575 args = PyTuple_New(0);
576
577 va_end(va);
578
579 if (args == NULL)
580 return NULL;
581
582 assert(PyTuple_Check(args));
583 retval = PyObject_Call(func, args, NULL);
584
585 Py_DECREF(args);
586 Py_DECREF(func);
587
588 return retval;
589}
590
591/* Clone of call_method() that returns NotImplemented when the lookup fails. */
592
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000593static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000594call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
595{
596 va_list va;
597 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000598 va_start(va, format);
599
Guido van Rossumda21c012001-10-03 00:50:18 +0000600 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000601 if (func == NULL) {
602 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000603 if (!PyErr_Occurred()) {
604 Py_INCREF(Py_NotImplemented);
605 return Py_NotImplemented;
606 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000607 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000608 }
609
610 if (format && *format)
611 args = Py_VaBuildValue(format, va);
612 else
613 args = PyTuple_New(0);
614
615 va_end(va);
616
Guido van Rossum717ce002001-09-14 16:58:08 +0000617 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000618 return NULL;
619
Guido van Rossum717ce002001-09-14 16:58:08 +0000620 assert(PyTuple_Check(args));
621 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000622
623 Py_DECREF(args);
624 Py_DECREF(func);
625
626 return retval;
627}
628
Tim Peters6d6c1a32001-08-02 04:15:00 +0000629/* Method resolution order algorithm from "Putting Metaclasses to Work"
630 by Forman and Danforth (Addison-Wesley 1999). */
631
632static int
633conservative_merge(PyObject *left, PyObject *right)
634{
635 int left_size;
636 int right_size;
637 int i, j, r, ok;
638 PyObject *temp, *rr;
639
640 assert(PyList_Check(left));
641 assert(PyList_Check(right));
642
643 again:
644 left_size = PyList_GET_SIZE(left);
645 right_size = PyList_GET_SIZE(right);
646 for (i = 0; i < left_size; i++) {
647 for (j = 0; j < right_size; j++) {
648 if (PyList_GET_ITEM(left, i) ==
649 PyList_GET_ITEM(right, j)) {
650 /* found a merge point */
651 temp = PyList_New(0);
652 if (temp == NULL)
653 return -1;
654 for (r = 0; r < j; r++) {
655 rr = PyList_GET_ITEM(right, r);
656 ok = PySequence_Contains(left, rr);
657 if (ok < 0) {
658 Py_DECREF(temp);
659 return -1;
660 }
661 if (!ok) {
662 ok = PyList_Append(temp, rr);
663 if (ok < 0) {
664 Py_DECREF(temp);
665 return -1;
666 }
667 }
668 }
669 ok = PyList_SetSlice(left, i, i, temp);
670 Py_DECREF(temp);
671 if (ok < 0)
672 return -1;
673 ok = PyList_SetSlice(right, 0, j+1, NULL);
674 if (ok < 0)
675 return -1;
676 goto again;
677 }
678 }
679 }
680 return PyList_SetSlice(left, left_size, left_size, right);
681}
682
683static int
684serious_order_disagreements(PyObject *left, PyObject *right)
685{
686 return 0; /* XXX later -- for now, we cheat: "don't do that" */
687}
688
Tim Petersa91e9642001-11-14 23:32:33 +0000689static int
690fill_classic_mro(PyObject *mro, PyObject *cls)
691{
692 PyObject *bases, *base;
693 int i, n;
694
695 assert(PyList_Check(mro));
696 assert(PyClass_Check(cls));
697 i = PySequence_Contains(mro, cls);
698 if (i < 0)
699 return -1;
700 if (!i) {
701 if (PyList_Append(mro, cls) < 0)
702 return -1;
703 }
704 bases = ((PyClassObject *)cls)->cl_bases;
705 assert(bases && PyTuple_Check(bases));
706 n = PyTuple_GET_SIZE(bases);
707 for (i = 0; i < n; i++) {
708 base = PyTuple_GET_ITEM(bases, i);
709 if (fill_classic_mro(mro, base) < 0)
710 return -1;
711 }
712 return 0;
713}
714
715static PyObject *
716classic_mro(PyObject *cls)
717{
718 PyObject *mro;
719
720 assert(PyClass_Check(cls));
721 mro = PyList_New(0);
722 if (mro != NULL) {
723 if (fill_classic_mro(mro, cls) == 0)
724 return mro;
725 Py_DECREF(mro);
726 }
727 return NULL;
728}
729
Tim Peters6d6c1a32001-08-02 04:15:00 +0000730static PyObject *
731mro_implementation(PyTypeObject *type)
732{
733 int i, n, ok;
734 PyObject *bases, *result;
735
Guido van Rossum63517572002-06-18 16:44:57 +0000736 if(type->tp_dict == NULL) {
737 if(PyType_Ready(type) < 0)
738 return NULL;
739 }
740
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 bases = type->tp_bases;
742 n = PyTuple_GET_SIZE(bases);
743 result = Py_BuildValue("[O]", (PyObject *)type);
744 if (result == NULL)
745 return NULL;
746 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000747 PyObject *base = PyTuple_GET_ITEM(bases, i);
748 PyObject *parentMRO;
749 if (PyType_Check(base))
750 parentMRO = PySequence_List(
751 ((PyTypeObject*)base)->tp_mro);
752 else
753 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000754 if (parentMRO == NULL) {
755 Py_DECREF(result);
756 return NULL;
757 }
758 if (serious_order_disagreements(result, parentMRO)) {
759 Py_DECREF(result);
760 return NULL;
761 }
762 ok = conservative_merge(result, parentMRO);
763 Py_DECREF(parentMRO);
764 if (ok < 0) {
765 Py_DECREF(result);
766 return NULL;
767 }
768 }
769 return result;
770}
771
772static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000773mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000774{
775 PyTypeObject *type = (PyTypeObject *)self;
776
Tim Peters6d6c1a32001-08-02 04:15:00 +0000777 return mro_implementation(type);
778}
779
780static int
781mro_internal(PyTypeObject *type)
782{
783 PyObject *mro, *result, *tuple;
784
785 if (type->ob_type == &PyType_Type) {
786 result = mro_implementation(type);
787 }
788 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000789 static PyObject *mro_str;
790 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791 if (mro == NULL)
792 return -1;
793 result = PyObject_CallObject(mro, NULL);
794 Py_DECREF(mro);
795 }
796 if (result == NULL)
797 return -1;
798 tuple = PySequence_Tuple(result);
799 Py_DECREF(result);
800 type->tp_mro = tuple;
801 return 0;
802}
803
804
805/* Calculate the best base amongst multiple base classes.
806 This is the first one that's on the path to the "solid base". */
807
808static PyTypeObject *
809best_base(PyObject *bases)
810{
811 int i, n;
812 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000813 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814
815 assert(PyTuple_Check(bases));
816 n = PyTuple_GET_SIZE(bases);
817 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000818 base = NULL;
819 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000821 base_proto = PyTuple_GET_ITEM(bases, i);
822 if (PyClass_Check(base_proto))
823 continue;
824 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825 PyErr_SetString(
826 PyExc_TypeError,
827 "bases must be types");
828 return NULL;
829 }
Tim Petersa91e9642001-11-14 23:32:33 +0000830 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000832 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000833 return NULL;
834 }
835 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000836 if (winner == NULL) {
837 winner = candidate;
838 base = base_i;
839 }
840 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841 ;
842 else if (PyType_IsSubtype(candidate, winner)) {
843 winner = candidate;
844 base = base_i;
845 }
846 else {
847 PyErr_SetString(
848 PyExc_TypeError,
849 "multiple bases have "
850 "instance lay-out conflict");
851 return NULL;
852 }
853 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000854 if (base == NULL)
855 PyErr_SetString(PyExc_TypeError,
856 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857 return base;
858}
859
860static int
861extra_ivars(PyTypeObject *type, PyTypeObject *base)
862{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000863 size_t t_size = type->tp_basicsize;
864 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000865
Guido van Rossum9676b222001-08-17 20:32:36 +0000866 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000867 if (type->tp_itemsize || base->tp_itemsize) {
868 /* If itemsize is involved, stricter rules */
869 return t_size != b_size ||
870 type->tp_itemsize != base->tp_itemsize;
871 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000872 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
873 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
874 t_size -= sizeof(PyObject *);
875 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
876 type->tp_dictoffset + sizeof(PyObject *) == t_size)
877 t_size -= sizeof(PyObject *);
878
879 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000880}
881
882static PyTypeObject *
883solid_base(PyTypeObject *type)
884{
885 PyTypeObject *base;
886
887 if (type->tp_base)
888 base = solid_base(type->tp_base);
889 else
890 base = &PyBaseObject_Type;
891 if (extra_ivars(type, base))
892 return type;
893 else
894 return base;
895}
896
Jeremy Hylton938ace62002-07-17 16:30:39 +0000897static void object_dealloc(PyObject *);
898static int object_init(PyObject *, PyObject *, PyObject *);
899static int update_slot(PyTypeObject *, PyObject *);
900static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000901
902static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000903subtype_dict(PyObject *obj, void *context)
904{
905 PyObject **dictptr = _PyObject_GetDictPtr(obj);
906 PyObject *dict;
907
908 if (dictptr == NULL) {
909 PyErr_SetString(PyExc_AttributeError,
910 "This object has no __dict__");
911 return NULL;
912 }
913 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000914 if (dict == NULL)
915 *dictptr = dict = PyDict_New();
916 Py_XINCREF(dict);
917 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000918}
919
Guido van Rossum6661be32001-10-26 04:26:12 +0000920static int
921subtype_setdict(PyObject *obj, PyObject *value, void *context)
922{
923 PyObject **dictptr = _PyObject_GetDictPtr(obj);
924 PyObject *dict;
925
926 if (dictptr == NULL) {
927 PyErr_SetString(PyExc_AttributeError,
928 "This object has no __dict__");
929 return -1;
930 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000931 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000932 PyErr_SetString(PyExc_TypeError,
933 "__dict__ must be set to a dictionary");
934 return -1;
935 }
936 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000937 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000938 *dictptr = value;
939 Py_XDECREF(dict);
940 return 0;
941}
942
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000943static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000944 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000945 {0},
946};
947
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000948/* bozo: __getstate__ that raises TypeError */
949
950static PyObject *
951bozo_func(PyObject *self, PyObject *args)
952{
953 PyErr_SetString(PyExc_TypeError,
954 "a class that defines __slots__ without "
955 "defining __getstate__ cannot be pickled");
956 return NULL;
957}
958
Neal Norwitz93c1e232002-03-31 16:06:11 +0000959static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000960
961static PyObject *bozo_obj = NULL;
962
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000963static int
964valid_identifier(PyObject *s)
965{
Guido van Rossum03013a02002-07-16 14:30:28 +0000966 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000967 int i, n;
968
969 if (!PyString_Check(s)) {
970 PyErr_SetString(PyExc_TypeError,
971 "__slots__ must be strings");
972 return 0;
973 }
Guido van Rossum03013a02002-07-16 14:30:28 +0000974 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000975 n = PyString_GET_SIZE(s);
976 /* We must reject an empty name. As a hack, we bump the
977 length to 1 so that the loop will balk on the trailing \0. */
978 if (n == 0)
979 n = 1;
980 for (i = 0; i < n; i++, p++) {
981 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
982 PyErr_SetString(PyExc_TypeError,
983 "__slots__ must be identifiers");
984 return 0;
985 }
986 }
987 return 1;
988}
989
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000990static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000991type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
992{
993 PyObject *name, *bases, *dict;
994 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +0000995 static char buffer[256];
996 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000997 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000999 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001000 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001
Tim Peters3abca122001-10-27 19:37:48 +00001002 assert(args != NULL && PyTuple_Check(args));
1003 assert(kwds == NULL || PyDict_Check(kwds));
1004
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001005 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001006 {
1007 const int nargs = PyTuple_GET_SIZE(args);
1008 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1009
1010 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1011 PyObject *x = PyTuple_GET_ITEM(args, 0);
1012 Py_INCREF(x->ob_type);
1013 return (PyObject *) x->ob_type;
1014 }
1015
1016 /* SF bug 475327 -- if that didn't trigger, we need 3
1017 arguments. but PyArg_ParseTupleAndKeywords below may give
1018 a msg saying type() needs exactly 3. */
1019 if (nargs + nkwds != 3) {
1020 PyErr_SetString(PyExc_TypeError,
1021 "type() takes 1 or 3 arguments");
1022 return NULL;
1023 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024 }
1025
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001026 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1028 &name,
1029 &PyTuple_Type, &bases,
1030 &PyDict_Type, &dict))
1031 return NULL;
1032
1033 /* Determine the proper metatype to deal with this,
1034 and check for metatype conflicts while we're at it.
1035 Note that if some other metatype wins to contract,
1036 it's possible that its instances are not types. */
1037 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001038 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 for (i = 0; i < nbases; i++) {
1040 tmp = PyTuple_GET_ITEM(bases, i);
1041 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001042 if (tmptype == &PyClass_Type)
1043 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001044 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001046 if (PyType_IsSubtype(tmptype, winner)) {
1047 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001048 continue;
1049 }
1050 PyErr_SetString(PyExc_TypeError,
1051 "metatype conflict among bases");
1052 return NULL;
1053 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001054 if (winner != metatype) {
1055 if (winner->tp_new != type_new) /* Pass it to the winner */
1056 return winner->tp_new(winner, args, kwds);
1057 metatype = winner;
1058 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001059
1060 /* Adjust for empty tuple bases */
1061 if (nbases == 0) {
1062 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1063 if (bases == NULL)
1064 return NULL;
1065 nbases = 1;
1066 }
1067 else
1068 Py_INCREF(bases);
1069
1070 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1071
1072 /* Calculate best base, and check that all bases are type objects */
1073 base = best_base(bases);
1074 if (base == NULL)
1075 return NULL;
1076 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1077 PyErr_Format(PyExc_TypeError,
1078 "type '%.100s' is not an acceptable base type",
1079 base->tp_name);
1080 return NULL;
1081 }
1082
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 /* Check for a __slots__ sequence variable in dict, and count it */
1084 slots = PyDict_GetItemString(dict, "__slots__");
1085 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001086 add_dict = 0;
1087 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088 if (slots != NULL) {
1089 /* Make it into a tuple */
1090 if (PyString_Check(slots))
1091 slots = Py_BuildValue("(O)", slots);
1092 else
1093 slots = PySequence_Tuple(slots);
1094 if (slots == NULL)
1095 return NULL;
1096 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001097 if (nslots > 0 && base->tp_itemsize != 0) {
1098 PyErr_Format(PyExc_TypeError,
1099 "nonempty __slots__ "
1100 "not supported for subtype of '%s'",
1101 base->tp_name);
1102 return NULL;
1103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001104 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001105 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001106 Py_DECREF(slots);
1107 return NULL;
1108 }
1109 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001110
1111 newslots = PyTuple_New(nslots);
1112 if (newslots == NULL)
1113 return NULL;
1114 for (i = 0; i < nslots; i++) {
1115 tmp = PyTuple_GET_ITEM(slots, i);
1116 if (_Py_Mangle(PyString_AS_STRING(name),
1117 PyString_AS_STRING(tmp),
1118 buffer, sizeof(buffer)))
1119 {
1120 tmp = PyString_FromString(buffer);
1121 } else {
1122 Py_INCREF(tmp);
1123 }
1124 PyTuple_SET_ITEM(newslots, i, tmp);
1125 }
1126 Py_DECREF(slots);
1127 slots = newslots;
1128
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001130 if (slots != NULL) {
1131 /* See if *this* class defines __getstate__ */
1132 PyObject *getstate = PyDict_GetItemString(dict,
1133 "__getstate__");
1134 if (getstate == NULL) {
1135 /* If not, provide a bozo that raises TypeError */
1136 if (bozo_obj == NULL) {
1137 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1138 if (bozo_obj == NULL) {
1139 /* XXX decref various things */
1140 return NULL;
1141 }
1142 }
1143 if (PyDict_SetItemString(dict,
1144 "__getstate__",
1145 bozo_obj) < 0) {
1146 /* XXX decref various things */
1147 return NULL;
1148 }
1149 }
1150 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 if (slots == NULL && base->tp_dictoffset == 0 &&
1152 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001153 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001154 add_dict++;
1155 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001156 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1157 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001158 nslots++;
1159 add_weak++;
1160 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161
1162 /* XXX From here until type is safely allocated,
1163 "return NULL" may leak slots! */
1164
1165 /* Allocate the type object */
1166 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1167 if (type == NULL)
1168 return NULL;
1169
1170 /* Keep name and slots alive in the extended type object */
1171 et = (etype *)type;
1172 Py_INCREF(name);
1173 et->name = name;
1174 et->slots = slots;
1175
Guido van Rossumdc91b992001-08-08 22:26:22 +00001176 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1178 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001179 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1180 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001181
1182 /* It's a new-style number unless it specifically inherits any
1183 old-style numeric behavior */
1184 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1185 (base->tp_as_number == NULL))
1186 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1187
1188 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 type->tp_as_number = &et->as_number;
1190 type->tp_as_sequence = &et->as_sequence;
1191 type->tp_as_mapping = &et->as_mapping;
1192 type->tp_as_buffer = &et->as_buffer;
1193 type->tp_name = PyString_AS_STRING(name);
1194
1195 /* Set tp_base and tp_bases */
1196 type->tp_bases = bases;
1197 Py_INCREF(base);
1198 type->tp_base = base;
1199
Guido van Rossum687ae002001-10-15 22:03:32 +00001200 /* Initialize tp_dict from passed-in dict */
1201 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 if (dict == NULL) {
1203 Py_DECREF(type);
1204 return NULL;
1205 }
1206
Guido van Rossumc3542212001-08-16 09:18:56 +00001207 /* Set __module__ in the dict */
1208 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1209 tmp = PyEval_GetGlobals();
1210 if (tmp != NULL) {
1211 tmp = PyDict_GetItemString(tmp, "__name__");
1212 if (tmp != NULL) {
1213 if (PyDict_SetItemString(dict, "__module__",
1214 tmp) < 0)
1215 return NULL;
1216 }
1217 }
1218 }
1219
Tim Peters2f93e282001-10-04 05:27:00 +00001220 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001221 and is a string. The __doc__ accessor will first look for tp_doc;
1222 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001223 */
1224 {
1225 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1226 if (doc != NULL && PyString_Check(doc)) {
1227 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001228 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001229 if (type->tp_doc == NULL) {
1230 Py_DECREF(type);
1231 return NULL;
1232 }
1233 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1234 }
1235 }
1236
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 /* Special-case __new__: if it's a plain function,
1238 make it a static function */
1239 tmp = PyDict_GetItemString(dict, "__new__");
1240 if (tmp != NULL && PyFunction_Check(tmp)) {
1241 tmp = PyStaticMethod_New(tmp);
1242 if (tmp == NULL) {
1243 Py_DECREF(type);
1244 return NULL;
1245 }
1246 PyDict_SetItemString(dict, "__new__", tmp);
1247 Py_DECREF(tmp);
1248 }
1249
1250 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1251 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001252 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 if (slots != NULL) {
1254 for (i = 0; i < nslots; i++, mp++) {
1255 mp->name = PyString_AS_STRING(
1256 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001257 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001259 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001260 strcmp(mp->name, "__weakref__") == 0) {
1261 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001262 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001263 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001264 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 slotoffset += sizeof(PyObject *);
1266 }
1267 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001268 else {
1269 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001270 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001271 type->tp_dictoffset =
1272 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001273 else
1274 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001275 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001276 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001277 }
1278 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001279 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001280 type->tp_weaklistoffset = slotoffset;
1281 mp->name = "__weakref__";
1282 mp->type = T_OBJECT;
1283 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001284 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001285 mp++;
1286 slotoffset += sizeof(PyObject *);
1287 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288 }
1289 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001290 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001291 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292
1293 /* Special case some slots */
1294 if (type->tp_dictoffset != 0 || nslots > 0) {
1295 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1296 type->tp_getattro = PyObject_GenericGetAttr;
1297 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1298 type->tp_setattro = PyObject_GenericSetAttr;
1299 }
1300 type->tp_dealloc = subtype_dealloc;
1301
Guido van Rossum9475a232001-10-05 20:51:39 +00001302 /* Enable GC unless there are really no instance variables possible */
1303 if (!(type->tp_basicsize == sizeof(PyObject) &&
1304 type->tp_itemsize == 0))
1305 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1306
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307 /* Always override allocation strategy to use regular heap */
1308 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001309 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001310 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001311 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001312 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001313 }
1314 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001315 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316
1317 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001318 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319 Py_DECREF(type);
1320 return NULL;
1321 }
1322
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001323 /* Put the proper slots in place */
1324 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001325
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326 return (PyObject *)type;
1327}
1328
1329/* Internal API to look for a name through the MRO.
1330 This returns a borrowed reference, and doesn't set an exception! */
1331PyObject *
1332_PyType_Lookup(PyTypeObject *type, PyObject *name)
1333{
1334 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001335 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001336
Guido van Rossum687ae002001-10-15 22:03:32 +00001337 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001339
1340 /* If mro is NULL, the type is either not yet initialized
1341 by PyType_Ready(), or already cleared by type_clear().
1342 Either way the safest thing to do is to return NULL. */
1343 if (mro == NULL)
1344 return NULL;
1345
Tim Peters6d6c1a32001-08-02 04:15:00 +00001346 assert(PyTuple_Check(mro));
1347 n = PyTuple_GET_SIZE(mro);
1348 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001349 base = PyTuple_GET_ITEM(mro, i);
1350 if (PyClass_Check(base))
1351 dict = ((PyClassObject *)base)->cl_dict;
1352 else {
1353 assert(PyType_Check(base));
1354 dict = ((PyTypeObject *)base)->tp_dict;
1355 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 assert(dict && PyDict_Check(dict));
1357 res = PyDict_GetItem(dict, name);
1358 if (res != NULL)
1359 return res;
1360 }
1361 return NULL;
1362}
1363
1364/* This is similar to PyObject_GenericGetAttr(),
1365 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1366static PyObject *
1367type_getattro(PyTypeObject *type, PyObject *name)
1368{
1369 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001370 PyObject *meta_attribute, *attribute;
1371 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372
1373 /* Initialize this type (we'll assume the metatype is initialized) */
1374 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001375 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376 return NULL;
1377 }
1378
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001379 /* No readable descriptor found yet */
1380 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001381
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001382 /* Look for the attribute in the metatype */
1383 meta_attribute = _PyType_Lookup(metatype, name);
1384
1385 if (meta_attribute != NULL) {
1386 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001387
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001388 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1389 /* Data descriptors implement tp_descr_set to intercept
1390 * writes. Assume the attribute is not overridden in
1391 * type's tp_dict (and bases): call the descriptor now.
1392 */
1393 return meta_get(meta_attribute, (PyObject *)type,
1394 (PyObject *)metatype);
1395 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001396 }
1397
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001398 /* No data descriptor found on metatype. Look in tp_dict of this
1399 * type and its bases */
1400 attribute = _PyType_Lookup(type, name);
1401 if (attribute != NULL) {
1402 /* Implement descriptor functionality, if any */
1403 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1404 if (local_get != NULL) {
1405 /* NULL 2nd argument indicates the descriptor was
1406 * found on the target object itself (or a base) */
1407 return local_get(attribute, (PyObject *)NULL,
1408 (PyObject *)type);
1409 }
Tim Peters34592512002-07-11 06:23:50 +00001410
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001411 Py_INCREF(attribute);
1412 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001413 }
1414
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001415 /* No attribute found in local __dict__ (or bases): use the
1416 * descriptor from the metatype, if any */
1417 if (meta_get != NULL)
1418 return meta_get(meta_attribute, (PyObject *)type,
1419 (PyObject *)metatype);
1420
1421 /* If an ordinary attribute was found on the metatype, return it now */
1422 if (meta_attribute != NULL) {
1423 Py_INCREF(meta_attribute);
1424 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 }
1426
1427 /* Give up */
1428 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001429 "type object '%.50s' has no attribute '%.400s'",
1430 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431 return NULL;
1432}
1433
1434static int
1435type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1436{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001437 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1438 PyErr_Format(
1439 PyExc_TypeError,
1440 "can't set attributes of built-in/extension type '%s'",
1441 type->tp_name);
1442 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001443 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001444 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1445 return -1;
1446 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447}
1448
1449static void
1450type_dealloc(PyTypeObject *type)
1451{
1452 etype *et;
1453
1454 /* Assert this is a heap-allocated type object */
1455 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001456 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001457 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 et = (etype *)type;
1459 Py_XDECREF(type->tp_base);
1460 Py_XDECREF(type->tp_dict);
1461 Py_XDECREF(type->tp_bases);
1462 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001463 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001464 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465 Py_XDECREF(et->name);
1466 Py_XDECREF(et->slots);
1467 type->ob_type->tp_free((PyObject *)type);
1468}
1469
Guido van Rossum1c450732001-10-08 15:18:27 +00001470static PyObject *
1471type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1472{
1473 PyObject *list, *raw, *ref;
1474 int i, n;
1475
1476 list = PyList_New(0);
1477 if (list == NULL)
1478 return NULL;
1479 raw = type->tp_subclasses;
1480 if (raw == NULL)
1481 return list;
1482 assert(PyList_Check(raw));
1483 n = PyList_GET_SIZE(raw);
1484 for (i = 0; i < n; i++) {
1485 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001486 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001487 ref = PyWeakref_GET_OBJECT(ref);
1488 if (ref != Py_None) {
1489 if (PyList_Append(list, ref) < 0) {
1490 Py_DECREF(list);
1491 return NULL;
1492 }
1493 }
1494 }
1495 return list;
1496}
1497
Tim Peters6d6c1a32001-08-02 04:15:00 +00001498static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001499 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001501 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1502 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001503 {0}
1504};
1505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001506PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001508"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509
Guido van Rossum048eb752001-10-02 21:24:57 +00001510static int
1511type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1512{
Guido van Rossum048eb752001-10-02 21:24:57 +00001513 int err;
1514
Guido van Rossuma3862092002-06-10 15:24:42 +00001515 /* Because of type_is_gc(), the collector only calls this
1516 for heaptypes. */
1517 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001518
1519#define VISIT(SLOT) \
1520 if (SLOT) { \
1521 err = visit((PyObject *)(SLOT), arg); \
1522 if (err) \
1523 return err; \
1524 }
1525
1526 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001527 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001528 VISIT(type->tp_mro);
1529 VISIT(type->tp_bases);
1530 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001531
1532 /* There's no need to visit type->tp_subclasses or
1533 ((etype *)type)->slots, because they can't be involved
1534 in cycles; tp_subclasses is a list of weak references,
1535 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001536
1537#undef VISIT
1538
1539 return 0;
1540}
1541
1542static int
1543type_clear(PyTypeObject *type)
1544{
Guido van Rossum048eb752001-10-02 21:24:57 +00001545 PyObject *tmp;
1546
Guido van Rossuma3862092002-06-10 15:24:42 +00001547 /* Because of type_is_gc(), the collector only calls this
1548 for heaptypes. */
1549 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001550
1551#define CLEAR(SLOT) \
1552 if (SLOT) { \
1553 tmp = (PyObject *)(SLOT); \
1554 SLOT = NULL; \
1555 Py_DECREF(tmp); \
1556 }
1557
Guido van Rossuma3862092002-06-10 15:24:42 +00001558 /* The only field we need to clear is tp_mro, which is part of a
1559 hard cycle (its first element is the class itself) that won't
1560 be broken otherwise (it's a tuple and tuples don't have a
1561 tp_clear handler). None of the other fields need to be
1562 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001563
Guido van Rossuma3862092002-06-10 15:24:42 +00001564 tp_dict:
1565 It is a dict, so the collector will call its tp_clear.
1566
1567 tp_cache:
1568 Not used; if it were, it would be a dict.
1569
1570 tp_bases, tp_base:
1571 If these are involved in a cycle, there must be at least
1572 one other, mutable object in the cycle, e.g. a base
1573 class's dict; the cycle will be broken that way.
1574
1575 tp_subclasses:
1576 A list of weak references can't be part of a cycle; and
1577 lists have their own tp_clear.
1578
1579 slots (in etype):
1580 A tuple of strings can't be part of a cycle.
1581 */
1582
1583 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001584
Guido van Rossum048eb752001-10-02 21:24:57 +00001585#undef CLEAR
1586
1587 return 0;
1588}
1589
1590static int
1591type_is_gc(PyTypeObject *type)
1592{
1593 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1594}
1595
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001596PyTypeObject PyType_Type = {
1597 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598 0, /* ob_size */
1599 "type", /* tp_name */
1600 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001601 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602 (destructor)type_dealloc, /* tp_dealloc */
1603 0, /* tp_print */
1604 0, /* tp_getattr */
1605 0, /* tp_setattr */
1606 type_compare, /* tp_compare */
1607 (reprfunc)type_repr, /* tp_repr */
1608 0, /* tp_as_number */
1609 0, /* tp_as_sequence */
1610 0, /* tp_as_mapping */
1611 (hashfunc)_Py_HashPointer, /* tp_hash */
1612 (ternaryfunc)type_call, /* tp_call */
1613 0, /* tp_str */
1614 (getattrofunc)type_getattro, /* tp_getattro */
1615 (setattrofunc)type_setattro, /* tp_setattro */
1616 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001617 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1618 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001620 (traverseproc)type_traverse, /* tp_traverse */
1621 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001622 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001623 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001624 0, /* tp_iter */
1625 0, /* tp_iternext */
1626 type_methods, /* tp_methods */
1627 type_members, /* tp_members */
1628 type_getsets, /* tp_getset */
1629 0, /* tp_base */
1630 0, /* tp_dict */
1631 0, /* tp_descr_get */
1632 0, /* tp_descr_set */
1633 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1634 0, /* tp_init */
1635 0, /* tp_alloc */
1636 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001637 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001638 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001639};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640
1641
1642/* The base type of all types (eventually)... except itself. */
1643
1644static int
1645object_init(PyObject *self, PyObject *args, PyObject *kwds)
1646{
1647 return 0;
1648}
1649
1650static void
1651object_dealloc(PyObject *self)
1652{
1653 self->ob_type->tp_free(self);
1654}
1655
Guido van Rossum8e248182001-08-12 05:17:56 +00001656static PyObject *
1657object_repr(PyObject *self)
1658{
Guido van Rossum76e69632001-08-16 18:52:43 +00001659 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001660 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001661
Guido van Rossum76e69632001-08-16 18:52:43 +00001662 type = self->ob_type;
1663 mod = type_module(type, NULL);
1664 if (mod == NULL)
1665 PyErr_Clear();
1666 else if (!PyString_Check(mod)) {
1667 Py_DECREF(mod);
1668 mod = NULL;
1669 }
1670 name = type_name(type, NULL);
1671 if (name == NULL)
1672 return NULL;
1673 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001674 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001675 PyString_AS_STRING(mod),
1676 PyString_AS_STRING(name),
1677 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001678 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001679 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001680 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001681 Py_XDECREF(mod);
1682 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001683 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001684}
1685
Guido van Rossumb8f63662001-08-15 23:57:02 +00001686static PyObject *
1687object_str(PyObject *self)
1688{
1689 unaryfunc f;
1690
1691 f = self->ob_type->tp_repr;
1692 if (f == NULL)
1693 f = object_repr;
1694 return f(self);
1695}
1696
Guido van Rossum8e248182001-08-12 05:17:56 +00001697static long
1698object_hash(PyObject *self)
1699{
1700 return _Py_HashPointer(self);
1701}
Guido van Rossum8e248182001-08-12 05:17:56 +00001702
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001703static PyObject *
1704object_get_class(PyObject *self, void *closure)
1705{
1706 Py_INCREF(self->ob_type);
1707 return (PyObject *)(self->ob_type);
1708}
1709
1710static int
1711equiv_structs(PyTypeObject *a, PyTypeObject *b)
1712{
1713 return a == b ||
1714 (a != NULL &&
1715 b != NULL &&
1716 a->tp_basicsize == b->tp_basicsize &&
1717 a->tp_itemsize == b->tp_itemsize &&
1718 a->tp_dictoffset == b->tp_dictoffset &&
1719 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1720 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1721 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1722}
1723
1724static int
1725same_slots_added(PyTypeObject *a, PyTypeObject *b)
1726{
1727 PyTypeObject *base = a->tp_base;
1728 int size;
1729
1730 if (base != b->tp_base)
1731 return 0;
1732 if (equiv_structs(a, base) && equiv_structs(b, base))
1733 return 1;
1734 size = base->tp_basicsize;
1735 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1736 size += sizeof(PyObject *);
1737 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1738 size += sizeof(PyObject *);
1739 return size == a->tp_basicsize && size == b->tp_basicsize;
1740}
1741
1742static int
1743object_set_class(PyObject *self, PyObject *value, void *closure)
1744{
1745 PyTypeObject *old = self->ob_type;
1746 PyTypeObject *new, *newbase, *oldbase;
1747
Guido van Rossumb6b89422002-04-15 01:03:30 +00001748 if (value == NULL) {
1749 PyErr_SetString(PyExc_TypeError,
1750 "can't delete __class__ attribute");
1751 return -1;
1752 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001753 if (!PyType_Check(value)) {
1754 PyErr_Format(PyExc_TypeError,
1755 "__class__ must be set to new-style class, not '%s' object",
1756 value->ob_type->tp_name);
1757 return -1;
1758 }
1759 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001760 if (new->tp_dealloc != old->tp_dealloc ||
1761 new->tp_free != old->tp_free)
1762 {
1763 PyErr_Format(PyExc_TypeError,
1764 "__class__ assignment: "
1765 "'%s' deallocator differs from '%s'",
1766 new->tp_name,
1767 old->tp_name);
1768 return -1;
1769 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001770 newbase = new;
1771 oldbase = old;
1772 while (equiv_structs(newbase, newbase->tp_base))
1773 newbase = newbase->tp_base;
1774 while (equiv_structs(oldbase, oldbase->tp_base))
1775 oldbase = oldbase->tp_base;
1776 if (newbase != oldbase &&
1777 (newbase->tp_base != oldbase->tp_base ||
1778 !same_slots_added(newbase, oldbase))) {
1779 PyErr_Format(PyExc_TypeError,
1780 "__class__ assignment: "
1781 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001782 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001783 old->tp_name);
1784 return -1;
1785 }
1786 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1787 Py_INCREF(new);
1788 }
1789 self->ob_type = new;
1790 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1791 Py_DECREF(old);
1792 }
1793 return 0;
1794}
1795
1796static PyGetSetDef object_getsets[] = {
1797 {"__class__", object_get_class, object_set_class,
1798 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 {0}
1800};
1801
Guido van Rossum3926a632001-09-25 16:25:58 +00001802static PyObject *
1803object_reduce(PyObject *self, PyObject *args)
1804{
1805 /* Call copy_reg._reduce(self) */
1806 static PyObject *copy_reg_str;
1807 PyObject *copy_reg, *res;
1808
1809 if (!copy_reg_str) {
1810 copy_reg_str = PyString_InternFromString("copy_reg");
1811 if (copy_reg_str == NULL)
1812 return NULL;
1813 }
1814 copy_reg = PyImport_Import(copy_reg_str);
1815 if (!copy_reg)
1816 return NULL;
1817 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1818 Py_DECREF(copy_reg);
1819 return res;
1820}
1821
1822static PyMethodDef object_methods[] = {
1823 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1824 {0}
1825};
1826
Tim Peters6d6c1a32001-08-02 04:15:00 +00001827PyTypeObject PyBaseObject_Type = {
1828 PyObject_HEAD_INIT(&PyType_Type)
1829 0, /* ob_size */
1830 "object", /* tp_name */
1831 sizeof(PyObject), /* tp_basicsize */
1832 0, /* tp_itemsize */
1833 (destructor)object_dealloc, /* tp_dealloc */
1834 0, /* tp_print */
1835 0, /* tp_getattr */
1836 0, /* tp_setattr */
1837 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001838 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839 0, /* tp_as_number */
1840 0, /* tp_as_sequence */
1841 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001842 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001844 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001846 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 0, /* tp_as_buffer */
1848 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1849 "The most base type", /* tp_doc */
1850 0, /* tp_traverse */
1851 0, /* tp_clear */
1852 0, /* tp_richcompare */
1853 0, /* tp_weaklistoffset */
1854 0, /* tp_iter */
1855 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001856 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001857 0, /* tp_members */
1858 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 0, /* tp_base */
1860 0, /* tp_dict */
1861 0, /* tp_descr_get */
1862 0, /* tp_descr_set */
1863 0, /* tp_dictoffset */
1864 object_init, /* tp_init */
1865 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001866 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001867 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868};
1869
1870
1871/* Initialize the __dict__ in a type object */
1872
Fred Drake7bf97152002-03-28 05:33:33 +00001873static PyObject *
1874create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1875{
1876 PyObject *cfunc;
1877 PyObject *result;
1878
1879 cfunc = PyCFunction_New(meth, NULL);
1880 if (cfunc == NULL)
1881 return NULL;
1882 result = func(cfunc);
1883 Py_DECREF(cfunc);
1884 return result;
1885}
1886
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887static int
1888add_methods(PyTypeObject *type, PyMethodDef *meth)
1889{
Guido van Rossum687ae002001-10-15 22:03:32 +00001890 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891
1892 for (; meth->ml_name != NULL; meth++) {
1893 PyObject *descr;
1894 if (PyDict_GetItemString(dict, meth->ml_name))
1895 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001896 if (meth->ml_flags & METH_CLASS) {
1897 if (meth->ml_flags & METH_STATIC) {
1898 PyErr_SetString(PyExc_ValueError,
1899 "method cannot be both class and static");
1900 return -1;
1901 }
1902 descr = create_specialmethod(meth, PyClassMethod_New);
1903 }
1904 else if (meth->ml_flags & METH_STATIC) {
1905 descr = create_specialmethod(meth, PyStaticMethod_New);
1906 }
1907 else {
1908 descr = PyDescr_NewMethod(type, meth);
1909 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910 if (descr == NULL)
1911 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001912 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001913 return -1;
1914 Py_DECREF(descr);
1915 }
1916 return 0;
1917}
1918
1919static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001920add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001921{
Guido van Rossum687ae002001-10-15 22:03:32 +00001922 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001923
1924 for (; memb->name != NULL; memb++) {
1925 PyObject *descr;
1926 if (PyDict_GetItemString(dict, memb->name))
1927 continue;
1928 descr = PyDescr_NewMember(type, memb);
1929 if (descr == NULL)
1930 return -1;
1931 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1932 return -1;
1933 Py_DECREF(descr);
1934 }
1935 return 0;
1936}
1937
1938static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001939add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940{
Guido van Rossum687ae002001-10-15 22:03:32 +00001941 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001942
1943 for (; gsp->name != NULL; gsp++) {
1944 PyObject *descr;
1945 if (PyDict_GetItemString(dict, gsp->name))
1946 continue;
1947 descr = PyDescr_NewGetSet(type, gsp);
1948
1949 if (descr == NULL)
1950 return -1;
1951 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1952 return -1;
1953 Py_DECREF(descr);
1954 }
1955 return 0;
1956}
1957
Guido van Rossum13d52f02001-08-10 21:24:08 +00001958static void
1959inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001960{
1961 int oldsize, newsize;
1962
Guido van Rossum13d52f02001-08-10 21:24:08 +00001963 /* Special flag magic */
1964 if (!type->tp_as_buffer && base->tp_as_buffer) {
1965 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1966 type->tp_flags |=
1967 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1968 }
1969 if (!type->tp_as_sequence && base->tp_as_sequence) {
1970 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1971 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1972 }
1973 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1974 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1975 if ((!type->tp_as_number && base->tp_as_number) ||
1976 (!type->tp_as_sequence && base->tp_as_sequence)) {
1977 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1978 if (!type->tp_as_number && !type->tp_as_sequence) {
1979 type->tp_flags |= base->tp_flags &
1980 Py_TPFLAGS_HAVE_INPLACEOPS;
1981 }
1982 }
1983 /* Wow */
1984 }
1985 if (!type->tp_as_number && base->tp_as_number) {
1986 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1987 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1988 }
1989
1990 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001991 oldsize = base->tp_basicsize;
1992 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1993 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1994 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001995 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1996 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001997 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001998 if (type->tp_traverse == NULL)
1999 type->tp_traverse = base->tp_traverse;
2000 if (type->tp_clear == NULL)
2001 type->tp_clear = base->tp_clear;
2002 }
2003 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002004 /* The condition below could use some explanation.
2005 It appears that tp_new is not inherited for static types
2006 whose base class is 'object'; this seems to be a precaution
2007 so that old extension types don't suddenly become
2008 callable (object.__new__ wouldn't insure the invariants
2009 that the extension type's own factory function ensures).
2010 Heap types, of course, are under our control, so they do
2011 inherit tp_new; static extension types that specify some
2012 other built-in type as the default are considered
2013 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002014 if (base != &PyBaseObject_Type ||
2015 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2016 if (type->tp_new == NULL)
2017 type->tp_new = base->tp_new;
2018 }
2019 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002020 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002021
2022 /* Copy other non-function slots */
2023
2024#undef COPYVAL
2025#define COPYVAL(SLOT) \
2026 if (type->SLOT == 0) type->SLOT = base->SLOT
2027
2028 COPYVAL(tp_itemsize);
2029 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2030 COPYVAL(tp_weaklistoffset);
2031 }
2032 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2033 COPYVAL(tp_dictoffset);
2034 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002035}
2036
2037static void
2038inherit_slots(PyTypeObject *type, PyTypeObject *base)
2039{
2040 PyTypeObject *basebase;
2041
2042#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043#undef COPYSLOT
2044#undef COPYNUM
2045#undef COPYSEQ
2046#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002047#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002048
2049#define SLOTDEFINED(SLOT) \
2050 (base->SLOT != 0 && \
2051 (basebase == NULL || base->SLOT != basebase->SLOT))
2052
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002054 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055
2056#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2057#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2058#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002059#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002060
Guido van Rossum13d52f02001-08-10 21:24:08 +00002061 /* This won't inherit indirect slots (from tp_as_number etc.)
2062 if type doesn't provide the space. */
2063
2064 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2065 basebase = base->tp_base;
2066 if (basebase->tp_as_number == NULL)
2067 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002068 COPYNUM(nb_add);
2069 COPYNUM(nb_subtract);
2070 COPYNUM(nb_multiply);
2071 COPYNUM(nb_divide);
2072 COPYNUM(nb_remainder);
2073 COPYNUM(nb_divmod);
2074 COPYNUM(nb_power);
2075 COPYNUM(nb_negative);
2076 COPYNUM(nb_positive);
2077 COPYNUM(nb_absolute);
2078 COPYNUM(nb_nonzero);
2079 COPYNUM(nb_invert);
2080 COPYNUM(nb_lshift);
2081 COPYNUM(nb_rshift);
2082 COPYNUM(nb_and);
2083 COPYNUM(nb_xor);
2084 COPYNUM(nb_or);
2085 COPYNUM(nb_coerce);
2086 COPYNUM(nb_int);
2087 COPYNUM(nb_long);
2088 COPYNUM(nb_float);
2089 COPYNUM(nb_oct);
2090 COPYNUM(nb_hex);
2091 COPYNUM(nb_inplace_add);
2092 COPYNUM(nb_inplace_subtract);
2093 COPYNUM(nb_inplace_multiply);
2094 COPYNUM(nb_inplace_divide);
2095 COPYNUM(nb_inplace_remainder);
2096 COPYNUM(nb_inplace_power);
2097 COPYNUM(nb_inplace_lshift);
2098 COPYNUM(nb_inplace_rshift);
2099 COPYNUM(nb_inplace_and);
2100 COPYNUM(nb_inplace_xor);
2101 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002102 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2103 COPYNUM(nb_true_divide);
2104 COPYNUM(nb_floor_divide);
2105 COPYNUM(nb_inplace_true_divide);
2106 COPYNUM(nb_inplace_floor_divide);
2107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108 }
2109
Guido van Rossum13d52f02001-08-10 21:24:08 +00002110 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2111 basebase = base->tp_base;
2112 if (basebase->tp_as_sequence == NULL)
2113 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114 COPYSEQ(sq_length);
2115 COPYSEQ(sq_concat);
2116 COPYSEQ(sq_repeat);
2117 COPYSEQ(sq_item);
2118 COPYSEQ(sq_slice);
2119 COPYSEQ(sq_ass_item);
2120 COPYSEQ(sq_ass_slice);
2121 COPYSEQ(sq_contains);
2122 COPYSEQ(sq_inplace_concat);
2123 COPYSEQ(sq_inplace_repeat);
2124 }
2125
Guido van Rossum13d52f02001-08-10 21:24:08 +00002126 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2127 basebase = base->tp_base;
2128 if (basebase->tp_as_mapping == NULL)
2129 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130 COPYMAP(mp_length);
2131 COPYMAP(mp_subscript);
2132 COPYMAP(mp_ass_subscript);
2133 }
2134
Tim Petersfc57ccb2001-10-12 02:38:24 +00002135 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2136 basebase = base->tp_base;
2137 if (basebase->tp_as_buffer == NULL)
2138 basebase = NULL;
2139 COPYBUF(bf_getreadbuffer);
2140 COPYBUF(bf_getwritebuffer);
2141 COPYBUF(bf_getsegcount);
2142 COPYBUF(bf_getcharbuffer);
2143 }
2144
Guido van Rossum13d52f02001-08-10 21:24:08 +00002145 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146
Tim Peters6d6c1a32001-08-02 04:15:00 +00002147 COPYSLOT(tp_dealloc);
2148 COPYSLOT(tp_print);
2149 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2150 type->tp_getattr = base->tp_getattr;
2151 type->tp_getattro = base->tp_getattro;
2152 }
2153 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2154 type->tp_setattr = base->tp_setattr;
2155 type->tp_setattro = base->tp_setattro;
2156 }
2157 /* tp_compare see tp_richcompare */
2158 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002159 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002160 COPYSLOT(tp_call);
2161 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002163 if (type->tp_compare == NULL &&
2164 type->tp_richcompare == NULL &&
2165 type->tp_hash == NULL)
2166 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002167 type->tp_compare = base->tp_compare;
2168 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002169 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002170 }
2171 }
2172 else {
2173 COPYSLOT(tp_compare);
2174 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2176 COPYSLOT(tp_iter);
2177 COPYSLOT(tp_iternext);
2178 }
2179 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2180 COPYSLOT(tp_descr_get);
2181 COPYSLOT(tp_descr_set);
2182 COPYSLOT(tp_dictoffset);
2183 COPYSLOT(tp_init);
2184 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002186 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188}
2189
Jeremy Hylton938ace62002-07-17 16:30:39 +00002190static int add_operators(PyTypeObject *);
2191static int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002192
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002194PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002196 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197 PyTypeObject *base;
2198 int i, n;
2199
Guido van Rossumcab05802002-06-10 15:29:03 +00002200 if (type->tp_flags & Py_TPFLAGS_READY) {
2201 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002202 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002203 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002204 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002205
2206 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207
2208 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2209 base = type->tp_base;
2210 if (base == NULL && type != &PyBaseObject_Type)
2211 base = type->tp_base = &PyBaseObject_Type;
2212
Guido van Rossum0986d822002-04-08 01:38:42 +00002213 /* Initialize ob_type if NULL. This means extensions that want to be
2214 compilable separately on Windows can call PyType_Ready() instead of
2215 initializing the ob_type field of their type objects. */
2216 if (type->ob_type == NULL)
2217 type->ob_type = base->ob_type;
2218
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219 /* Initialize tp_bases */
2220 bases = type->tp_bases;
2221 if (bases == NULL) {
2222 if (base == NULL)
2223 bases = PyTuple_New(0);
2224 else
2225 bases = Py_BuildValue("(O)", base);
2226 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002227 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228 type->tp_bases = bases;
2229 }
2230
2231 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002232 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002233 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002234 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235 }
2236
Guido van Rossum687ae002001-10-15 22:03:32 +00002237 /* Initialize tp_dict */
2238 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239 if (dict == NULL) {
2240 dict = PyDict_New();
2241 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002242 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002243 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244 }
2245
Guido van Rossum687ae002001-10-15 22:03:32 +00002246 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002248 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002249 if (type->tp_methods != NULL) {
2250 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002251 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002252 }
2253 if (type->tp_members != NULL) {
2254 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002255 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002256 }
2257 if (type->tp_getset != NULL) {
2258 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002259 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002260 }
2261
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262 /* Calculate method resolution order */
2263 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002264 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002265 }
2266
Guido van Rossum13d52f02001-08-10 21:24:08 +00002267 /* Inherit special flags from dominant base */
2268 if (type->tp_base != NULL)
2269 inherit_special(type, type->tp_base);
2270
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002272 bases = type->tp_mro;
2273 assert(bases != NULL);
2274 assert(PyTuple_Check(bases));
2275 n = PyTuple_GET_SIZE(bases);
2276 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002277 PyObject *b = PyTuple_GET_ITEM(bases, i);
2278 if (PyType_Check(b))
2279 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002280 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002282 /* if the type dictionary doesn't contain a __doc__, set it from
2283 the tp_doc slot.
2284 */
2285 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2286 if (type->tp_doc != NULL) {
2287 PyObject *doc = PyString_FromString(type->tp_doc);
2288 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2289 Py_DECREF(doc);
2290 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002291 PyDict_SetItemString(type->tp_dict,
2292 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002293 }
2294 }
2295
Guido van Rossum13d52f02001-08-10 21:24:08 +00002296 /* Some more special stuff */
2297 base = type->tp_base;
2298 if (base != NULL) {
2299 if (type->tp_as_number == NULL)
2300 type->tp_as_number = base->tp_as_number;
2301 if (type->tp_as_sequence == NULL)
2302 type->tp_as_sequence = base->tp_as_sequence;
2303 if (type->tp_as_mapping == NULL)
2304 type->tp_as_mapping = base->tp_as_mapping;
2305 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002306
Guido van Rossum1c450732001-10-08 15:18:27 +00002307 /* Link into each base class's list of subclasses */
2308 bases = type->tp_bases;
2309 n = PyTuple_GET_SIZE(bases);
2310 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002311 PyObject *b = PyTuple_GET_ITEM(bases, i);
2312 if (PyType_Check(b) &&
2313 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002314 goto error;
2315 }
2316
Guido van Rossum13d52f02001-08-10 21:24:08 +00002317 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002318 assert(type->tp_dict != NULL);
2319 type->tp_flags =
2320 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002321 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002322
2323 error:
2324 type->tp_flags &= ~Py_TPFLAGS_READYING;
2325 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326}
2327
Guido van Rossum1c450732001-10-08 15:18:27 +00002328static int
2329add_subclass(PyTypeObject *base, PyTypeObject *type)
2330{
2331 int i;
2332 PyObject *list, *ref, *new;
2333
2334 list = base->tp_subclasses;
2335 if (list == NULL) {
2336 base->tp_subclasses = list = PyList_New(0);
2337 if (list == NULL)
2338 return -1;
2339 }
2340 assert(PyList_Check(list));
2341 new = PyWeakref_NewRef((PyObject *)type, NULL);
2342 i = PyList_GET_SIZE(list);
2343 while (--i >= 0) {
2344 ref = PyList_GET_ITEM(list, i);
2345 assert(PyWeakref_CheckRef(ref));
2346 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2347 return PyList_SetItem(list, i, new);
2348 }
2349 i = PyList_Append(list, new);
2350 Py_DECREF(new);
2351 return i;
2352}
2353
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354
2355/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2356
2357/* There's a wrapper *function* for each distinct function typedef used
2358 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2359 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2360 Most tables have only one entry; the tables for binary operators have two
2361 entries, one regular and one with reversed arguments. */
2362
2363static PyObject *
2364wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2365{
2366 inquiry func = (inquiry)wrapped;
2367 int res;
2368
2369 if (!PyArg_ParseTuple(args, ""))
2370 return NULL;
2371 res = (*func)(self);
2372 if (res == -1 && PyErr_Occurred())
2373 return NULL;
2374 return PyInt_FromLong((long)res);
2375}
2376
Tim Peters6d6c1a32001-08-02 04:15:00 +00002377static PyObject *
2378wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2379{
2380 binaryfunc func = (binaryfunc)wrapped;
2381 PyObject *other;
2382
2383 if (!PyArg_ParseTuple(args, "O", &other))
2384 return NULL;
2385 return (*func)(self, other);
2386}
2387
2388static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002389wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2390{
2391 binaryfunc func = (binaryfunc)wrapped;
2392 PyObject *other;
2393
2394 if (!PyArg_ParseTuple(args, "O", &other))
2395 return NULL;
2396 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002397 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002398 Py_INCREF(Py_NotImplemented);
2399 return Py_NotImplemented;
2400 }
2401 return (*func)(self, other);
2402}
2403
2404static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002405wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2406{
2407 binaryfunc func = (binaryfunc)wrapped;
2408 PyObject *other;
2409
2410 if (!PyArg_ParseTuple(args, "O", &other))
2411 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002412 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002413 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002414 Py_INCREF(Py_NotImplemented);
2415 return Py_NotImplemented;
2416 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417 return (*func)(other, self);
2418}
2419
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002420static PyObject *
2421wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2422{
2423 coercion func = (coercion)wrapped;
2424 PyObject *other, *res;
2425 int ok;
2426
2427 if (!PyArg_ParseTuple(args, "O", &other))
2428 return NULL;
2429 ok = func(&self, &other);
2430 if (ok < 0)
2431 return NULL;
2432 if (ok > 0) {
2433 Py_INCREF(Py_NotImplemented);
2434 return Py_NotImplemented;
2435 }
2436 res = PyTuple_New(2);
2437 if (res == NULL) {
2438 Py_DECREF(self);
2439 Py_DECREF(other);
2440 return NULL;
2441 }
2442 PyTuple_SET_ITEM(res, 0, self);
2443 PyTuple_SET_ITEM(res, 1, other);
2444 return res;
2445}
2446
Tim Peters6d6c1a32001-08-02 04:15:00 +00002447static PyObject *
2448wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2449{
2450 ternaryfunc func = (ternaryfunc)wrapped;
2451 PyObject *other;
2452 PyObject *third = Py_None;
2453
2454 /* Note: This wrapper only works for __pow__() */
2455
2456 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2457 return NULL;
2458 return (*func)(self, other, third);
2459}
2460
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002461static PyObject *
2462wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2463{
2464 ternaryfunc func = (ternaryfunc)wrapped;
2465 PyObject *other;
2466 PyObject *third = Py_None;
2467
2468 /* Note: This wrapper only works for __pow__() */
2469
2470 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2471 return NULL;
2472 return (*func)(other, self, third);
2473}
2474
Tim Peters6d6c1a32001-08-02 04:15:00 +00002475static PyObject *
2476wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2477{
2478 unaryfunc func = (unaryfunc)wrapped;
2479
2480 if (!PyArg_ParseTuple(args, ""))
2481 return NULL;
2482 return (*func)(self);
2483}
2484
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485static PyObject *
2486wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2487{
2488 intargfunc func = (intargfunc)wrapped;
2489 int i;
2490
2491 if (!PyArg_ParseTuple(args, "i", &i))
2492 return NULL;
2493 return (*func)(self, i);
2494}
2495
Guido van Rossum5d815f32001-08-17 21:57:47 +00002496static int
2497getindex(PyObject *self, PyObject *arg)
2498{
2499 int i;
2500
2501 i = PyInt_AsLong(arg);
2502 if (i == -1 && PyErr_Occurred())
2503 return -1;
2504 if (i < 0) {
2505 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2506 if (sq && sq->sq_length) {
2507 int n = (*sq->sq_length)(self);
2508 if (n < 0)
2509 return -1;
2510 i += n;
2511 }
2512 }
2513 return i;
2514}
2515
2516static PyObject *
2517wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2518{
2519 intargfunc func = (intargfunc)wrapped;
2520 PyObject *arg;
2521 int i;
2522
Guido van Rossumf4593e02001-10-03 12:09:30 +00002523 if (PyTuple_GET_SIZE(args) == 1) {
2524 arg = PyTuple_GET_ITEM(args, 0);
2525 i = getindex(self, arg);
2526 if (i == -1 && PyErr_Occurred())
2527 return NULL;
2528 return (*func)(self, i);
2529 }
2530 PyArg_ParseTuple(args, "O", &arg);
2531 assert(PyErr_Occurred());
2532 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002533}
2534
Tim Peters6d6c1a32001-08-02 04:15:00 +00002535static PyObject *
2536wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2537{
2538 intintargfunc func = (intintargfunc)wrapped;
2539 int i, j;
2540
2541 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2542 return NULL;
2543 return (*func)(self, i, j);
2544}
2545
Tim Peters6d6c1a32001-08-02 04:15:00 +00002546static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002547wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002548{
2549 intobjargproc func = (intobjargproc)wrapped;
2550 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002551 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002552
Guido van Rossum5d815f32001-08-17 21:57:47 +00002553 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2554 return NULL;
2555 i = getindex(self, arg);
2556 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002557 return NULL;
2558 res = (*func)(self, i, value);
2559 if (res == -1 && PyErr_Occurred())
2560 return NULL;
2561 Py_INCREF(Py_None);
2562 return Py_None;
2563}
2564
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002565static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002566wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002567{
2568 intobjargproc func = (intobjargproc)wrapped;
2569 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002570 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002571
Guido van Rossum5d815f32001-08-17 21:57:47 +00002572 if (!PyArg_ParseTuple(args, "O", &arg))
2573 return NULL;
2574 i = getindex(self, arg);
2575 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002576 return NULL;
2577 res = (*func)(self, i, NULL);
2578 if (res == -1 && PyErr_Occurred())
2579 return NULL;
2580 Py_INCREF(Py_None);
2581 return Py_None;
2582}
2583
Tim Peters6d6c1a32001-08-02 04:15:00 +00002584static PyObject *
2585wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2586{
2587 intintobjargproc func = (intintobjargproc)wrapped;
2588 int i, j, res;
2589 PyObject *value;
2590
2591 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2592 return NULL;
2593 res = (*func)(self, i, j, value);
2594 if (res == -1 && PyErr_Occurred())
2595 return NULL;
2596 Py_INCREF(Py_None);
2597 return Py_None;
2598}
2599
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002600static PyObject *
2601wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2602{
2603 intintobjargproc func = (intintobjargproc)wrapped;
2604 int i, j, res;
2605
2606 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2607 return NULL;
2608 res = (*func)(self, i, j, NULL);
2609 if (res == -1 && PyErr_Occurred())
2610 return NULL;
2611 Py_INCREF(Py_None);
2612 return Py_None;
2613}
2614
Tim Peters6d6c1a32001-08-02 04:15:00 +00002615/* XXX objobjproc is a misnomer; should be objargpred */
2616static PyObject *
2617wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2618{
2619 objobjproc func = (objobjproc)wrapped;
2620 int res;
2621 PyObject *value;
2622
2623 if (!PyArg_ParseTuple(args, "O", &value))
2624 return NULL;
2625 res = (*func)(self, value);
2626 if (res == -1 && PyErr_Occurred())
2627 return NULL;
2628 return PyInt_FromLong((long)res);
2629}
2630
Tim Peters6d6c1a32001-08-02 04:15:00 +00002631static PyObject *
2632wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2633{
2634 objobjargproc func = (objobjargproc)wrapped;
2635 int res;
2636 PyObject *key, *value;
2637
2638 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2639 return NULL;
2640 res = (*func)(self, key, value);
2641 if (res == -1 && PyErr_Occurred())
2642 return NULL;
2643 Py_INCREF(Py_None);
2644 return Py_None;
2645}
2646
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002647static PyObject *
2648wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2649{
2650 objobjargproc func = (objobjargproc)wrapped;
2651 int res;
2652 PyObject *key;
2653
2654 if (!PyArg_ParseTuple(args, "O", &key))
2655 return NULL;
2656 res = (*func)(self, key, NULL);
2657 if (res == -1 && PyErr_Occurred())
2658 return NULL;
2659 Py_INCREF(Py_None);
2660 return Py_None;
2661}
2662
Tim Peters6d6c1a32001-08-02 04:15:00 +00002663static PyObject *
2664wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2665{
2666 cmpfunc func = (cmpfunc)wrapped;
2667 int res;
2668 PyObject *other;
2669
2670 if (!PyArg_ParseTuple(args, "O", &other))
2671 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002672 if (other->ob_type->tp_compare != func &&
2673 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002674 PyErr_Format(
2675 PyExc_TypeError,
2676 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2677 self->ob_type->tp_name,
2678 self->ob_type->tp_name,
2679 other->ob_type->tp_name);
2680 return NULL;
2681 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682 res = (*func)(self, other);
2683 if (PyErr_Occurred())
2684 return NULL;
2685 return PyInt_FromLong((long)res);
2686}
2687
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688static PyObject *
2689wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2690{
2691 setattrofunc func = (setattrofunc)wrapped;
2692 int res;
2693 PyObject *name, *value;
2694
2695 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2696 return NULL;
2697 res = (*func)(self, name, value);
2698 if (res < 0)
2699 return NULL;
2700 Py_INCREF(Py_None);
2701 return Py_None;
2702}
2703
2704static PyObject *
2705wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2706{
2707 setattrofunc func = (setattrofunc)wrapped;
2708 int res;
2709 PyObject *name;
2710
2711 if (!PyArg_ParseTuple(args, "O", &name))
2712 return NULL;
2713 res = (*func)(self, name, NULL);
2714 if (res < 0)
2715 return NULL;
2716 Py_INCREF(Py_None);
2717 return Py_None;
2718}
2719
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720static PyObject *
2721wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2722{
2723 hashfunc func = (hashfunc)wrapped;
2724 long res;
2725
2726 if (!PyArg_ParseTuple(args, ""))
2727 return NULL;
2728 res = (*func)(self);
2729 if (res == -1 && PyErr_Occurred())
2730 return NULL;
2731 return PyInt_FromLong(res);
2732}
2733
Tim Peters6d6c1a32001-08-02 04:15:00 +00002734static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002735wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736{
2737 ternaryfunc func = (ternaryfunc)wrapped;
2738
Guido van Rossumc8e56452001-10-22 00:43:43 +00002739 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002740}
2741
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742static PyObject *
2743wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2744{
2745 richcmpfunc func = (richcmpfunc)wrapped;
2746 PyObject *other;
2747
2748 if (!PyArg_ParseTuple(args, "O", &other))
2749 return NULL;
2750 return (*func)(self, other, op);
2751}
2752
2753#undef RICHCMP_WRAPPER
2754#define RICHCMP_WRAPPER(NAME, OP) \
2755static PyObject * \
2756richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2757{ \
2758 return wrap_richcmpfunc(self, args, wrapped, OP); \
2759}
2760
Jack Jansen8e938b42001-08-08 15:29:49 +00002761RICHCMP_WRAPPER(lt, Py_LT)
2762RICHCMP_WRAPPER(le, Py_LE)
2763RICHCMP_WRAPPER(eq, Py_EQ)
2764RICHCMP_WRAPPER(ne, Py_NE)
2765RICHCMP_WRAPPER(gt, Py_GT)
2766RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768static PyObject *
2769wrap_next(PyObject *self, PyObject *args, void *wrapped)
2770{
2771 unaryfunc func = (unaryfunc)wrapped;
2772 PyObject *res;
2773
2774 if (!PyArg_ParseTuple(args, ""))
2775 return NULL;
2776 res = (*func)(self);
2777 if (res == NULL && !PyErr_Occurred())
2778 PyErr_SetNone(PyExc_StopIteration);
2779 return res;
2780}
2781
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782static PyObject *
2783wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2784{
2785 descrgetfunc func = (descrgetfunc)wrapped;
2786 PyObject *obj;
2787 PyObject *type = NULL;
2788
2789 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2790 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 return (*func)(self, obj, type);
2792}
2793
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002795wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796{
2797 descrsetfunc func = (descrsetfunc)wrapped;
2798 PyObject *obj, *value;
2799 int ret;
2800
2801 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2802 return NULL;
2803 ret = (*func)(self, obj, value);
2804 if (ret < 0)
2805 return NULL;
2806 Py_INCREF(Py_None);
2807 return Py_None;
2808}
2809
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002811wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812{
2813 initproc func = (initproc)wrapped;
2814
Guido van Rossumc8e56452001-10-22 00:43:43 +00002815 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816 return NULL;
2817 Py_INCREF(Py_None);
2818 return Py_None;
2819}
2820
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002822tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823{
Barry Warsaw60f01882001-08-22 19:24:42 +00002824 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002825 PyObject *arg0, *res;
2826
2827 if (self == NULL || !PyType_Check(self))
2828 Py_FatalError("__new__() called with non-type 'self'");
2829 type = (PyTypeObject *)self;
2830 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002831 PyErr_Format(PyExc_TypeError,
2832 "%s.__new__(): not enough arguments",
2833 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002834 return NULL;
2835 }
2836 arg0 = PyTuple_GET_ITEM(args, 0);
2837 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002838 PyErr_Format(PyExc_TypeError,
2839 "%s.__new__(X): X is not a type object (%s)",
2840 type->tp_name,
2841 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002842 return NULL;
2843 }
2844 subtype = (PyTypeObject *)arg0;
2845 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002846 PyErr_Format(PyExc_TypeError,
2847 "%s.__new__(%s): %s is not a subtype of %s",
2848 type->tp_name,
2849 subtype->tp_name,
2850 subtype->tp_name,
2851 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002852 return NULL;
2853 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002854
2855 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002856 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002857 most derived base that's not a heap type is this type. */
2858 staticbase = subtype;
2859 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2860 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002861 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002862 PyErr_Format(PyExc_TypeError,
2863 "%s.__new__(%s) is not safe, use %s.__new__()",
2864 type->tp_name,
2865 subtype->tp_name,
2866 staticbase == NULL ? "?" : staticbase->tp_name);
2867 return NULL;
2868 }
2869
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002870 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2871 if (args == NULL)
2872 return NULL;
2873 res = type->tp_new(subtype, args, kwds);
2874 Py_DECREF(args);
2875 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002876}
2877
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002878static struct PyMethodDef tp_new_methoddef[] = {
2879 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2880 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002881 {0}
2882};
2883
2884static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002885add_tp_new_wrapper(PyTypeObject *type)
2886{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002887 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002888
Guido van Rossum687ae002001-10-15 22:03:32 +00002889 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002890 return 0;
2891 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002892 if (func == NULL)
2893 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002894 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002895}
2896
Guido van Rossumf040ede2001-08-07 16:40:56 +00002897/* Slot wrappers that call the corresponding __foo__ slot. See comments
2898 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899
Guido van Rossumdc91b992001-08-08 22:26:22 +00002900#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002902FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002904 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002905 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002906}
2907
Guido van Rossumdc91b992001-08-08 22:26:22 +00002908#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002910FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002912 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002913 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002914}
2915
Guido van Rossumdc91b992001-08-08 22:26:22 +00002916
2917#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002919FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002921 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002922 int do_other = self->ob_type != other->ob_type && \
2923 other->ob_type->tp_as_number != NULL && \
2924 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002925 if (self->ob_type->tp_as_number != NULL && \
2926 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2927 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002928 if (do_other && \
2929 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2930 r = call_maybe( \
2931 other, ROPSTR, &rcache_str, "(O)", self); \
2932 if (r != Py_NotImplemented) \
2933 return r; \
2934 Py_DECREF(r); \
2935 do_other = 0; \
2936 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002937 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002938 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002939 if (r != Py_NotImplemented || \
2940 other->ob_type == self->ob_type) \
2941 return r; \
2942 Py_DECREF(r); \
2943 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002944 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002945 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002946 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002947 } \
2948 Py_INCREF(Py_NotImplemented); \
2949 return Py_NotImplemented; \
2950}
2951
2952#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2953 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2954
2955#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2956static PyObject * \
2957FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2958{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002959 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002960 return call_method(self, OPSTR, &cache_str, \
2961 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962}
2963
2964static int
2965slot_sq_length(PyObject *self)
2966{
Guido van Rossum2730b132001-08-28 18:22:14 +00002967 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002968 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002969 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970
2971 if (res == NULL)
2972 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002973 len = (int)PyInt_AsLong(res);
2974 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00002975 if (len == -1 && PyErr_Occurred())
2976 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00002977 if (len < 0) {
2978 PyErr_SetString(PyExc_ValueError,
2979 "__len__() should return >= 0");
2980 return -1;
2981 }
Guido van Rossum26111622001-10-01 16:42:49 +00002982 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983}
2984
Guido van Rossumdc91b992001-08-08 22:26:22 +00002985SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2986SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002987
2988/* Super-optimized version of slot_sq_item.
2989 Other slots could do the same... */
2990static PyObject *
2991slot_sq_item(PyObject *self, int i)
2992{
2993 static PyObject *getitem_str;
2994 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2995 descrgetfunc f;
2996
2997 if (getitem_str == NULL) {
2998 getitem_str = PyString_InternFromString("__getitem__");
2999 if (getitem_str == NULL)
3000 return NULL;
3001 }
3002 func = _PyType_Lookup(self->ob_type, getitem_str);
3003 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003004 if ((f = func->ob_type->tp_descr_get) == NULL)
3005 Py_INCREF(func);
3006 else
3007 func = f(func, self, (PyObject *)(self->ob_type));
3008 ival = PyInt_FromLong(i);
3009 if (ival != NULL) {
3010 args = PyTuple_New(1);
3011 if (args != NULL) {
3012 PyTuple_SET_ITEM(args, 0, ival);
3013 retval = PyObject_Call(func, args, NULL);
3014 Py_XDECREF(args);
3015 Py_XDECREF(func);
3016 return retval;
3017 }
3018 }
3019 }
3020 else {
3021 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3022 }
3023 Py_XDECREF(args);
3024 Py_XDECREF(ival);
3025 Py_XDECREF(func);
3026 return NULL;
3027}
3028
Guido van Rossumdc91b992001-08-08 22:26:22 +00003029SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030
3031static int
3032slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3033{
3034 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003035 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036
3037 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003038 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003039 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003041 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003042 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043 if (res == NULL)
3044 return -1;
3045 Py_DECREF(res);
3046 return 0;
3047}
3048
3049static int
3050slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3051{
3052 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003053 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054
3055 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003056 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003057 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003059 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003060 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061 if (res == NULL)
3062 return -1;
3063 Py_DECREF(res);
3064 return 0;
3065}
3066
3067static int
3068slot_sq_contains(PyObject *self, PyObject *value)
3069{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003070 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003071 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072
Guido van Rossum55f20992001-10-01 17:18:22 +00003073 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003074
3075 if (func != NULL) {
3076 args = Py_BuildValue("(O)", value);
3077 if (args == NULL)
3078 res = NULL;
3079 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003080 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003081 Py_DECREF(args);
3082 }
3083 Py_DECREF(func);
3084 if (res == NULL)
3085 return -1;
3086 return PyObject_IsTrue(res);
3087 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003088 else if (PyErr_Occurred())
3089 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003090 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003091 return _PySequence_IterSearch(self, value,
3092 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003093 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094}
3095
Guido van Rossumdc91b992001-08-08 22:26:22 +00003096SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3097SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098
3099#define slot_mp_length slot_sq_length
3100
Guido van Rossumdc91b992001-08-08 22:26:22 +00003101SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102
3103static int
3104slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3105{
3106 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003107 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108
3109 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003110 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003111 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003113 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003114 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115 if (res == NULL)
3116 return -1;
3117 Py_DECREF(res);
3118 return 0;
3119}
3120
Guido van Rossumdc91b992001-08-08 22:26:22 +00003121SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3122SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3123SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3124SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3125SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3126SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3127
Jeremy Hylton938ace62002-07-17 16:30:39 +00003128static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003129
3130SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3131 nb_power, "__pow__", "__rpow__")
3132
3133static PyObject *
3134slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3135{
Guido van Rossum2730b132001-08-28 18:22:14 +00003136 static PyObject *pow_str;
3137
Guido van Rossumdc91b992001-08-08 22:26:22 +00003138 if (modulus == Py_None)
3139 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003140 /* Three-arg power doesn't use __rpow__. But ternary_op
3141 can call this when the second argument's type uses
3142 slot_nb_power, so check before calling self.__pow__. */
3143 if (self->ob_type->tp_as_number != NULL &&
3144 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3145 return call_method(self, "__pow__", &pow_str,
3146 "(OO)", other, modulus);
3147 }
3148 Py_INCREF(Py_NotImplemented);
3149 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003150}
3151
3152SLOT0(slot_nb_negative, "__neg__")
3153SLOT0(slot_nb_positive, "__pos__")
3154SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155
3156static int
3157slot_nb_nonzero(PyObject *self)
3158{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003159 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003160 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003161
Guido van Rossum55f20992001-10-01 17:18:22 +00003162 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003163 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003164 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003165 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003166 func = lookup_maybe(self, "__len__", &len_str);
3167 if (func == NULL) {
3168 if (PyErr_Occurred())
3169 return -1;
3170 else
3171 return 1;
3172 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003173 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003174 res = PyObject_CallObject(func, NULL);
3175 Py_DECREF(func);
3176 if (res == NULL)
3177 return -1;
3178 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003179}
3180
Guido van Rossumdc91b992001-08-08 22:26:22 +00003181SLOT0(slot_nb_invert, "__invert__")
3182SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3183SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3184SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3185SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3186SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003187
3188static int
3189slot_nb_coerce(PyObject **a, PyObject **b)
3190{
3191 static PyObject *coerce_str;
3192 PyObject *self = *a, *other = *b;
3193
3194 if (self->ob_type->tp_as_number != NULL &&
3195 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3196 PyObject *r;
3197 r = call_maybe(
3198 self, "__coerce__", &coerce_str, "(O)", other);
3199 if (r == NULL)
3200 return -1;
3201 if (r == Py_NotImplemented) {
3202 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003203 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003204 else {
3205 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3206 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003207 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003208 Py_DECREF(r);
3209 return -1;
3210 }
3211 *a = PyTuple_GET_ITEM(r, 0);
3212 Py_INCREF(*a);
3213 *b = PyTuple_GET_ITEM(r, 1);
3214 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003215 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003216 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003217 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003218 }
3219 if (other->ob_type->tp_as_number != NULL &&
3220 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3221 PyObject *r;
3222 r = call_maybe(
3223 other, "__coerce__", &coerce_str, "(O)", self);
3224 if (r == NULL)
3225 return -1;
3226 if (r == Py_NotImplemented) {
3227 Py_DECREF(r);
3228 return 1;
3229 }
3230 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3231 PyErr_SetString(PyExc_TypeError,
3232 "__coerce__ didn't return a 2-tuple");
3233 Py_DECREF(r);
3234 return -1;
3235 }
3236 *a = PyTuple_GET_ITEM(r, 1);
3237 Py_INCREF(*a);
3238 *b = PyTuple_GET_ITEM(r, 0);
3239 Py_INCREF(*b);
3240 Py_DECREF(r);
3241 return 0;
3242 }
3243 return 1;
3244}
3245
Guido van Rossumdc91b992001-08-08 22:26:22 +00003246SLOT0(slot_nb_int, "__int__")
3247SLOT0(slot_nb_long, "__long__")
3248SLOT0(slot_nb_float, "__float__")
3249SLOT0(slot_nb_oct, "__oct__")
3250SLOT0(slot_nb_hex, "__hex__")
3251SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3252SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3253SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3254SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3255SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3256SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3257SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3258SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3259SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3260SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3261SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3262SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3263 "__floordiv__", "__rfloordiv__")
3264SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3265SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3266SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003267
3268static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003269half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003270{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003271 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003272 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274
Guido van Rossum60718732001-08-28 17:47:51 +00003275 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003276 if (func == NULL) {
3277 PyErr_Clear();
3278 }
3279 else {
3280 args = Py_BuildValue("(O)", other);
3281 if (args == NULL)
3282 res = NULL;
3283 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003284 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003285 Py_DECREF(args);
3286 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003287 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003288 if (res != Py_NotImplemented) {
3289 if (res == NULL)
3290 return -2;
3291 c = PyInt_AsLong(res);
3292 Py_DECREF(res);
3293 if (c == -1 && PyErr_Occurred())
3294 return -2;
3295 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3296 }
3297 Py_DECREF(res);
3298 }
3299 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300}
3301
Guido van Rossumab3b0342001-09-18 20:38:53 +00003302/* This slot is published for the benefit of try_3way_compare in object.c */
3303int
3304_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003305{
3306 int c;
3307
Guido van Rossumab3b0342001-09-18 20:38:53 +00003308 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003309 c = half_compare(self, other);
3310 if (c <= 1)
3311 return c;
3312 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003313 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003314 c = half_compare(other, self);
3315 if (c < -1)
3316 return -2;
3317 if (c <= 1)
3318 return -c;
3319 }
3320 return (void *)self < (void *)other ? -1 :
3321 (void *)self > (void *)other ? 1 : 0;
3322}
3323
3324static PyObject *
3325slot_tp_repr(PyObject *self)
3326{
3327 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003328 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003329
Guido van Rossum60718732001-08-28 17:47:51 +00003330 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003331 if (func != NULL) {
3332 res = PyEval_CallObject(func, NULL);
3333 Py_DECREF(func);
3334 return res;
3335 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003336 PyErr_Clear();
3337 return PyString_FromFormat("<%s object at %p>",
3338 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003339}
3340
3341static PyObject *
3342slot_tp_str(PyObject *self)
3343{
3344 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003345 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003346
Guido van Rossum60718732001-08-28 17:47:51 +00003347 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003348 if (func != NULL) {
3349 res = PyEval_CallObject(func, NULL);
3350 Py_DECREF(func);
3351 return res;
3352 }
3353 else {
3354 PyErr_Clear();
3355 return slot_tp_repr(self);
3356 }
3357}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358
3359static long
3360slot_tp_hash(PyObject *self)
3361{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003362 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003363 static PyObject *hash_str, *eq_str, *cmp_str;
3364
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365 long h;
3366
Guido van Rossum60718732001-08-28 17:47:51 +00003367 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003368
3369 if (func != NULL) {
3370 res = PyEval_CallObject(func, NULL);
3371 Py_DECREF(func);
3372 if (res == NULL)
3373 return -1;
3374 h = PyInt_AsLong(res);
3375 }
3376 else {
3377 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003378 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003379 if (func == NULL) {
3380 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003381 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003382 }
3383 if (func != NULL) {
3384 Py_DECREF(func);
3385 PyErr_SetString(PyExc_TypeError, "unhashable type");
3386 return -1;
3387 }
3388 PyErr_Clear();
3389 h = _Py_HashPointer((void *)self);
3390 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391 if (h == -1 && !PyErr_Occurred())
3392 h = -2;
3393 return h;
3394}
3395
3396static PyObject *
3397slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3398{
Guido van Rossum60718732001-08-28 17:47:51 +00003399 static PyObject *call_str;
3400 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003401 PyObject *res;
3402
3403 if (meth == NULL)
3404 return NULL;
3405 res = PyObject_Call(meth, args, kwds);
3406 Py_DECREF(meth);
3407 return res;
3408}
3409
Guido van Rossum14a6f832001-10-17 13:59:09 +00003410/* There are two slot dispatch functions for tp_getattro.
3411
3412 - slot_tp_getattro() is used when __getattribute__ is overridden
3413 but no __getattr__ hook is present;
3414
3415 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3416
Guido van Rossumc334df52002-04-04 23:44:47 +00003417 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3418 detects the absence of __getattr__ and then installs the simpler slot if
3419 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003420
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421static PyObject *
3422slot_tp_getattro(PyObject *self, PyObject *name)
3423{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003424 static PyObject *getattribute_str = NULL;
3425 return call_method(self, "__getattribute__", &getattribute_str,
3426 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003427}
3428
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003429static PyObject *
3430slot_tp_getattr_hook(PyObject *self, PyObject *name)
3431{
3432 PyTypeObject *tp = self->ob_type;
3433 PyObject *getattr, *getattribute, *res;
3434 static PyObject *getattribute_str = NULL;
3435 static PyObject *getattr_str = NULL;
3436
3437 if (getattr_str == NULL) {
3438 getattr_str = PyString_InternFromString("__getattr__");
3439 if (getattr_str == NULL)
3440 return NULL;
3441 }
3442 if (getattribute_str == NULL) {
3443 getattribute_str =
3444 PyString_InternFromString("__getattribute__");
3445 if (getattribute_str == NULL)
3446 return NULL;
3447 }
3448 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003449 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003450 /* No __getattr__ hook: use a simpler dispatcher */
3451 tp->tp_getattro = slot_tp_getattro;
3452 return slot_tp_getattro(self, name);
3453 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003454 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003455 if (getattribute == NULL ||
3456 (getattribute->ob_type == &PyWrapperDescr_Type &&
3457 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3458 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003459 res = PyObject_GenericGetAttr(self, name);
3460 else
3461 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003462 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003463 PyErr_Clear();
3464 res = PyObject_CallFunction(getattr, "OO", self, name);
3465 }
3466 return res;
3467}
3468
Tim Peters6d6c1a32001-08-02 04:15:00 +00003469static int
3470slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3471{
3472 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003473 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003474
3475 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003476 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003477 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003479 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003480 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481 if (res == NULL)
3482 return -1;
3483 Py_DECREF(res);
3484 return 0;
3485}
3486
3487/* Map rich comparison operators to their __xx__ namesakes */
3488static char *name_op[] = {
3489 "__lt__",
3490 "__le__",
3491 "__eq__",
3492 "__ne__",
3493 "__gt__",
3494 "__ge__",
3495};
3496
3497static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003498half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003500 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003501 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502
Guido van Rossum60718732001-08-28 17:47:51 +00003503 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003504 if (func == NULL) {
3505 PyErr_Clear();
3506 Py_INCREF(Py_NotImplemented);
3507 return Py_NotImplemented;
3508 }
3509 args = Py_BuildValue("(O)", other);
3510 if (args == NULL)
3511 res = NULL;
3512 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003513 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003514 Py_DECREF(args);
3515 }
3516 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517 return res;
3518}
3519
Guido van Rossumb8f63662001-08-15 23:57:02 +00003520/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3521static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3522
3523static PyObject *
3524slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3525{
3526 PyObject *res;
3527
3528 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3529 res = half_richcompare(self, other, op);
3530 if (res != Py_NotImplemented)
3531 return res;
3532 Py_DECREF(res);
3533 }
3534 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3535 res = half_richcompare(other, self, swapped_op[op]);
3536 if (res != Py_NotImplemented) {
3537 return res;
3538 }
3539 Py_DECREF(res);
3540 }
3541 Py_INCREF(Py_NotImplemented);
3542 return Py_NotImplemented;
3543}
3544
3545static PyObject *
3546slot_tp_iter(PyObject *self)
3547{
3548 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003549 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003550
Guido van Rossum60718732001-08-28 17:47:51 +00003551 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003552 if (func != NULL) {
3553 res = PyObject_CallObject(func, NULL);
3554 Py_DECREF(func);
3555 return res;
3556 }
3557 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003558 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003559 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003560 PyErr_SetString(PyExc_TypeError,
3561 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003562 return NULL;
3563 }
3564 Py_DECREF(func);
3565 return PySeqIter_New(self);
3566}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003567
3568static PyObject *
3569slot_tp_iternext(PyObject *self)
3570{
Guido van Rossum2730b132001-08-28 18:22:14 +00003571 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003572 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003573}
3574
Guido van Rossum1a493502001-08-17 16:47:50 +00003575static PyObject *
3576slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3577{
3578 PyTypeObject *tp = self->ob_type;
3579 PyObject *get;
3580 static PyObject *get_str = NULL;
3581
3582 if (get_str == NULL) {
3583 get_str = PyString_InternFromString("__get__");
3584 if (get_str == NULL)
3585 return NULL;
3586 }
3587 get = _PyType_Lookup(tp, get_str);
3588 if (get == NULL) {
3589 /* Avoid further slowdowns */
3590 if (tp->tp_descr_get == slot_tp_descr_get)
3591 tp->tp_descr_get = NULL;
3592 Py_INCREF(self);
3593 return self;
3594 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003595 if (obj == NULL)
3596 obj = Py_None;
3597 if (type == NULL)
3598 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003599 return PyObject_CallFunction(get, "OOO", self, obj, type);
3600}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003601
3602static int
3603slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3604{
Guido van Rossum2c252392001-08-24 10:13:31 +00003605 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003606 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003607
3608 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003609 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003610 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003611 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003612 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003613 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614 if (res == NULL)
3615 return -1;
3616 Py_DECREF(res);
3617 return 0;
3618}
3619
3620static int
3621slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3622{
Guido van Rossum60718732001-08-28 17:47:51 +00003623 static PyObject *init_str;
3624 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625 PyObject *res;
3626
3627 if (meth == NULL)
3628 return -1;
3629 res = PyObject_Call(meth, args, kwds);
3630 Py_DECREF(meth);
3631 if (res == NULL)
3632 return -1;
3633 Py_DECREF(res);
3634 return 0;
3635}
3636
3637static PyObject *
3638slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3639{
3640 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3641 PyObject *newargs, *x;
3642 int i, n;
3643
3644 if (func == NULL)
3645 return NULL;
3646 assert(PyTuple_Check(args));
3647 n = PyTuple_GET_SIZE(args);
3648 newargs = PyTuple_New(n+1);
3649 if (newargs == NULL)
3650 return NULL;
3651 Py_INCREF(type);
3652 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3653 for (i = 0; i < n; i++) {
3654 x = PyTuple_GET_ITEM(args, i);
3655 Py_INCREF(x);
3656 PyTuple_SET_ITEM(newargs, i+1, x);
3657 }
3658 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003659 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660 Py_DECREF(func);
3661 return x;
3662}
3663
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003664
3665/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3666 functions. The offsets here are relative to the 'etype' structure, which
3667 incorporates the additional structures used for numbers, sequences and
3668 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3669 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003670 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3671 terminated with an all-zero entry. (This table is further initialized and
3672 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003673
Guido van Rossum6d204072001-10-21 00:44:31 +00003674typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003675
3676#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003677#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003678#undef ETSLOT
3679#undef SQSLOT
3680#undef MPSLOT
3681#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003682#undef UNSLOT
3683#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003684#undef BINSLOT
3685#undef RBINSLOT
3686
Guido van Rossum6d204072001-10-21 00:44:31 +00003687#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3688 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003689#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3690 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3691 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003692#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3693 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3694#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3695 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3696#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3697 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3698#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3699 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3700#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3701 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3702 "x." NAME "() <==> " DOC)
3703#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3704 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3705 "x." NAME "(y) <==> x" DOC "y")
3706#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3707 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3708 "x." NAME "(y) <==> x" DOC "y")
3709#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3710 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3711 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003712
3713static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003714 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3715 "x.__len__() <==> len(x)"),
3716 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3717 "x.__add__(y) <==> x+y"),
3718 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3719 "x.__mul__(n) <==> x*n"),
3720 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3721 "x.__rmul__(n) <==> n*x"),
3722 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3723 "x.__getitem__(y) <==> x[y]"),
3724 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3725 "x.__getslice__(i, j) <==> x[i:j]"),
3726 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3727 "x.__setitem__(i, y) <==> x[i]=y"),
3728 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3729 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003730 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003731 wrap_intintobjargproc,
3732 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3733 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3734 "x.__delslice__(i, j) <==> del x[i:j]"),
3735 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3736 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003737 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003738 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003739 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003740 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003741
Guido van Rossum6d204072001-10-21 00:44:31 +00003742 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3743 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003744 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003745 wrap_binaryfunc,
3746 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003747 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003748 wrap_objobjargproc,
3749 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003750 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003751 wrap_delitem,
3752 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003753
Guido van Rossum6d204072001-10-21 00:44:31 +00003754 BINSLOT("__add__", nb_add, slot_nb_add,
3755 "+"),
3756 RBINSLOT("__radd__", nb_add, slot_nb_add,
3757 "+"),
3758 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3759 "-"),
3760 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3761 "-"),
3762 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3763 "*"),
3764 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3765 "*"),
3766 BINSLOT("__div__", nb_divide, slot_nb_divide,
3767 "/"),
3768 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3769 "/"),
3770 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3771 "%"),
3772 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3773 "%"),
3774 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3775 "divmod(x, y)"),
3776 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3777 "divmod(y, x)"),
3778 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3779 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3780 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3781 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3782 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3783 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3784 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3785 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003786 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003787 "x != 0"),
3788 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3789 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3790 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3791 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3792 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3793 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3794 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3795 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3796 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3797 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3798 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3799 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3800 "x.__coerce__(y) <==> coerce(x, y)"),
3801 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3802 "int(x)"),
3803 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3804 "long(x)"),
3805 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3806 "float(x)"),
3807 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3808 "oct(x)"),
3809 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3810 "hex(x)"),
3811 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3812 wrap_binaryfunc, "+"),
3813 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3814 wrap_binaryfunc, "-"),
3815 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3816 wrap_binaryfunc, "*"),
3817 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3818 wrap_binaryfunc, "/"),
3819 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3820 wrap_binaryfunc, "%"),
3821 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3822 wrap_ternaryfunc, "**"),
3823 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3824 wrap_binaryfunc, "<<"),
3825 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3826 wrap_binaryfunc, ">>"),
3827 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3828 wrap_binaryfunc, "&"),
3829 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3830 wrap_binaryfunc, "^"),
3831 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3832 wrap_binaryfunc, "|"),
3833 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3834 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3835 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3836 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3837 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3838 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3839 IBSLOT("__itruediv__", nb_inplace_true_divide,
3840 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003841
Guido van Rossum6d204072001-10-21 00:44:31 +00003842 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3843 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003844 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003845 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3846 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003847 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003848 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3849 "x.__cmp__(y) <==> cmp(x,y)"),
3850 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3851 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003852 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3853 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003854 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003855 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3856 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3857 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3858 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3859 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3860 "x.__setattr__('name', value) <==> x.name = value"),
3861 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3862 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3863 "x.__delattr__('name') <==> del x.name"),
3864 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3865 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3866 "x.__lt__(y) <==> x<y"),
3867 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3868 "x.__le__(y) <==> x<=y"),
3869 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3870 "x.__eq__(y) <==> x==y"),
3871 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3872 "x.__ne__(y) <==> x!=y"),
3873 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3874 "x.__gt__(y) <==> x>y"),
3875 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3876 "x.__ge__(y) <==> x>=y"),
3877 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3878 "x.__iter__() <==> iter(x)"),
3879 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3880 "x.next() -> the next value, or raise StopIteration"),
3881 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3882 "descr.__get__(obj[, type]) -> value"),
3883 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3884 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003885 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003886 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003887 "see x.__class__.__doc__ for signature",
3888 PyWrapperFlag_KEYWORDS),
3889 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003890 {NULL}
3891};
3892
Guido van Rossumc334df52002-04-04 23:44:47 +00003893/* Given a type pointer and an offset gotten from a slotdef entry, return a
3894 pointer to the actual slot. This is not quite the same as simply adding
3895 the offset to the type pointer, since it takes care to indirect through the
3896 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3897 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003898static void **
3899slotptr(PyTypeObject *type, int offset)
3900{
3901 char *ptr;
3902
Guido van Rossum09638c12002-06-13 19:17:46 +00003903 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003904 assert(offset >= 0);
3905 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003906 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003907 ptr = (void *)type->tp_as_sequence;
3908 offset -= offsetof(etype, as_sequence);
3909 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003910 else if (offset >= offsetof(etype, as_mapping)) {
3911 ptr = (void *)type->tp_as_mapping;
3912 offset -= offsetof(etype, as_mapping);
3913 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003914 else if (offset >= offsetof(etype, as_number)) {
3915 ptr = (void *)type->tp_as_number;
3916 offset -= offsetof(etype, as_number);
3917 }
3918 else {
3919 ptr = (void *)type;
3920 }
3921 if (ptr != NULL)
3922 ptr += offset;
3923 return (void **)ptr;
3924}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003925
Guido van Rossumc334df52002-04-04 23:44:47 +00003926/* Length of array of slotdef pointers used to store slots with the
3927 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3928 the same __name__, for any __name__. Since that's a static property, it is
3929 appropriate to declare fixed-size arrays for this. */
3930#define MAX_EQUIV 10
3931
3932/* Return a slot pointer for a given name, but ONLY if the attribute has
3933 exactly one slot function. The name must be an interned string. */
3934static void **
3935resolve_slotdups(PyTypeObject *type, PyObject *name)
3936{
3937 /* XXX Maybe this could be optimized more -- but is it worth it? */
3938
3939 /* pname and ptrs act as a little cache */
3940 static PyObject *pname;
3941 static slotdef *ptrs[MAX_EQUIV];
3942 slotdef *p, **pp;
3943 void **res, **ptr;
3944
3945 if (pname != name) {
3946 /* Collect all slotdefs that match name into ptrs. */
3947 pname = name;
3948 pp = ptrs;
3949 for (p = slotdefs; p->name_strobj; p++) {
3950 if (p->name_strobj == name)
3951 *pp++ = p;
3952 }
3953 *pp = NULL;
3954 }
3955
3956 /* Look in all matching slots of the type; if exactly one of these has
3957 a filled-in slot, return its value. Otherwise return NULL. */
3958 res = NULL;
3959 for (pp = ptrs; *pp; pp++) {
3960 ptr = slotptr(type, (*pp)->offset);
3961 if (ptr == NULL || *ptr == NULL)
3962 continue;
3963 if (res != NULL)
3964 return NULL;
3965 res = ptr;
3966 }
3967 return res;
3968}
3969
3970/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3971 does some incredibly complex thinking and then sticks something into the
3972 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3973 interests, and then stores a generic wrapper or a specific function into
3974 the slot.) Return a pointer to the next slotdef with a different offset,
3975 because that's convenient for fixup_slot_dispatchers(). */
3976static slotdef *
3977update_one_slot(PyTypeObject *type, slotdef *p)
3978{
3979 PyObject *descr;
3980 PyWrapperDescrObject *d;
3981 void *generic = NULL, *specific = NULL;
3982 int use_generic = 0;
3983 int offset = p->offset;
3984 void **ptr = slotptr(type, offset);
3985
3986 if (ptr == NULL) {
3987 do {
3988 ++p;
3989 } while (p->offset == offset);
3990 return p;
3991 }
3992 do {
3993 descr = _PyType_Lookup(type, p->name_strobj);
3994 if (descr == NULL)
3995 continue;
3996 if (descr->ob_type == &PyWrapperDescr_Type) {
3997 void **tptr = resolve_slotdups(type, p->name_strobj);
3998 if (tptr == NULL || tptr == ptr)
3999 generic = p->function;
4000 d = (PyWrapperDescrObject *)descr;
4001 if (d->d_base->wrapper == p->wrapper &&
4002 PyType_IsSubtype(type, d->d_type))
4003 {
4004 if (specific == NULL ||
4005 specific == d->d_wrapped)
4006 specific = d->d_wrapped;
4007 else
4008 use_generic = 1;
4009 }
4010 }
4011 else {
4012 use_generic = 1;
4013 generic = p->function;
4014 }
4015 } while ((++p)->offset == offset);
4016 if (specific && !use_generic)
4017 *ptr = specific;
4018 else
4019 *ptr = generic;
4020 return p;
4021}
4022
Jeremy Hylton938ace62002-07-17 16:30:39 +00004023static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
4024 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004025
Guido van Rossumc334df52002-04-04 23:44:47 +00004026/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4027 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004028static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004029update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004030{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004031 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004032
Guido van Rossumc334df52002-04-04 23:44:47 +00004033 for (pp = pp0; *pp; pp++)
4034 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004035 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004036}
4037
Guido van Rossumc334df52002-04-04 23:44:47 +00004038/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4039 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004040static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004041recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004042{
4043 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004044 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004045 int i, n;
4046
4047 subclasses = type->tp_subclasses;
4048 if (subclasses == NULL)
4049 return 0;
4050 assert(PyList_Check(subclasses));
4051 n = PyList_GET_SIZE(subclasses);
4052 for (i = 0; i < n; i++) {
4053 ref = PyList_GET_ITEM(subclasses, i);
4054 assert(PyWeakref_CheckRef(ref));
4055 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004056 assert(subclass != NULL);
4057 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004058 continue;
4059 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004060 /* Avoid recursing down into unaffected classes */
4061 dict = subclass->tp_dict;
4062 if (dict != NULL && PyDict_Check(dict) &&
4063 PyDict_GetItem(dict, name) != NULL)
4064 continue;
4065 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004066 return -1;
4067 }
4068 return 0;
4069}
4070
Guido van Rossumc334df52002-04-04 23:44:47 +00004071/* Comparison function for qsort() to compare slotdefs by their offset, and
4072 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004073static int
4074slotdef_cmp(const void *aa, const void *bb)
4075{
4076 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4077 int c = a->offset - b->offset;
4078 if (c != 0)
4079 return c;
4080 else
4081 return a - b;
4082}
4083
Guido van Rossumc334df52002-04-04 23:44:47 +00004084/* Initialize the slotdefs table by adding interned string objects for the
4085 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004086static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004087init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004088{
4089 slotdef *p;
4090 static int initialized = 0;
4091
4092 if (initialized)
4093 return;
4094 for (p = slotdefs; p->name; p++) {
4095 p->name_strobj = PyString_InternFromString(p->name);
4096 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004097 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004098 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004099 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4100 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004101 initialized = 1;
4102}
4103
Guido van Rossumc334df52002-04-04 23:44:47 +00004104/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004105static int
4106update_slot(PyTypeObject *type, PyObject *name)
4107{
Guido van Rossumc334df52002-04-04 23:44:47 +00004108 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004109 slotdef *p;
4110 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004111 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004112
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004113 init_slotdefs();
4114 pp = ptrs;
4115 for (p = slotdefs; p->name; p++) {
4116 /* XXX assume name is interned! */
4117 if (p->name_strobj == name)
4118 *pp++ = p;
4119 }
4120 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004121 for (pp = ptrs; *pp; pp++) {
4122 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004123 offset = p->offset;
4124 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004125 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004126 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004127 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004128 if (ptrs[0] == NULL)
4129 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004130 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004131}
4132
Guido van Rossumc334df52002-04-04 23:44:47 +00004133/* Store the proper functions in the slot dispatches at class (type)
4134 definition time, based upon which operations the class overrides in its
4135 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004137fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004139 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004141 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004142 for (p = slotdefs; p->name; )
4143 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004145
Guido van Rossum6d204072001-10-21 00:44:31 +00004146/* This function is called by PyType_Ready() to populate the type's
4147 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004148 function slot (like tp_repr) that's defined in the type, one or more
4149 corresponding descriptors are added in the type's tp_dict dictionary
4150 under the appropriate name (like __repr__). Some function slots
4151 cause more than one descriptor to be added (for example, the nb_add
4152 slot adds both __add__ and __radd__ descriptors) and some function
4153 slots compete for the same descriptor (for example both sq_item and
4154 mp_subscript generate a __getitem__ descriptor).
4155
4156 In the latter case, the first slotdef entry encoutered wins. Since
4157 slotdef entries are sorted by the offset of the slot in the etype
4158 struct, this gives us some control over disambiguating between
4159 competing slots: the members of struct etype are listed from most
4160 general to least general, so the most general slot is preferred. In
4161 particular, because as_mapping comes before as_sequence, for a type
4162 that defines both mp_subscript and sq_item, mp_subscript wins.
4163
4164 This only adds new descriptors and doesn't overwrite entries in
4165 tp_dict that were previously defined. The descriptors contain a
4166 reference to the C function they must call, so that it's safe if they
4167 are copied into a subtype's __dict__ and the subtype has a different
4168 C function in its slot -- calling the method defined by the
4169 descriptor will call the C function that was used to create it,
4170 rather than the C function present in the slot when it is called.
4171 (This is important because a subtype may have a C function in the
4172 slot that calls the method from the dictionary, and we want to avoid
4173 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004174
4175static int
4176add_operators(PyTypeObject *type)
4177{
4178 PyObject *dict = type->tp_dict;
4179 slotdef *p;
4180 PyObject *descr;
4181 void **ptr;
4182
4183 init_slotdefs();
4184 for (p = slotdefs; p->name; p++) {
4185 if (p->wrapper == NULL)
4186 continue;
4187 ptr = slotptr(type, p->offset);
4188 if (!ptr || !*ptr)
4189 continue;
4190 if (PyDict_GetItem(dict, p->name_strobj))
4191 continue;
4192 descr = PyDescr_NewWrapper(type, p, *ptr);
4193 if (descr == NULL)
4194 return -1;
4195 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4196 return -1;
4197 Py_DECREF(descr);
4198 }
4199 if (type->tp_new != NULL) {
4200 if (add_tp_new_wrapper(type) < 0)
4201 return -1;
4202 }
4203 return 0;
4204}
4205
Guido van Rossum705f0f52001-08-24 16:47:00 +00004206
4207/* Cooperative 'super' */
4208
4209typedef struct {
4210 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004211 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004212 PyObject *obj;
4213} superobject;
4214
Guido van Rossum6f799372001-09-20 20:46:19 +00004215static PyMemberDef super_members[] = {
4216 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4217 "the class invoking super()"},
4218 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4219 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004220 {0}
4221};
4222
Guido van Rossum705f0f52001-08-24 16:47:00 +00004223static void
4224super_dealloc(PyObject *self)
4225{
4226 superobject *su = (superobject *)self;
4227
Guido van Rossum048eb752001-10-02 21:24:57 +00004228 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004229 Py_XDECREF(su->obj);
4230 Py_XDECREF(su->type);
4231 self->ob_type->tp_free(self);
4232}
4233
4234static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004235super_repr(PyObject *self)
4236{
4237 superobject *su = (superobject *)self;
4238
4239 if (su->obj)
4240 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004241 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004242 su->type ? su->type->tp_name : "NULL",
4243 su->obj->ob_type->tp_name);
4244 else
4245 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004246 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004247 su->type ? su->type->tp_name : "NULL");
4248}
4249
4250static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004251super_getattro(PyObject *self, PyObject *name)
4252{
4253 superobject *su = (superobject *)self;
4254
4255 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004256 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004257 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004258 descrgetfunc f;
4259 int i, n;
4260
Guido van Rossum155db9a2002-04-02 17:53:47 +00004261 starttype = su->obj->ob_type;
4262 mro = starttype->tp_mro;
4263
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004264 if (mro == NULL)
4265 n = 0;
4266 else {
4267 assert(PyTuple_Check(mro));
4268 n = PyTuple_GET_SIZE(mro);
4269 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004270 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004271 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004272 break;
4273 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004274 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004275 starttype = (PyTypeObject *)(su->obj);
4276 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004277 if (mro == NULL)
4278 n = 0;
4279 else {
4280 assert(PyTuple_Check(mro));
4281 n = PyTuple_GET_SIZE(mro);
4282 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004283 for (i = 0; i < n; i++) {
4284 if ((PyObject *)(su->type) ==
4285 PyTuple_GET_ITEM(mro, i))
4286 break;
4287 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004288 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004289 i++;
4290 res = NULL;
4291 for (; i < n; i++) {
4292 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004293 if (PyType_Check(tmp))
4294 dict = ((PyTypeObject *)tmp)->tp_dict;
4295 else if (PyClass_Check(tmp))
4296 dict = ((PyClassObject *)tmp)->cl_dict;
4297 else
4298 continue;
4299 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004300 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004301 Py_INCREF(res);
4302 f = res->ob_type->tp_descr_get;
4303 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004304 tmp = f(res, su->obj,
4305 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004306 Py_DECREF(res);
4307 res = tmp;
4308 }
4309 return res;
4310 }
4311 }
4312 }
4313 return PyObject_GenericGetAttr(self, name);
4314}
4315
Guido van Rossum5b443c62001-12-03 15:38:28 +00004316static int
4317supercheck(PyTypeObject *type, PyObject *obj)
4318{
4319 if (!PyType_IsSubtype(obj->ob_type, type) &&
4320 !(PyType_Check(obj) &&
4321 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4322 PyErr_SetString(PyExc_TypeError,
4323 "super(type, obj): "
4324 "obj must be an instance or subtype of type");
4325 return -1;
4326 }
4327 else
4328 return 0;
4329}
4330
Guido van Rossum705f0f52001-08-24 16:47:00 +00004331static PyObject *
4332super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4333{
4334 superobject *su = (superobject *)self;
4335 superobject *new;
4336
4337 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4338 /* Not binding to an object, or already bound */
4339 Py_INCREF(self);
4340 return self;
4341 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004342 if (su->ob_type != &PySuper_Type)
4343 /* If su is an instance of a subclass of super,
4344 call its type */
4345 return PyObject_CallFunction((PyObject *)su->ob_type,
4346 "OO", su->type, obj);
4347 else {
4348 /* Inline the common case */
4349 if (supercheck(su->type, obj) < 0)
4350 return NULL;
4351 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4352 NULL, NULL);
4353 if (new == NULL)
4354 return NULL;
4355 Py_INCREF(su->type);
4356 Py_INCREF(obj);
4357 new->type = su->type;
4358 new->obj = obj;
4359 return (PyObject *)new;
4360 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004361}
4362
4363static int
4364super_init(PyObject *self, PyObject *args, PyObject *kwds)
4365{
4366 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004367 PyTypeObject *type;
4368 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004369
4370 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4371 return -1;
4372 if (obj == Py_None)
4373 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004374 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004375 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004376 Py_INCREF(type);
4377 Py_XINCREF(obj);
4378 su->type = type;
4379 su->obj = obj;
4380 return 0;
4381}
4382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004383PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004384"super(type) -> unbound super object\n"
4385"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004386"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004387"Typical use to call a cooperative superclass method:\n"
4388"class C(B):\n"
4389" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004390" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004391
Guido van Rossum048eb752001-10-02 21:24:57 +00004392static int
4393super_traverse(PyObject *self, visitproc visit, void *arg)
4394{
4395 superobject *su = (superobject *)self;
4396 int err;
4397
4398#define VISIT(SLOT) \
4399 if (SLOT) { \
4400 err = visit((PyObject *)(SLOT), arg); \
4401 if (err) \
4402 return err; \
4403 }
4404
4405 VISIT(su->obj);
4406 VISIT(su->type);
4407
4408#undef VISIT
4409
4410 return 0;
4411}
4412
Guido van Rossum705f0f52001-08-24 16:47:00 +00004413PyTypeObject PySuper_Type = {
4414 PyObject_HEAD_INIT(&PyType_Type)
4415 0, /* ob_size */
4416 "super", /* tp_name */
4417 sizeof(superobject), /* tp_basicsize */
4418 0, /* tp_itemsize */
4419 /* methods */
4420 super_dealloc, /* tp_dealloc */
4421 0, /* tp_print */
4422 0, /* tp_getattr */
4423 0, /* tp_setattr */
4424 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004425 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004426 0, /* tp_as_number */
4427 0, /* tp_as_sequence */
4428 0, /* tp_as_mapping */
4429 0, /* tp_hash */
4430 0, /* tp_call */
4431 0, /* tp_str */
4432 super_getattro, /* tp_getattro */
4433 0, /* tp_setattro */
4434 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004435 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4436 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004437 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004438 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004439 0, /* tp_clear */
4440 0, /* tp_richcompare */
4441 0, /* tp_weaklistoffset */
4442 0, /* tp_iter */
4443 0, /* tp_iternext */
4444 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004445 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004446 0, /* tp_getset */
4447 0, /* tp_base */
4448 0, /* tp_dict */
4449 super_descr_get, /* tp_descr_get */
4450 0, /* tp_descr_set */
4451 0, /* tp_dictoffset */
4452 super_init, /* tp_init */
4453 PyType_GenericAlloc, /* tp_alloc */
4454 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004455 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004456};