blob: a7afa9b7f0cc30d9a03f7cd5e6abb1b961d08c35 [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;
202 if (type->tp_init != NULL &&
203 type->tp_init(obj, args, kwds) < 0) {
204 Py_DECREF(obj);
205 obj = NULL;
206 }
207 }
208 return obj;
209}
210
211PyObject *
212PyType_GenericAlloc(PyTypeObject *type, int nitems)
213{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000214 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000215 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000216
217 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000218 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000219 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000220 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000221
Neil Schemenauerc806c882001-08-29 23:54:54 +0000222 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000223 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000224
Neil Schemenauerc806c882001-08-29 23:54:54 +0000225 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000226
Tim Peters6d6c1a32001-08-02 04:15:00 +0000227 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
228 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000229
Tim Peters6d6c1a32001-08-02 04:15:00 +0000230 if (type->tp_itemsize == 0)
231 PyObject_INIT(obj, type);
232 else
233 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000234
Tim Peters6d6c1a32001-08-02 04:15:00 +0000235 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000236 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000237 return obj;
238}
239
240PyObject *
241PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
242{
243 return type->tp_alloc(type, 0);
244}
245
Guido van Rossum9475a232001-10-05 20:51:39 +0000246/* Helpers for subtyping */
247
248static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000249traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
250{
251 int i, n;
252 PyMemberDef *mp;
253
254 n = type->ob_size;
255 mp = ((etype *)type)->members;
256 for (i = 0; i < n; i++, mp++) {
257 if (mp->type == T_OBJECT_EX) {
258 char *addr = (char *)self + mp->offset;
259 PyObject *obj = *(PyObject **)addr;
260 if (obj != NULL) {
261 int err = visit(obj, arg);
262 if (err)
263 return err;
264 }
265 }
266 }
267 return 0;
268}
269
270static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000271subtype_traverse(PyObject *self, visitproc visit, void *arg)
272{
273 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000274 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000275
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000276 /* Find the nearest base with a different tp_traverse,
277 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000278 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000279 base = type;
280 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
281 if (base->ob_size) {
282 int err = traverse_slots(base, self, visit, arg);
283 if (err)
284 return err;
285 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000286 base = base->tp_base;
287 assert(base);
288 }
289
290 if (type->tp_dictoffset != base->tp_dictoffset) {
291 PyObject **dictptr = _PyObject_GetDictPtr(self);
292 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000293 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000294 if (err)
295 return err;
296 }
297 }
298
Guido van Rossuma3862092002-06-10 15:24:42 +0000299 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
300 /* For a heaptype, the instances count as references
301 to the type. Traverse the type so the collector
302 can find cycles involving this link. */
303 int err = visit((PyObject *)type, arg);
304 if (err)
305 return err;
306 }
307
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000308 if (basetraverse)
309 return basetraverse(self, visit, arg);
310 return 0;
311}
312
313static void
314clear_slots(PyTypeObject *type, PyObject *self)
315{
316 int i, n;
317 PyMemberDef *mp;
318
319 n = type->ob_size;
320 mp = ((etype *)type)->members;
321 for (i = 0; i < n; i++, mp++) {
322 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
323 char *addr = (char *)self + mp->offset;
324 PyObject *obj = *(PyObject **)addr;
325 if (obj != NULL) {
326 Py_DECREF(obj);
327 *(PyObject **)addr = NULL;
328 }
329 }
330 }
331}
332
333static int
334subtype_clear(PyObject *self)
335{
336 PyTypeObject *type, *base;
337 inquiry baseclear;
338
339 /* Find the nearest base with a different tp_clear
340 and clear slots while we're at it */
341 type = self->ob_type;
342 base = type;
343 while ((baseclear = base->tp_clear) == subtype_clear) {
344 if (base->ob_size)
345 clear_slots(base, self);
346 base = base->tp_base;
347 assert(base);
348 }
349
Guido van Rossuma3862092002-06-10 15:24:42 +0000350 /* There's no need to clear the instance dict (if any);
351 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000352
353 if (baseclear)
354 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000355 return 0;
356}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000357
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000358staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
359
360static int
361call_finalizer(PyObject *self)
362{
363 static PyObject *del_str = NULL;
364 PyObject *del, *res;
365 PyObject *error_type, *error_value, *error_traceback;
366
367 /* Temporarily resurrect the object. */
Tim Peters34592512002-07-11 06:23:50 +0000368 assert(self->ob_refcnt == 0);
369 self->ob_refcnt = 1;
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000370
371 /* Save the current exception, if any. */
372 PyErr_Fetch(&error_type, &error_value, &error_traceback);
373
374 /* Execute __del__ method, if any. */
375 del = lookup_maybe(self, "__del__", &del_str);
376 if (del != NULL) {
377 res = PyEval_CallObject(del, NULL);
378 if (res == NULL)
379 PyErr_WriteUnraisable(del);
380 else
381 Py_DECREF(res);
382 Py_DECREF(del);
383 }
384
385 /* Restore the saved exception. */
386 PyErr_Restore(error_type, error_value, error_traceback);
387
388 /* Undo the temporary resurrection; can't use DECREF here, it would
389 * cause a recursive call.
390 */
Tim Peters34592512002-07-11 06:23:50 +0000391 assert(self->ob_refcnt > 0);
392 if (--self->ob_refcnt == 0)
393 return 0; /* this is the normal path out */
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000394
Tim Peters34592512002-07-11 06:23:50 +0000395 /* __del__ resurrected it! Make it look like the original Py_DECREF
396 * never happened.
397 */
398 {
399 int refcnt = self->ob_refcnt;
400 _Py_NewReference(self);
401 self->ob_refcnt = refcnt;
402 }
403 assert(_Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
404 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
405 * _Py_NewReference bumped it again, so that's a wash.
406 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
407 * chain, so no more to do there either.
408 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
409 * _Py_NewReference bumped tp_allocs: both of those need to be
410 * undone.
411 */
412#ifdef COUNT_ALLOCS
413 --self->ob_type->tp_frees;
414 --self->ob_type->tp_allocs;
415#endif
416 return -1; /* __del__ added a reference; don't delete now */
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000417}
418
Tim Peters6d6c1a32001-08-02 04:15:00 +0000419static void
420subtype_dealloc(PyObject *self)
421{
Guido van Rossum14227b42001-12-06 02:35:58 +0000422 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000423 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424
425 /* This exists so we can DECREF self->ob_type */
426
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000427 if (call_finalizer(self) < 0)
428 return;
429
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000430 /* Find the nearest base with a different tp_dealloc
431 and clear slots while we're at it */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000432 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000433 base = type;
434 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
435 if (base->ob_size)
436 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 base = base->tp_base;
438 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000439 }
440
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000442 if (type->tp_dictoffset && !base->tp_dictoffset) {
443 PyObject **dictptr = _PyObject_GetDictPtr(self);
444 if (dictptr != NULL) {
445 PyObject *dict = *dictptr;
446 if (dict != NULL) {
447 Py_DECREF(dict);
448 *dictptr = NULL;
449 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450 }
451 }
452
Guido van Rossum9676b222001-08-17 20:32:36 +0000453 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000454 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000455 PyObject_ClearWeakRefs(self);
456
Tim Peters6d6c1a32001-08-02 04:15:00 +0000457 /* Finalize GC if the base doesn't do GC and we do */
458 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000459 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460
461 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000462 assert(basedealloc);
463 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000464
465 /* Can't reference self beyond this point */
466 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
467 Py_DECREF(type);
468 }
469}
470
Tim Peters6d6c1a32001-08-02 04:15:00 +0000471staticforward PyTypeObject *solid_base(PyTypeObject *type);
472
Tim Peters6d6c1a32001-08-02 04:15:00 +0000473/* type test with subclassing support */
474
475int
476PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
477{
478 PyObject *mro;
479
Guido van Rossum9478d072001-09-07 18:52:13 +0000480 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
481 return b == a || b == &PyBaseObject_Type;
482
Tim Peters6d6c1a32001-08-02 04:15:00 +0000483 mro = a->tp_mro;
484 if (mro != NULL) {
485 /* Deal with multiple inheritance without recursion
486 by walking the MRO tuple */
487 int i, n;
488 assert(PyTuple_Check(mro));
489 n = PyTuple_GET_SIZE(mro);
490 for (i = 0; i < n; i++) {
491 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
492 return 1;
493 }
494 return 0;
495 }
496 else {
497 /* a is not completely initilized yet; follow tp_base */
498 do {
499 if (a == b)
500 return 1;
501 a = a->tp_base;
502 } while (a != NULL);
503 return b == &PyBaseObject_Type;
504 }
505}
506
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000507/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000508 without looking in the instance dictionary
509 (so we can't use PyObject_GetAttr) but still binding
510 it to the instance. The arguments are the object,
511 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000512 static variable used to cache the interned Python string.
513
514 Two variants:
515
516 - lookup_maybe() returns NULL without raising an exception
517 when the _PyType_Lookup() call fails;
518
519 - lookup_method() always raises an exception upon errors.
520*/
Guido van Rossum60718732001-08-28 17:47:51 +0000521
522static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000523lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000524{
525 PyObject *res;
526
527 if (*attrobj == NULL) {
528 *attrobj = PyString_InternFromString(attrstr);
529 if (*attrobj == NULL)
530 return NULL;
531 }
532 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000533 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000534 descrgetfunc f;
535 if ((f = res->ob_type->tp_descr_get) == NULL)
536 Py_INCREF(res);
537 else
538 res = f(res, self, (PyObject *)(self->ob_type));
539 }
540 return res;
541}
542
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000543static PyObject *
544lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
545{
546 PyObject *res = lookup_maybe(self, attrstr, attrobj);
547 if (res == NULL && !PyErr_Occurred())
548 PyErr_SetObject(PyExc_AttributeError, *attrobj);
549 return res;
550}
551
Guido van Rossum2730b132001-08-28 18:22:14 +0000552/* A variation of PyObject_CallMethod that uses lookup_method()
553 instead of PyObject_GetAttrString(). This uses the same convention
554 as lookup_method to cache the interned name string object. */
555
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000556static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000557call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
558{
559 va_list va;
560 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000561 va_start(va, format);
562
Guido van Rossumda21c012001-10-03 00:50:18 +0000563 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000564 if (func == NULL) {
565 va_end(va);
566 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000567 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000568 return NULL;
569 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000570
571 if (format && *format)
572 args = Py_VaBuildValue(format, va);
573 else
574 args = PyTuple_New(0);
575
576 va_end(va);
577
578 if (args == NULL)
579 return NULL;
580
581 assert(PyTuple_Check(args));
582 retval = PyObject_Call(func, args, NULL);
583
584 Py_DECREF(args);
585 Py_DECREF(func);
586
587 return retval;
588}
589
590/* Clone of call_method() that returns NotImplemented when the lookup fails. */
591
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000592static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000593call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
594{
595 va_list va;
596 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000597 va_start(va, format);
598
Guido van Rossumda21c012001-10-03 00:50:18 +0000599 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000600 if (func == NULL) {
601 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000602 if (!PyErr_Occurred()) {
603 Py_INCREF(Py_NotImplemented);
604 return Py_NotImplemented;
605 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000606 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000607 }
608
609 if (format && *format)
610 args = Py_VaBuildValue(format, va);
611 else
612 args = PyTuple_New(0);
613
614 va_end(va);
615
Guido van Rossum717ce002001-09-14 16:58:08 +0000616 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000617 return NULL;
618
Guido van Rossum717ce002001-09-14 16:58:08 +0000619 assert(PyTuple_Check(args));
620 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000621
622 Py_DECREF(args);
623 Py_DECREF(func);
624
625 return retval;
626}
627
Tim Peters6d6c1a32001-08-02 04:15:00 +0000628/* Method resolution order algorithm from "Putting Metaclasses to Work"
629 by Forman and Danforth (Addison-Wesley 1999). */
630
631static int
632conservative_merge(PyObject *left, PyObject *right)
633{
634 int left_size;
635 int right_size;
636 int i, j, r, ok;
637 PyObject *temp, *rr;
638
639 assert(PyList_Check(left));
640 assert(PyList_Check(right));
641
642 again:
643 left_size = PyList_GET_SIZE(left);
644 right_size = PyList_GET_SIZE(right);
645 for (i = 0; i < left_size; i++) {
646 for (j = 0; j < right_size; j++) {
647 if (PyList_GET_ITEM(left, i) ==
648 PyList_GET_ITEM(right, j)) {
649 /* found a merge point */
650 temp = PyList_New(0);
651 if (temp == NULL)
652 return -1;
653 for (r = 0; r < j; r++) {
654 rr = PyList_GET_ITEM(right, r);
655 ok = PySequence_Contains(left, rr);
656 if (ok < 0) {
657 Py_DECREF(temp);
658 return -1;
659 }
660 if (!ok) {
661 ok = PyList_Append(temp, rr);
662 if (ok < 0) {
663 Py_DECREF(temp);
664 return -1;
665 }
666 }
667 }
668 ok = PyList_SetSlice(left, i, i, temp);
669 Py_DECREF(temp);
670 if (ok < 0)
671 return -1;
672 ok = PyList_SetSlice(right, 0, j+1, NULL);
673 if (ok < 0)
674 return -1;
675 goto again;
676 }
677 }
678 }
679 return PyList_SetSlice(left, left_size, left_size, right);
680}
681
682static int
683serious_order_disagreements(PyObject *left, PyObject *right)
684{
685 return 0; /* XXX later -- for now, we cheat: "don't do that" */
686}
687
Tim Petersa91e9642001-11-14 23:32:33 +0000688static int
689fill_classic_mro(PyObject *mro, PyObject *cls)
690{
691 PyObject *bases, *base;
692 int i, n;
693
694 assert(PyList_Check(mro));
695 assert(PyClass_Check(cls));
696 i = PySequence_Contains(mro, cls);
697 if (i < 0)
698 return -1;
699 if (!i) {
700 if (PyList_Append(mro, cls) < 0)
701 return -1;
702 }
703 bases = ((PyClassObject *)cls)->cl_bases;
704 assert(bases && PyTuple_Check(bases));
705 n = PyTuple_GET_SIZE(bases);
706 for (i = 0; i < n; i++) {
707 base = PyTuple_GET_ITEM(bases, i);
708 if (fill_classic_mro(mro, base) < 0)
709 return -1;
710 }
711 return 0;
712}
713
714static PyObject *
715classic_mro(PyObject *cls)
716{
717 PyObject *mro;
718
719 assert(PyClass_Check(cls));
720 mro = PyList_New(0);
721 if (mro != NULL) {
722 if (fill_classic_mro(mro, cls) == 0)
723 return mro;
724 Py_DECREF(mro);
725 }
726 return NULL;
727}
728
Tim Peters6d6c1a32001-08-02 04:15:00 +0000729static PyObject *
730mro_implementation(PyTypeObject *type)
731{
732 int i, n, ok;
733 PyObject *bases, *result;
734
Guido van Rossum63517572002-06-18 16:44:57 +0000735 if(type->tp_dict == NULL) {
736 if(PyType_Ready(type) < 0)
737 return NULL;
738 }
739
Tim Peters6d6c1a32001-08-02 04:15:00 +0000740 bases = type->tp_bases;
741 n = PyTuple_GET_SIZE(bases);
742 result = Py_BuildValue("[O]", (PyObject *)type);
743 if (result == NULL)
744 return NULL;
745 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000746 PyObject *base = PyTuple_GET_ITEM(bases, i);
747 PyObject *parentMRO;
748 if (PyType_Check(base))
749 parentMRO = PySequence_List(
750 ((PyTypeObject*)base)->tp_mro);
751 else
752 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000753 if (parentMRO == NULL) {
754 Py_DECREF(result);
755 return NULL;
756 }
757 if (serious_order_disagreements(result, parentMRO)) {
758 Py_DECREF(result);
759 return NULL;
760 }
761 ok = conservative_merge(result, parentMRO);
762 Py_DECREF(parentMRO);
763 if (ok < 0) {
764 Py_DECREF(result);
765 return NULL;
766 }
767 }
768 return result;
769}
770
771static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000772mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773{
774 PyTypeObject *type = (PyTypeObject *)self;
775
Tim Peters6d6c1a32001-08-02 04:15:00 +0000776 return mro_implementation(type);
777}
778
779static int
780mro_internal(PyTypeObject *type)
781{
782 PyObject *mro, *result, *tuple;
783
784 if (type->ob_type == &PyType_Type) {
785 result = mro_implementation(type);
786 }
787 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000788 static PyObject *mro_str;
789 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790 if (mro == NULL)
791 return -1;
792 result = PyObject_CallObject(mro, NULL);
793 Py_DECREF(mro);
794 }
795 if (result == NULL)
796 return -1;
797 tuple = PySequence_Tuple(result);
798 Py_DECREF(result);
799 type->tp_mro = tuple;
800 return 0;
801}
802
803
804/* Calculate the best base amongst multiple base classes.
805 This is the first one that's on the path to the "solid base". */
806
807static PyTypeObject *
808best_base(PyObject *bases)
809{
810 int i, n;
811 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000812 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000813
814 assert(PyTuple_Check(bases));
815 n = PyTuple_GET_SIZE(bases);
816 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000817 base = NULL;
818 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000820 base_proto = PyTuple_GET_ITEM(bases, i);
821 if (PyClass_Check(base_proto))
822 continue;
823 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 PyErr_SetString(
825 PyExc_TypeError,
826 "bases must be types");
827 return NULL;
828 }
Tim Petersa91e9642001-11-14 23:32:33 +0000829 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000831 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832 return NULL;
833 }
834 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000835 if (winner == NULL) {
836 winner = candidate;
837 base = base_i;
838 }
839 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840 ;
841 else if (PyType_IsSubtype(candidate, winner)) {
842 winner = candidate;
843 base = base_i;
844 }
845 else {
846 PyErr_SetString(
847 PyExc_TypeError,
848 "multiple bases have "
849 "instance lay-out conflict");
850 return NULL;
851 }
852 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000853 if (base == NULL)
854 PyErr_SetString(PyExc_TypeError,
855 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000856 return base;
857}
858
859static int
860extra_ivars(PyTypeObject *type, PyTypeObject *base)
861{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000862 size_t t_size = type->tp_basicsize;
863 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000864
Guido van Rossum9676b222001-08-17 20:32:36 +0000865 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866 if (type->tp_itemsize || base->tp_itemsize) {
867 /* If itemsize is involved, stricter rules */
868 return t_size != b_size ||
869 type->tp_itemsize != base->tp_itemsize;
870 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000871 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
872 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
873 t_size -= sizeof(PyObject *);
874 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
875 type->tp_dictoffset + sizeof(PyObject *) == t_size)
876 t_size -= sizeof(PyObject *);
877
878 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000879}
880
881static PyTypeObject *
882solid_base(PyTypeObject *type)
883{
884 PyTypeObject *base;
885
886 if (type->tp_base)
887 base = solid_base(type->tp_base);
888 else
889 base = &PyBaseObject_Type;
890 if (extra_ivars(type, base))
891 return type;
892 else
893 return base;
894}
895
896staticforward void object_dealloc(PyObject *);
897staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000898staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000899staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900
901static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000902subtype_dict(PyObject *obj, void *context)
903{
904 PyObject **dictptr = _PyObject_GetDictPtr(obj);
905 PyObject *dict;
906
907 if (dictptr == NULL) {
908 PyErr_SetString(PyExc_AttributeError,
909 "This object has no __dict__");
910 return NULL;
911 }
912 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000913 if (dict == NULL)
914 *dictptr = dict = PyDict_New();
915 Py_XINCREF(dict);
916 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000917}
918
Guido van Rossum6661be32001-10-26 04:26:12 +0000919static int
920subtype_setdict(PyObject *obj, PyObject *value, void *context)
921{
922 PyObject **dictptr = _PyObject_GetDictPtr(obj);
923 PyObject *dict;
924
925 if (dictptr == NULL) {
926 PyErr_SetString(PyExc_AttributeError,
927 "This object has no __dict__");
928 return -1;
929 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000930 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000931 PyErr_SetString(PyExc_TypeError,
932 "__dict__ must be set to a dictionary");
933 return -1;
934 }
935 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000936 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000937 *dictptr = value;
938 Py_XDECREF(dict);
939 return 0;
940}
941
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000942static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000943 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000944 {0},
945};
946
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000947/* bozo: __getstate__ that raises TypeError */
948
949static PyObject *
950bozo_func(PyObject *self, PyObject *args)
951{
952 PyErr_SetString(PyExc_TypeError,
953 "a class that defines __slots__ without "
954 "defining __getstate__ cannot be pickled");
955 return NULL;
956}
957
Neal Norwitz93c1e232002-03-31 16:06:11 +0000958static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000959
960static PyObject *bozo_obj = NULL;
961
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000962static int
963valid_identifier(PyObject *s)
964{
965 char *p;
966 int i, n;
967
968 if (!PyString_Check(s)) {
969 PyErr_SetString(PyExc_TypeError,
970 "__slots__ must be strings");
971 return 0;
972 }
973 p = PyString_AS_STRING(s);
974 n = PyString_GET_SIZE(s);
975 /* We must reject an empty name. As a hack, we bump the
976 length to 1 so that the loop will balk on the trailing \0. */
977 if (n == 0)
978 n = 1;
979 for (i = 0; i < n; i++, p++) {
980 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
981 PyErr_SetString(PyExc_TypeError,
982 "__slots__ must be identifiers");
983 return 0;
984 }
985 }
986 return 1;
987}
988
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000989static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000990type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
991{
992 PyObject *name, *bases, *dict;
993 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +0000994 static char buffer[256];
995 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000996 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000998 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000999 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000
Tim Peters3abca122001-10-27 19:37:48 +00001001 assert(args != NULL && PyTuple_Check(args));
1002 assert(kwds == NULL || PyDict_Check(kwds));
1003
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001004 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001005 {
1006 const int nargs = PyTuple_GET_SIZE(args);
1007 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1008
1009 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1010 PyObject *x = PyTuple_GET_ITEM(args, 0);
1011 Py_INCREF(x->ob_type);
1012 return (PyObject *) x->ob_type;
1013 }
1014
1015 /* SF bug 475327 -- if that didn't trigger, we need 3
1016 arguments. but PyArg_ParseTupleAndKeywords below may give
1017 a msg saying type() needs exactly 3. */
1018 if (nargs + nkwds != 3) {
1019 PyErr_SetString(PyExc_TypeError,
1020 "type() takes 1 or 3 arguments");
1021 return NULL;
1022 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001023 }
1024
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001025 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001026 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1027 &name,
1028 &PyTuple_Type, &bases,
1029 &PyDict_Type, &dict))
1030 return NULL;
1031
1032 /* Determine the proper metatype to deal with this,
1033 and check for metatype conflicts while we're at it.
1034 Note that if some other metatype wins to contract,
1035 it's possible that its instances are not types. */
1036 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001037 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038 for (i = 0; i < nbases; i++) {
1039 tmp = PyTuple_GET_ITEM(bases, i);
1040 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001041 if (tmptype == &PyClass_Type)
1042 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001043 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001044 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001045 if (PyType_IsSubtype(tmptype, winner)) {
1046 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047 continue;
1048 }
1049 PyErr_SetString(PyExc_TypeError,
1050 "metatype conflict among bases");
1051 return NULL;
1052 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001053 if (winner != metatype) {
1054 if (winner->tp_new != type_new) /* Pass it to the winner */
1055 return winner->tp_new(winner, args, kwds);
1056 metatype = winner;
1057 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001058
1059 /* Adjust for empty tuple bases */
1060 if (nbases == 0) {
1061 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1062 if (bases == NULL)
1063 return NULL;
1064 nbases = 1;
1065 }
1066 else
1067 Py_INCREF(bases);
1068
1069 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1070
1071 /* Calculate best base, and check that all bases are type objects */
1072 base = best_base(bases);
1073 if (base == NULL)
1074 return NULL;
1075 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1076 PyErr_Format(PyExc_TypeError,
1077 "type '%.100s' is not an acceptable base type",
1078 base->tp_name);
1079 return NULL;
1080 }
1081
Tim Peters6d6c1a32001-08-02 04:15:00 +00001082 /* Check for a __slots__ sequence variable in dict, and count it */
1083 slots = PyDict_GetItemString(dict, "__slots__");
1084 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001085 add_dict = 0;
1086 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 if (slots != NULL) {
1088 /* Make it into a tuple */
1089 if (PyString_Check(slots))
1090 slots = Py_BuildValue("(O)", slots);
1091 else
1092 slots = PySequence_Tuple(slots);
1093 if (slots == NULL)
1094 return NULL;
1095 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001096 if (nslots > 0 && base->tp_itemsize != 0) {
1097 PyErr_Format(PyExc_TypeError,
1098 "nonempty __slots__ "
1099 "not supported for subtype of '%s'",
1100 base->tp_name);
1101 return NULL;
1102 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001103 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001104 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001105 Py_DECREF(slots);
1106 return NULL;
1107 }
1108 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001109
1110 newslots = PyTuple_New(nslots);
1111 if (newslots == NULL)
1112 return NULL;
1113 for (i = 0; i < nslots; i++) {
1114 tmp = PyTuple_GET_ITEM(slots, i);
1115 if (_Py_Mangle(PyString_AS_STRING(name),
1116 PyString_AS_STRING(tmp),
1117 buffer, sizeof(buffer)))
1118 {
1119 tmp = PyString_FromString(buffer);
1120 } else {
1121 Py_INCREF(tmp);
1122 }
1123 PyTuple_SET_ITEM(newslots, i, tmp);
1124 }
1125 Py_DECREF(slots);
1126 slots = newslots;
1127
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001129 if (slots != NULL) {
1130 /* See if *this* class defines __getstate__ */
1131 PyObject *getstate = PyDict_GetItemString(dict,
1132 "__getstate__");
1133 if (getstate == NULL) {
1134 /* If not, provide a bozo that raises TypeError */
1135 if (bozo_obj == NULL) {
1136 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1137 if (bozo_obj == NULL) {
1138 /* XXX decref various things */
1139 return NULL;
1140 }
1141 }
1142 if (PyDict_SetItemString(dict,
1143 "__getstate__",
1144 bozo_obj) < 0) {
1145 /* XXX decref various things */
1146 return NULL;
1147 }
1148 }
1149 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150 if (slots == NULL && base->tp_dictoffset == 0 &&
1151 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001152 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001153 add_dict++;
1154 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001155 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1156 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001157 nslots++;
1158 add_weak++;
1159 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160
1161 /* XXX From here until type is safely allocated,
1162 "return NULL" may leak slots! */
1163
1164 /* Allocate the type object */
1165 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1166 if (type == NULL)
1167 return NULL;
1168
1169 /* Keep name and slots alive in the extended type object */
1170 et = (etype *)type;
1171 Py_INCREF(name);
1172 et->name = name;
1173 et->slots = slots;
1174
Guido van Rossumdc91b992001-08-08 22:26:22 +00001175 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1177 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001178 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1179 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001180
1181 /* It's a new-style number unless it specifically inherits any
1182 old-style numeric behavior */
1183 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1184 (base->tp_as_number == NULL))
1185 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1186
1187 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 type->tp_as_number = &et->as_number;
1189 type->tp_as_sequence = &et->as_sequence;
1190 type->tp_as_mapping = &et->as_mapping;
1191 type->tp_as_buffer = &et->as_buffer;
1192 type->tp_name = PyString_AS_STRING(name);
1193
1194 /* Set tp_base and tp_bases */
1195 type->tp_bases = bases;
1196 Py_INCREF(base);
1197 type->tp_base = base;
1198
Guido van Rossum687ae002001-10-15 22:03:32 +00001199 /* Initialize tp_dict from passed-in dict */
1200 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201 if (dict == NULL) {
1202 Py_DECREF(type);
1203 return NULL;
1204 }
1205
Guido van Rossumc3542212001-08-16 09:18:56 +00001206 /* Set __module__ in the dict */
1207 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1208 tmp = PyEval_GetGlobals();
1209 if (tmp != NULL) {
1210 tmp = PyDict_GetItemString(tmp, "__name__");
1211 if (tmp != NULL) {
1212 if (PyDict_SetItemString(dict, "__module__",
1213 tmp) < 0)
1214 return NULL;
1215 }
1216 }
1217 }
1218
Tim Peters2f93e282001-10-04 05:27:00 +00001219 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001220 and is a string. The __doc__ accessor will first look for tp_doc;
1221 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001222 */
1223 {
1224 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1225 if (doc != NULL && PyString_Check(doc)) {
1226 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001227 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001228 if (type->tp_doc == NULL) {
1229 Py_DECREF(type);
1230 return NULL;
1231 }
1232 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1233 }
1234 }
1235
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 /* Special-case __new__: if it's a plain function,
1237 make it a static function */
1238 tmp = PyDict_GetItemString(dict, "__new__");
1239 if (tmp != NULL && PyFunction_Check(tmp)) {
1240 tmp = PyStaticMethod_New(tmp);
1241 if (tmp == NULL) {
1242 Py_DECREF(type);
1243 return NULL;
1244 }
1245 PyDict_SetItemString(dict, "__new__", tmp);
1246 Py_DECREF(tmp);
1247 }
1248
1249 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1250 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001251 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 if (slots != NULL) {
1253 for (i = 0; i < nslots; i++, mp++) {
1254 mp->name = PyString_AS_STRING(
1255 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001256 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001258 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001259 strcmp(mp->name, "__weakref__") == 0) {
1260 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001261 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001262 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001263 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264 slotoffset += sizeof(PyObject *);
1265 }
1266 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001267 else {
1268 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001269 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001270 type->tp_dictoffset =
1271 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001272 else
1273 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001274 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001275 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001276 }
1277 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001278 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001279 type->tp_weaklistoffset = slotoffset;
1280 mp->name = "__weakref__";
1281 mp->type = T_OBJECT;
1282 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001283 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001284 mp++;
1285 slotoffset += sizeof(PyObject *);
1286 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001287 }
1288 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001289 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001290 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291
1292 /* Special case some slots */
1293 if (type->tp_dictoffset != 0 || nslots > 0) {
1294 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1295 type->tp_getattro = PyObject_GenericGetAttr;
1296 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1297 type->tp_setattro = PyObject_GenericSetAttr;
1298 }
1299 type->tp_dealloc = subtype_dealloc;
1300
Guido van Rossum9475a232001-10-05 20:51:39 +00001301 /* Enable GC unless there are really no instance variables possible */
1302 if (!(type->tp_basicsize == sizeof(PyObject) &&
1303 type->tp_itemsize == 0))
1304 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1305
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 /* Always override allocation strategy to use regular heap */
1307 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001308 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001309 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001310 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001311 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001312 }
1313 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001314 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315
1316 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001317 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318 Py_DECREF(type);
1319 return NULL;
1320 }
1321
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001322 /* Put the proper slots in place */
1323 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001324
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 return (PyObject *)type;
1326}
1327
1328/* Internal API to look for a name through the MRO.
1329 This returns a borrowed reference, and doesn't set an exception! */
1330PyObject *
1331_PyType_Lookup(PyTypeObject *type, PyObject *name)
1332{
1333 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001334 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335
Guido van Rossum687ae002001-10-15 22:03:32 +00001336 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001338
1339 /* If mro is NULL, the type is either not yet initialized
1340 by PyType_Ready(), or already cleared by type_clear().
1341 Either way the safest thing to do is to return NULL. */
1342 if (mro == NULL)
1343 return NULL;
1344
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345 assert(PyTuple_Check(mro));
1346 n = PyTuple_GET_SIZE(mro);
1347 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001348 base = PyTuple_GET_ITEM(mro, i);
1349 if (PyClass_Check(base))
1350 dict = ((PyClassObject *)base)->cl_dict;
1351 else {
1352 assert(PyType_Check(base));
1353 dict = ((PyTypeObject *)base)->tp_dict;
1354 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355 assert(dict && PyDict_Check(dict));
1356 res = PyDict_GetItem(dict, name);
1357 if (res != NULL)
1358 return res;
1359 }
1360 return NULL;
1361}
1362
1363/* This is similar to PyObject_GenericGetAttr(),
1364 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1365static PyObject *
1366type_getattro(PyTypeObject *type, PyObject *name)
1367{
1368 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001369 PyObject *meta_attribute, *attribute;
1370 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371
1372 /* Initialize this type (we'll assume the metatype is initialized) */
1373 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001374 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375 return NULL;
1376 }
1377
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001378 /* No readable descriptor found yet */
1379 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001380
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001381 /* Look for the attribute in the metatype */
1382 meta_attribute = _PyType_Lookup(metatype, name);
1383
1384 if (meta_attribute != NULL) {
1385 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001386
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001387 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1388 /* Data descriptors implement tp_descr_set to intercept
1389 * writes. Assume the attribute is not overridden in
1390 * type's tp_dict (and bases): call the descriptor now.
1391 */
1392 return meta_get(meta_attribute, (PyObject *)type,
1393 (PyObject *)metatype);
1394 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395 }
1396
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001397 /* No data descriptor found on metatype. Look in tp_dict of this
1398 * type and its bases */
1399 attribute = _PyType_Lookup(type, name);
1400 if (attribute != NULL) {
1401 /* Implement descriptor functionality, if any */
1402 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1403 if (local_get != NULL) {
1404 /* NULL 2nd argument indicates the descriptor was
1405 * found on the target object itself (or a base) */
1406 return local_get(attribute, (PyObject *)NULL,
1407 (PyObject *)type);
1408 }
Tim Peters34592512002-07-11 06:23:50 +00001409
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001410 Py_INCREF(attribute);
1411 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 }
1413
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001414 /* No attribute found in local __dict__ (or bases): use the
1415 * descriptor from the metatype, if any */
1416 if (meta_get != NULL)
1417 return meta_get(meta_attribute, (PyObject *)type,
1418 (PyObject *)metatype);
1419
1420 /* If an ordinary attribute was found on the metatype, return it now */
1421 if (meta_attribute != NULL) {
1422 Py_INCREF(meta_attribute);
1423 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424 }
1425
1426 /* Give up */
1427 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001428 "type object '%.50s' has no attribute '%.400s'",
1429 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001430 return NULL;
1431}
1432
1433static int
1434type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1435{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001436 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1437 PyErr_Format(
1438 PyExc_TypeError,
1439 "can't set attributes of built-in/extension type '%s'",
1440 type->tp_name);
1441 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001442 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001443 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1444 return -1;
1445 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446}
1447
1448static void
1449type_dealloc(PyTypeObject *type)
1450{
1451 etype *et;
1452
1453 /* Assert this is a heap-allocated type object */
1454 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001455 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001456 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001457 et = (etype *)type;
1458 Py_XDECREF(type->tp_base);
1459 Py_XDECREF(type->tp_dict);
1460 Py_XDECREF(type->tp_bases);
1461 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001462 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001463 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464 Py_XDECREF(et->name);
1465 Py_XDECREF(et->slots);
1466 type->ob_type->tp_free((PyObject *)type);
1467}
1468
Guido van Rossum1c450732001-10-08 15:18:27 +00001469static PyObject *
1470type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1471{
1472 PyObject *list, *raw, *ref;
1473 int i, n;
1474
1475 list = PyList_New(0);
1476 if (list == NULL)
1477 return NULL;
1478 raw = type->tp_subclasses;
1479 if (raw == NULL)
1480 return list;
1481 assert(PyList_Check(raw));
1482 n = PyList_GET_SIZE(raw);
1483 for (i = 0; i < n; i++) {
1484 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001485 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001486 ref = PyWeakref_GET_OBJECT(ref);
1487 if (ref != Py_None) {
1488 if (PyList_Append(list, ref) < 0) {
1489 Py_DECREF(list);
1490 return NULL;
1491 }
1492 }
1493 }
1494 return list;
1495}
1496
Tim Peters6d6c1a32001-08-02 04:15:00 +00001497static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001498 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001499 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001500 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1501 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502 {0}
1503};
1504
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001505PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001506"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001507"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508
Guido van Rossum048eb752001-10-02 21:24:57 +00001509static int
1510type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1511{
Guido van Rossum048eb752001-10-02 21:24:57 +00001512 int err;
1513
Guido van Rossuma3862092002-06-10 15:24:42 +00001514 /* Because of type_is_gc(), the collector only calls this
1515 for heaptypes. */
1516 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001517
1518#define VISIT(SLOT) \
1519 if (SLOT) { \
1520 err = visit((PyObject *)(SLOT), arg); \
1521 if (err) \
1522 return err; \
1523 }
1524
1525 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001526 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001527 VISIT(type->tp_mro);
1528 VISIT(type->tp_bases);
1529 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001530
1531 /* There's no need to visit type->tp_subclasses or
1532 ((etype *)type)->slots, because they can't be involved
1533 in cycles; tp_subclasses is a list of weak references,
1534 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001535
1536#undef VISIT
1537
1538 return 0;
1539}
1540
1541static int
1542type_clear(PyTypeObject *type)
1543{
Guido van Rossum048eb752001-10-02 21:24:57 +00001544 PyObject *tmp;
1545
Guido van Rossuma3862092002-06-10 15:24:42 +00001546 /* Because of type_is_gc(), the collector only calls this
1547 for heaptypes. */
1548 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001549
1550#define CLEAR(SLOT) \
1551 if (SLOT) { \
1552 tmp = (PyObject *)(SLOT); \
1553 SLOT = NULL; \
1554 Py_DECREF(tmp); \
1555 }
1556
Guido van Rossuma3862092002-06-10 15:24:42 +00001557 /* The only field we need to clear is tp_mro, which is part of a
1558 hard cycle (its first element is the class itself) that won't
1559 be broken otherwise (it's a tuple and tuples don't have a
1560 tp_clear handler). None of the other fields need to be
1561 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001562
Guido van Rossuma3862092002-06-10 15:24:42 +00001563 tp_dict:
1564 It is a dict, so the collector will call its tp_clear.
1565
1566 tp_cache:
1567 Not used; if it were, it would be a dict.
1568
1569 tp_bases, tp_base:
1570 If these are involved in a cycle, there must be at least
1571 one other, mutable object in the cycle, e.g. a base
1572 class's dict; the cycle will be broken that way.
1573
1574 tp_subclasses:
1575 A list of weak references can't be part of a cycle; and
1576 lists have their own tp_clear.
1577
1578 slots (in etype):
1579 A tuple of strings can't be part of a cycle.
1580 */
1581
1582 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001583
Guido van Rossum048eb752001-10-02 21:24:57 +00001584#undef CLEAR
1585
1586 return 0;
1587}
1588
1589static int
1590type_is_gc(PyTypeObject *type)
1591{
1592 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1593}
1594
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001595PyTypeObject PyType_Type = {
1596 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001597 0, /* ob_size */
1598 "type", /* tp_name */
1599 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001600 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601 (destructor)type_dealloc, /* tp_dealloc */
1602 0, /* tp_print */
1603 0, /* tp_getattr */
1604 0, /* tp_setattr */
1605 type_compare, /* tp_compare */
1606 (reprfunc)type_repr, /* tp_repr */
1607 0, /* tp_as_number */
1608 0, /* tp_as_sequence */
1609 0, /* tp_as_mapping */
1610 (hashfunc)_Py_HashPointer, /* tp_hash */
1611 (ternaryfunc)type_call, /* tp_call */
1612 0, /* tp_str */
1613 (getattrofunc)type_getattro, /* tp_getattro */
1614 (setattrofunc)type_setattro, /* tp_setattro */
1615 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001616 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1617 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001618 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001619 (traverseproc)type_traverse, /* tp_traverse */
1620 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001621 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001622 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623 0, /* tp_iter */
1624 0, /* tp_iternext */
1625 type_methods, /* tp_methods */
1626 type_members, /* tp_members */
1627 type_getsets, /* tp_getset */
1628 0, /* tp_base */
1629 0, /* tp_dict */
1630 0, /* tp_descr_get */
1631 0, /* tp_descr_set */
1632 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1633 0, /* tp_init */
1634 0, /* tp_alloc */
1635 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001636 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001637 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001638};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001639
1640
1641/* The base type of all types (eventually)... except itself. */
1642
1643static int
1644object_init(PyObject *self, PyObject *args, PyObject *kwds)
1645{
1646 return 0;
1647}
1648
1649static void
1650object_dealloc(PyObject *self)
1651{
1652 self->ob_type->tp_free(self);
1653}
1654
Guido van Rossum8e248182001-08-12 05:17:56 +00001655static PyObject *
1656object_repr(PyObject *self)
1657{
Guido van Rossum76e69632001-08-16 18:52:43 +00001658 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001659 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001660
Guido van Rossum76e69632001-08-16 18:52:43 +00001661 type = self->ob_type;
1662 mod = type_module(type, NULL);
1663 if (mod == NULL)
1664 PyErr_Clear();
1665 else if (!PyString_Check(mod)) {
1666 Py_DECREF(mod);
1667 mod = NULL;
1668 }
1669 name = type_name(type, NULL);
1670 if (name == NULL)
1671 return NULL;
1672 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001673 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001674 PyString_AS_STRING(mod),
1675 PyString_AS_STRING(name),
1676 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001677 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001678 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001679 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001680 Py_XDECREF(mod);
1681 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001682 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001683}
1684
Guido van Rossumb8f63662001-08-15 23:57:02 +00001685static PyObject *
1686object_str(PyObject *self)
1687{
1688 unaryfunc f;
1689
1690 f = self->ob_type->tp_repr;
1691 if (f == NULL)
1692 f = object_repr;
1693 return f(self);
1694}
1695
Guido van Rossum8e248182001-08-12 05:17:56 +00001696static long
1697object_hash(PyObject *self)
1698{
1699 return _Py_HashPointer(self);
1700}
Guido van Rossum8e248182001-08-12 05:17:56 +00001701
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001702static PyObject *
1703object_get_class(PyObject *self, void *closure)
1704{
1705 Py_INCREF(self->ob_type);
1706 return (PyObject *)(self->ob_type);
1707}
1708
1709static int
1710equiv_structs(PyTypeObject *a, PyTypeObject *b)
1711{
1712 return a == b ||
1713 (a != NULL &&
1714 b != NULL &&
1715 a->tp_basicsize == b->tp_basicsize &&
1716 a->tp_itemsize == b->tp_itemsize &&
1717 a->tp_dictoffset == b->tp_dictoffset &&
1718 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1719 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1720 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1721}
1722
1723static int
1724same_slots_added(PyTypeObject *a, PyTypeObject *b)
1725{
1726 PyTypeObject *base = a->tp_base;
1727 int size;
1728
1729 if (base != b->tp_base)
1730 return 0;
1731 if (equiv_structs(a, base) && equiv_structs(b, base))
1732 return 1;
1733 size = base->tp_basicsize;
1734 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1735 size += sizeof(PyObject *);
1736 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1737 size += sizeof(PyObject *);
1738 return size == a->tp_basicsize && size == b->tp_basicsize;
1739}
1740
1741static int
1742object_set_class(PyObject *self, PyObject *value, void *closure)
1743{
1744 PyTypeObject *old = self->ob_type;
1745 PyTypeObject *new, *newbase, *oldbase;
1746
Guido van Rossumb6b89422002-04-15 01:03:30 +00001747 if (value == NULL) {
1748 PyErr_SetString(PyExc_TypeError,
1749 "can't delete __class__ attribute");
1750 return -1;
1751 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001752 if (!PyType_Check(value)) {
1753 PyErr_Format(PyExc_TypeError,
1754 "__class__ must be set to new-style class, not '%s' object",
1755 value->ob_type->tp_name);
1756 return -1;
1757 }
1758 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001759 if (new->tp_dealloc != old->tp_dealloc ||
1760 new->tp_free != old->tp_free)
1761 {
1762 PyErr_Format(PyExc_TypeError,
1763 "__class__ assignment: "
1764 "'%s' deallocator differs from '%s'",
1765 new->tp_name,
1766 old->tp_name);
1767 return -1;
1768 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001769 newbase = new;
1770 oldbase = old;
1771 while (equiv_structs(newbase, newbase->tp_base))
1772 newbase = newbase->tp_base;
1773 while (equiv_structs(oldbase, oldbase->tp_base))
1774 oldbase = oldbase->tp_base;
1775 if (newbase != oldbase &&
1776 (newbase->tp_base != oldbase->tp_base ||
1777 !same_slots_added(newbase, oldbase))) {
1778 PyErr_Format(PyExc_TypeError,
1779 "__class__ assignment: "
1780 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001781 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001782 old->tp_name);
1783 return -1;
1784 }
1785 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1786 Py_INCREF(new);
1787 }
1788 self->ob_type = new;
1789 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1790 Py_DECREF(old);
1791 }
1792 return 0;
1793}
1794
1795static PyGetSetDef object_getsets[] = {
1796 {"__class__", object_get_class, object_set_class,
1797 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 {0}
1799};
1800
Guido van Rossum3926a632001-09-25 16:25:58 +00001801static PyObject *
1802object_reduce(PyObject *self, PyObject *args)
1803{
1804 /* Call copy_reg._reduce(self) */
1805 static PyObject *copy_reg_str;
1806 PyObject *copy_reg, *res;
1807
1808 if (!copy_reg_str) {
1809 copy_reg_str = PyString_InternFromString("copy_reg");
1810 if (copy_reg_str == NULL)
1811 return NULL;
1812 }
1813 copy_reg = PyImport_Import(copy_reg_str);
1814 if (!copy_reg)
1815 return NULL;
1816 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1817 Py_DECREF(copy_reg);
1818 return res;
1819}
1820
1821static PyMethodDef object_methods[] = {
1822 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1823 {0}
1824};
1825
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826PyTypeObject PyBaseObject_Type = {
1827 PyObject_HEAD_INIT(&PyType_Type)
1828 0, /* ob_size */
1829 "object", /* tp_name */
1830 sizeof(PyObject), /* tp_basicsize */
1831 0, /* tp_itemsize */
1832 (destructor)object_dealloc, /* tp_dealloc */
1833 0, /* tp_print */
1834 0, /* tp_getattr */
1835 0, /* tp_setattr */
1836 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001837 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 0, /* tp_as_number */
1839 0, /* tp_as_sequence */
1840 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001841 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001843 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001845 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846 0, /* tp_as_buffer */
1847 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1848 "The most base type", /* tp_doc */
1849 0, /* tp_traverse */
1850 0, /* tp_clear */
1851 0, /* tp_richcompare */
1852 0, /* tp_weaklistoffset */
1853 0, /* tp_iter */
1854 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001855 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001856 0, /* tp_members */
1857 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858 0, /* tp_base */
1859 0, /* tp_dict */
1860 0, /* tp_descr_get */
1861 0, /* tp_descr_set */
1862 0, /* tp_dictoffset */
1863 object_init, /* tp_init */
1864 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001865 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001866 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867};
1868
1869
1870/* Initialize the __dict__ in a type object */
1871
Fred Drake7bf97152002-03-28 05:33:33 +00001872static PyObject *
1873create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1874{
1875 PyObject *cfunc;
1876 PyObject *result;
1877
1878 cfunc = PyCFunction_New(meth, NULL);
1879 if (cfunc == NULL)
1880 return NULL;
1881 result = func(cfunc);
1882 Py_DECREF(cfunc);
1883 return result;
1884}
1885
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886static int
1887add_methods(PyTypeObject *type, PyMethodDef *meth)
1888{
Guido van Rossum687ae002001-10-15 22:03:32 +00001889 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001890
1891 for (; meth->ml_name != NULL; meth++) {
1892 PyObject *descr;
1893 if (PyDict_GetItemString(dict, meth->ml_name))
1894 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001895 if (meth->ml_flags & METH_CLASS) {
1896 if (meth->ml_flags & METH_STATIC) {
1897 PyErr_SetString(PyExc_ValueError,
1898 "method cannot be both class and static");
1899 return -1;
1900 }
1901 descr = create_specialmethod(meth, PyClassMethod_New);
1902 }
1903 else if (meth->ml_flags & METH_STATIC) {
1904 descr = create_specialmethod(meth, PyStaticMethod_New);
1905 }
1906 else {
1907 descr = PyDescr_NewMethod(type, meth);
1908 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909 if (descr == NULL)
1910 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001911 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912 return -1;
1913 Py_DECREF(descr);
1914 }
1915 return 0;
1916}
1917
1918static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001919add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920{
Guido van Rossum687ae002001-10-15 22:03:32 +00001921 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922
1923 for (; memb->name != NULL; memb++) {
1924 PyObject *descr;
1925 if (PyDict_GetItemString(dict, memb->name))
1926 continue;
1927 descr = PyDescr_NewMember(type, memb);
1928 if (descr == NULL)
1929 return -1;
1930 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1931 return -1;
1932 Py_DECREF(descr);
1933 }
1934 return 0;
1935}
1936
1937static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001938add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001939{
Guido van Rossum687ae002001-10-15 22:03:32 +00001940 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941
1942 for (; gsp->name != NULL; gsp++) {
1943 PyObject *descr;
1944 if (PyDict_GetItemString(dict, gsp->name))
1945 continue;
1946 descr = PyDescr_NewGetSet(type, gsp);
1947
1948 if (descr == NULL)
1949 return -1;
1950 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1951 return -1;
1952 Py_DECREF(descr);
1953 }
1954 return 0;
1955}
1956
Guido van Rossum13d52f02001-08-10 21:24:08 +00001957static void
1958inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959{
1960 int oldsize, newsize;
1961
Guido van Rossum13d52f02001-08-10 21:24:08 +00001962 /* Special flag magic */
1963 if (!type->tp_as_buffer && base->tp_as_buffer) {
1964 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1965 type->tp_flags |=
1966 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1967 }
1968 if (!type->tp_as_sequence && base->tp_as_sequence) {
1969 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1970 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1971 }
1972 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1973 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1974 if ((!type->tp_as_number && base->tp_as_number) ||
1975 (!type->tp_as_sequence && base->tp_as_sequence)) {
1976 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1977 if (!type->tp_as_number && !type->tp_as_sequence) {
1978 type->tp_flags |= base->tp_flags &
1979 Py_TPFLAGS_HAVE_INPLACEOPS;
1980 }
1981 }
1982 /* Wow */
1983 }
1984 if (!type->tp_as_number && base->tp_as_number) {
1985 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1986 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1987 }
1988
1989 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001990 oldsize = base->tp_basicsize;
1991 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1992 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1993 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001994 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1995 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001996 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001997 if (type->tp_traverse == NULL)
1998 type->tp_traverse = base->tp_traverse;
1999 if (type->tp_clear == NULL)
2000 type->tp_clear = base->tp_clear;
2001 }
2002 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002003 /* The condition below could use some explanation.
2004 It appears that tp_new is not inherited for static types
2005 whose base class is 'object'; this seems to be a precaution
2006 so that old extension types don't suddenly become
2007 callable (object.__new__ wouldn't insure the invariants
2008 that the extension type's own factory function ensures).
2009 Heap types, of course, are under our control, so they do
2010 inherit tp_new; static extension types that specify some
2011 other built-in type as the default are considered
2012 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002013 if (base != &PyBaseObject_Type ||
2014 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2015 if (type->tp_new == NULL)
2016 type->tp_new = base->tp_new;
2017 }
2018 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002019 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002020
2021 /* Copy other non-function slots */
2022
2023#undef COPYVAL
2024#define COPYVAL(SLOT) \
2025 if (type->SLOT == 0) type->SLOT = base->SLOT
2026
2027 COPYVAL(tp_itemsize);
2028 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2029 COPYVAL(tp_weaklistoffset);
2030 }
2031 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2032 COPYVAL(tp_dictoffset);
2033 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002034}
2035
2036static void
2037inherit_slots(PyTypeObject *type, PyTypeObject *base)
2038{
2039 PyTypeObject *basebase;
2040
2041#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042#undef COPYSLOT
2043#undef COPYNUM
2044#undef COPYSEQ
2045#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002046#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002047
2048#define SLOTDEFINED(SLOT) \
2049 (base->SLOT != 0 && \
2050 (basebase == NULL || base->SLOT != basebase->SLOT))
2051
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002053 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002054
2055#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2056#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2057#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002058#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002059
Guido van Rossum13d52f02001-08-10 21:24:08 +00002060 /* This won't inherit indirect slots (from tp_as_number etc.)
2061 if type doesn't provide the space. */
2062
2063 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2064 basebase = base->tp_base;
2065 if (basebase->tp_as_number == NULL)
2066 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 COPYNUM(nb_add);
2068 COPYNUM(nb_subtract);
2069 COPYNUM(nb_multiply);
2070 COPYNUM(nb_divide);
2071 COPYNUM(nb_remainder);
2072 COPYNUM(nb_divmod);
2073 COPYNUM(nb_power);
2074 COPYNUM(nb_negative);
2075 COPYNUM(nb_positive);
2076 COPYNUM(nb_absolute);
2077 COPYNUM(nb_nonzero);
2078 COPYNUM(nb_invert);
2079 COPYNUM(nb_lshift);
2080 COPYNUM(nb_rshift);
2081 COPYNUM(nb_and);
2082 COPYNUM(nb_xor);
2083 COPYNUM(nb_or);
2084 COPYNUM(nb_coerce);
2085 COPYNUM(nb_int);
2086 COPYNUM(nb_long);
2087 COPYNUM(nb_float);
2088 COPYNUM(nb_oct);
2089 COPYNUM(nb_hex);
2090 COPYNUM(nb_inplace_add);
2091 COPYNUM(nb_inplace_subtract);
2092 COPYNUM(nb_inplace_multiply);
2093 COPYNUM(nb_inplace_divide);
2094 COPYNUM(nb_inplace_remainder);
2095 COPYNUM(nb_inplace_power);
2096 COPYNUM(nb_inplace_lshift);
2097 COPYNUM(nb_inplace_rshift);
2098 COPYNUM(nb_inplace_and);
2099 COPYNUM(nb_inplace_xor);
2100 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002101 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2102 COPYNUM(nb_true_divide);
2103 COPYNUM(nb_floor_divide);
2104 COPYNUM(nb_inplace_true_divide);
2105 COPYNUM(nb_inplace_floor_divide);
2106 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 }
2108
Guido van Rossum13d52f02001-08-10 21:24:08 +00002109 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2110 basebase = base->tp_base;
2111 if (basebase->tp_as_sequence == NULL)
2112 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 COPYSEQ(sq_length);
2114 COPYSEQ(sq_concat);
2115 COPYSEQ(sq_repeat);
2116 COPYSEQ(sq_item);
2117 COPYSEQ(sq_slice);
2118 COPYSEQ(sq_ass_item);
2119 COPYSEQ(sq_ass_slice);
2120 COPYSEQ(sq_contains);
2121 COPYSEQ(sq_inplace_concat);
2122 COPYSEQ(sq_inplace_repeat);
2123 }
2124
Guido van Rossum13d52f02001-08-10 21:24:08 +00002125 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2126 basebase = base->tp_base;
2127 if (basebase->tp_as_mapping == NULL)
2128 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002129 COPYMAP(mp_length);
2130 COPYMAP(mp_subscript);
2131 COPYMAP(mp_ass_subscript);
2132 }
2133
Tim Petersfc57ccb2001-10-12 02:38:24 +00002134 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2135 basebase = base->tp_base;
2136 if (basebase->tp_as_buffer == NULL)
2137 basebase = NULL;
2138 COPYBUF(bf_getreadbuffer);
2139 COPYBUF(bf_getwritebuffer);
2140 COPYBUF(bf_getsegcount);
2141 COPYBUF(bf_getcharbuffer);
2142 }
2143
Guido van Rossum13d52f02001-08-10 21:24:08 +00002144 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002145
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146 COPYSLOT(tp_dealloc);
2147 COPYSLOT(tp_print);
2148 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2149 type->tp_getattr = base->tp_getattr;
2150 type->tp_getattro = base->tp_getattro;
2151 }
2152 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2153 type->tp_setattr = base->tp_setattr;
2154 type->tp_setattro = base->tp_setattro;
2155 }
2156 /* tp_compare see tp_richcompare */
2157 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002158 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002159 COPYSLOT(tp_call);
2160 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002162 if (type->tp_compare == NULL &&
2163 type->tp_richcompare == NULL &&
2164 type->tp_hash == NULL)
2165 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166 type->tp_compare = base->tp_compare;
2167 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002168 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002169 }
2170 }
2171 else {
2172 COPYSLOT(tp_compare);
2173 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002174 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2175 COPYSLOT(tp_iter);
2176 COPYSLOT(tp_iternext);
2177 }
2178 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2179 COPYSLOT(tp_descr_get);
2180 COPYSLOT(tp_descr_set);
2181 COPYSLOT(tp_dictoffset);
2182 COPYSLOT(tp_init);
2183 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002185 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187}
2188
Guido van Rossum13d52f02001-08-10 21:24:08 +00002189staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002190staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002191
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002193PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002194{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002195 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196 PyTypeObject *base;
2197 int i, n;
2198
Guido van Rossumcab05802002-06-10 15:29:03 +00002199 if (type->tp_flags & Py_TPFLAGS_READY) {
2200 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002201 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002202 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002203 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002204
2205 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002206
2207 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2208 base = type->tp_base;
2209 if (base == NULL && type != &PyBaseObject_Type)
2210 base = type->tp_base = &PyBaseObject_Type;
2211
Guido van Rossum0986d822002-04-08 01:38:42 +00002212 /* Initialize ob_type if NULL. This means extensions that want to be
2213 compilable separately on Windows can call PyType_Ready() instead of
2214 initializing the ob_type field of their type objects. */
2215 if (type->ob_type == NULL)
2216 type->ob_type = base->ob_type;
2217
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218 /* Initialize tp_bases */
2219 bases = type->tp_bases;
2220 if (bases == NULL) {
2221 if (base == NULL)
2222 bases = PyTuple_New(0);
2223 else
2224 bases = Py_BuildValue("(O)", base);
2225 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002226 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227 type->tp_bases = bases;
2228 }
2229
2230 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002231 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002232 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002233 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002234 }
2235
Guido van Rossum687ae002001-10-15 22:03:32 +00002236 /* Initialize tp_dict */
2237 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238 if (dict == NULL) {
2239 dict = PyDict_New();
2240 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002241 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002242 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002243 }
2244
Guido van Rossum687ae002001-10-15 22:03:32 +00002245 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002247 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002248 if (type->tp_methods != NULL) {
2249 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002250 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002251 }
2252 if (type->tp_members != NULL) {
2253 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002254 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002255 }
2256 if (type->tp_getset != NULL) {
2257 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002258 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259 }
2260
Tim Peters6d6c1a32001-08-02 04:15:00 +00002261 /* Calculate method resolution order */
2262 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002263 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002264 }
2265
Guido van Rossum13d52f02001-08-10 21:24:08 +00002266 /* Inherit special flags from dominant base */
2267 if (type->tp_base != NULL)
2268 inherit_special(type, type->tp_base);
2269
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002271 bases = type->tp_mro;
2272 assert(bases != NULL);
2273 assert(PyTuple_Check(bases));
2274 n = PyTuple_GET_SIZE(bases);
2275 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002276 PyObject *b = PyTuple_GET_ITEM(bases, i);
2277 if (PyType_Check(b))
2278 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002279 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002281 /* if the type dictionary doesn't contain a __doc__, set it from
2282 the tp_doc slot.
2283 */
2284 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2285 if (type->tp_doc != NULL) {
2286 PyObject *doc = PyString_FromString(type->tp_doc);
2287 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2288 Py_DECREF(doc);
2289 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002290 PyDict_SetItemString(type->tp_dict,
2291 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002292 }
2293 }
2294
Guido van Rossum13d52f02001-08-10 21:24:08 +00002295 /* Some more special stuff */
2296 base = type->tp_base;
2297 if (base != NULL) {
2298 if (type->tp_as_number == NULL)
2299 type->tp_as_number = base->tp_as_number;
2300 if (type->tp_as_sequence == NULL)
2301 type->tp_as_sequence = base->tp_as_sequence;
2302 if (type->tp_as_mapping == NULL)
2303 type->tp_as_mapping = base->tp_as_mapping;
2304 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305
Guido van Rossum1c450732001-10-08 15:18:27 +00002306 /* Link into each base class's list of subclasses */
2307 bases = type->tp_bases;
2308 n = PyTuple_GET_SIZE(bases);
2309 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002310 PyObject *b = PyTuple_GET_ITEM(bases, i);
2311 if (PyType_Check(b) &&
2312 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002313 goto error;
2314 }
2315
Guido van Rossum13d52f02001-08-10 21:24:08 +00002316 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002317 assert(type->tp_dict != NULL);
2318 type->tp_flags =
2319 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002321
2322 error:
2323 type->tp_flags &= ~Py_TPFLAGS_READYING;
2324 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002325}
2326
Guido van Rossum1c450732001-10-08 15:18:27 +00002327static int
2328add_subclass(PyTypeObject *base, PyTypeObject *type)
2329{
2330 int i;
2331 PyObject *list, *ref, *new;
2332
2333 list = base->tp_subclasses;
2334 if (list == NULL) {
2335 base->tp_subclasses = list = PyList_New(0);
2336 if (list == NULL)
2337 return -1;
2338 }
2339 assert(PyList_Check(list));
2340 new = PyWeakref_NewRef((PyObject *)type, NULL);
2341 i = PyList_GET_SIZE(list);
2342 while (--i >= 0) {
2343 ref = PyList_GET_ITEM(list, i);
2344 assert(PyWeakref_CheckRef(ref));
2345 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2346 return PyList_SetItem(list, i, new);
2347 }
2348 i = PyList_Append(list, new);
2349 Py_DECREF(new);
2350 return i;
2351}
2352
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353
2354/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2355
2356/* There's a wrapper *function* for each distinct function typedef used
2357 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2358 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2359 Most tables have only one entry; the tables for binary operators have two
2360 entries, one regular and one with reversed arguments. */
2361
2362static PyObject *
2363wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2364{
2365 inquiry func = (inquiry)wrapped;
2366 int res;
2367
2368 if (!PyArg_ParseTuple(args, ""))
2369 return NULL;
2370 res = (*func)(self);
2371 if (res == -1 && PyErr_Occurred())
2372 return NULL;
2373 return PyInt_FromLong((long)res);
2374}
2375
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376static PyObject *
2377wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2378{
2379 binaryfunc func = (binaryfunc)wrapped;
2380 PyObject *other;
2381
2382 if (!PyArg_ParseTuple(args, "O", &other))
2383 return NULL;
2384 return (*func)(self, other);
2385}
2386
2387static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002388wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2389{
2390 binaryfunc func = (binaryfunc)wrapped;
2391 PyObject *other;
2392
2393 if (!PyArg_ParseTuple(args, "O", &other))
2394 return NULL;
2395 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002396 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002397 Py_INCREF(Py_NotImplemented);
2398 return Py_NotImplemented;
2399 }
2400 return (*func)(self, other);
2401}
2402
2403static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2405{
2406 binaryfunc func = (binaryfunc)wrapped;
2407 PyObject *other;
2408
2409 if (!PyArg_ParseTuple(args, "O", &other))
2410 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002411 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002412 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002413 Py_INCREF(Py_NotImplemented);
2414 return Py_NotImplemented;
2415 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002416 return (*func)(other, self);
2417}
2418
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002419static PyObject *
2420wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2421{
2422 coercion func = (coercion)wrapped;
2423 PyObject *other, *res;
2424 int ok;
2425
2426 if (!PyArg_ParseTuple(args, "O", &other))
2427 return NULL;
2428 ok = func(&self, &other);
2429 if (ok < 0)
2430 return NULL;
2431 if (ok > 0) {
2432 Py_INCREF(Py_NotImplemented);
2433 return Py_NotImplemented;
2434 }
2435 res = PyTuple_New(2);
2436 if (res == NULL) {
2437 Py_DECREF(self);
2438 Py_DECREF(other);
2439 return NULL;
2440 }
2441 PyTuple_SET_ITEM(res, 0, self);
2442 PyTuple_SET_ITEM(res, 1, other);
2443 return res;
2444}
2445
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446static PyObject *
2447wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2448{
2449 ternaryfunc func = (ternaryfunc)wrapped;
2450 PyObject *other;
2451 PyObject *third = Py_None;
2452
2453 /* Note: This wrapper only works for __pow__() */
2454
2455 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2456 return NULL;
2457 return (*func)(self, other, third);
2458}
2459
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002460static PyObject *
2461wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2462{
2463 ternaryfunc func = (ternaryfunc)wrapped;
2464 PyObject *other;
2465 PyObject *third = Py_None;
2466
2467 /* Note: This wrapper only works for __pow__() */
2468
2469 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2470 return NULL;
2471 return (*func)(other, self, third);
2472}
2473
Tim Peters6d6c1a32001-08-02 04:15:00 +00002474static PyObject *
2475wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2476{
2477 unaryfunc func = (unaryfunc)wrapped;
2478
2479 if (!PyArg_ParseTuple(args, ""))
2480 return NULL;
2481 return (*func)(self);
2482}
2483
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484static PyObject *
2485wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2486{
2487 intargfunc func = (intargfunc)wrapped;
2488 int i;
2489
2490 if (!PyArg_ParseTuple(args, "i", &i))
2491 return NULL;
2492 return (*func)(self, i);
2493}
2494
Guido van Rossum5d815f32001-08-17 21:57:47 +00002495static int
2496getindex(PyObject *self, PyObject *arg)
2497{
2498 int i;
2499
2500 i = PyInt_AsLong(arg);
2501 if (i == -1 && PyErr_Occurred())
2502 return -1;
2503 if (i < 0) {
2504 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2505 if (sq && sq->sq_length) {
2506 int n = (*sq->sq_length)(self);
2507 if (n < 0)
2508 return -1;
2509 i += n;
2510 }
2511 }
2512 return i;
2513}
2514
2515static PyObject *
2516wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2517{
2518 intargfunc func = (intargfunc)wrapped;
2519 PyObject *arg;
2520 int i;
2521
Guido van Rossumf4593e02001-10-03 12:09:30 +00002522 if (PyTuple_GET_SIZE(args) == 1) {
2523 arg = PyTuple_GET_ITEM(args, 0);
2524 i = getindex(self, arg);
2525 if (i == -1 && PyErr_Occurred())
2526 return NULL;
2527 return (*func)(self, i);
2528 }
2529 PyArg_ParseTuple(args, "O", &arg);
2530 assert(PyErr_Occurred());
2531 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002532}
2533
Tim Peters6d6c1a32001-08-02 04:15:00 +00002534static PyObject *
2535wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2536{
2537 intintargfunc func = (intintargfunc)wrapped;
2538 int i, j;
2539
2540 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2541 return NULL;
2542 return (*func)(self, i, j);
2543}
2544
Tim Peters6d6c1a32001-08-02 04:15:00 +00002545static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002546wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002547{
2548 intobjargproc func = (intobjargproc)wrapped;
2549 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002550 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002551
Guido van Rossum5d815f32001-08-17 21:57:47 +00002552 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2553 return NULL;
2554 i = getindex(self, arg);
2555 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002556 return NULL;
2557 res = (*func)(self, i, value);
2558 if (res == -1 && PyErr_Occurred())
2559 return NULL;
2560 Py_INCREF(Py_None);
2561 return Py_None;
2562}
2563
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002564static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002565wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002566{
2567 intobjargproc func = (intobjargproc)wrapped;
2568 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002569 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002570
Guido van Rossum5d815f32001-08-17 21:57:47 +00002571 if (!PyArg_ParseTuple(args, "O", &arg))
2572 return NULL;
2573 i = getindex(self, arg);
2574 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002575 return NULL;
2576 res = (*func)(self, i, NULL);
2577 if (res == -1 && PyErr_Occurred())
2578 return NULL;
2579 Py_INCREF(Py_None);
2580 return Py_None;
2581}
2582
Tim Peters6d6c1a32001-08-02 04:15:00 +00002583static PyObject *
2584wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2585{
2586 intintobjargproc func = (intintobjargproc)wrapped;
2587 int i, j, res;
2588 PyObject *value;
2589
2590 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2591 return NULL;
2592 res = (*func)(self, i, j, value);
2593 if (res == -1 && PyErr_Occurred())
2594 return NULL;
2595 Py_INCREF(Py_None);
2596 return Py_None;
2597}
2598
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002599static PyObject *
2600wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2601{
2602 intintobjargproc func = (intintobjargproc)wrapped;
2603 int i, j, res;
2604
2605 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2606 return NULL;
2607 res = (*func)(self, i, j, NULL);
2608 if (res == -1 && PyErr_Occurred())
2609 return NULL;
2610 Py_INCREF(Py_None);
2611 return Py_None;
2612}
2613
Tim Peters6d6c1a32001-08-02 04:15:00 +00002614/* XXX objobjproc is a misnomer; should be objargpred */
2615static PyObject *
2616wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2617{
2618 objobjproc func = (objobjproc)wrapped;
2619 int res;
2620 PyObject *value;
2621
2622 if (!PyArg_ParseTuple(args, "O", &value))
2623 return NULL;
2624 res = (*func)(self, value);
2625 if (res == -1 && PyErr_Occurred())
2626 return NULL;
2627 return PyInt_FromLong((long)res);
2628}
2629
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630static PyObject *
2631wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2632{
2633 objobjargproc func = (objobjargproc)wrapped;
2634 int res;
2635 PyObject *key, *value;
2636
2637 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2638 return NULL;
2639 res = (*func)(self, key, value);
2640 if (res == -1 && PyErr_Occurred())
2641 return NULL;
2642 Py_INCREF(Py_None);
2643 return Py_None;
2644}
2645
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002646static PyObject *
2647wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2648{
2649 objobjargproc func = (objobjargproc)wrapped;
2650 int res;
2651 PyObject *key;
2652
2653 if (!PyArg_ParseTuple(args, "O", &key))
2654 return NULL;
2655 res = (*func)(self, key, NULL);
2656 if (res == -1 && PyErr_Occurred())
2657 return NULL;
2658 Py_INCREF(Py_None);
2659 return Py_None;
2660}
2661
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662static PyObject *
2663wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2664{
2665 cmpfunc func = (cmpfunc)wrapped;
2666 int res;
2667 PyObject *other;
2668
2669 if (!PyArg_ParseTuple(args, "O", &other))
2670 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002671 if (other->ob_type->tp_compare != func &&
2672 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002673 PyErr_Format(
2674 PyExc_TypeError,
2675 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2676 self->ob_type->tp_name,
2677 self->ob_type->tp_name,
2678 other->ob_type->tp_name);
2679 return NULL;
2680 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002681 res = (*func)(self, other);
2682 if (PyErr_Occurred())
2683 return NULL;
2684 return PyInt_FromLong((long)res);
2685}
2686
Tim Peters6d6c1a32001-08-02 04:15:00 +00002687static PyObject *
2688wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2689{
2690 setattrofunc func = (setattrofunc)wrapped;
2691 int res;
2692 PyObject *name, *value;
2693
2694 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2695 return NULL;
2696 res = (*func)(self, name, value);
2697 if (res < 0)
2698 return NULL;
2699 Py_INCREF(Py_None);
2700 return Py_None;
2701}
2702
2703static PyObject *
2704wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2705{
2706 setattrofunc func = (setattrofunc)wrapped;
2707 int res;
2708 PyObject *name;
2709
2710 if (!PyArg_ParseTuple(args, "O", &name))
2711 return NULL;
2712 res = (*func)(self, name, NULL);
2713 if (res < 0)
2714 return NULL;
2715 Py_INCREF(Py_None);
2716 return Py_None;
2717}
2718
Tim Peters6d6c1a32001-08-02 04:15:00 +00002719static PyObject *
2720wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2721{
2722 hashfunc func = (hashfunc)wrapped;
2723 long res;
2724
2725 if (!PyArg_ParseTuple(args, ""))
2726 return NULL;
2727 res = (*func)(self);
2728 if (res == -1 && PyErr_Occurred())
2729 return NULL;
2730 return PyInt_FromLong(res);
2731}
2732
Tim Peters6d6c1a32001-08-02 04:15:00 +00002733static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002734wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735{
2736 ternaryfunc func = (ternaryfunc)wrapped;
2737
Guido van Rossumc8e56452001-10-22 00:43:43 +00002738 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002739}
2740
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741static PyObject *
2742wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2743{
2744 richcmpfunc func = (richcmpfunc)wrapped;
2745 PyObject *other;
2746
2747 if (!PyArg_ParseTuple(args, "O", &other))
2748 return NULL;
2749 return (*func)(self, other, op);
2750}
2751
2752#undef RICHCMP_WRAPPER
2753#define RICHCMP_WRAPPER(NAME, OP) \
2754static PyObject * \
2755richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2756{ \
2757 return wrap_richcmpfunc(self, args, wrapped, OP); \
2758}
2759
Jack Jansen8e938b42001-08-08 15:29:49 +00002760RICHCMP_WRAPPER(lt, Py_LT)
2761RICHCMP_WRAPPER(le, Py_LE)
2762RICHCMP_WRAPPER(eq, Py_EQ)
2763RICHCMP_WRAPPER(ne, Py_NE)
2764RICHCMP_WRAPPER(gt, Py_GT)
2765RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767static PyObject *
2768wrap_next(PyObject *self, PyObject *args, void *wrapped)
2769{
2770 unaryfunc func = (unaryfunc)wrapped;
2771 PyObject *res;
2772
2773 if (!PyArg_ParseTuple(args, ""))
2774 return NULL;
2775 res = (*func)(self);
2776 if (res == NULL && !PyErr_Occurred())
2777 PyErr_SetNone(PyExc_StopIteration);
2778 return res;
2779}
2780
Tim Peters6d6c1a32001-08-02 04:15:00 +00002781static PyObject *
2782wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2783{
2784 descrgetfunc func = (descrgetfunc)wrapped;
2785 PyObject *obj;
2786 PyObject *type = NULL;
2787
2788 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2789 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002790 return (*func)(self, obj, type);
2791}
2792
Tim Peters6d6c1a32001-08-02 04:15:00 +00002793static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002794wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002795{
2796 descrsetfunc func = (descrsetfunc)wrapped;
2797 PyObject *obj, *value;
2798 int ret;
2799
2800 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2801 return NULL;
2802 ret = (*func)(self, obj, value);
2803 if (ret < 0)
2804 return NULL;
2805 Py_INCREF(Py_None);
2806 return Py_None;
2807}
2808
Tim Peters6d6c1a32001-08-02 04:15:00 +00002809static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002810wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002811{
2812 initproc func = (initproc)wrapped;
2813
Guido van Rossumc8e56452001-10-22 00:43:43 +00002814 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002815 return NULL;
2816 Py_INCREF(Py_None);
2817 return Py_None;
2818}
2819
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002821tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822{
Barry Warsaw60f01882001-08-22 19:24:42 +00002823 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002824 PyObject *arg0, *res;
2825
2826 if (self == NULL || !PyType_Check(self))
2827 Py_FatalError("__new__() called with non-type 'self'");
2828 type = (PyTypeObject *)self;
2829 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002830 PyErr_Format(PyExc_TypeError,
2831 "%s.__new__(): not enough arguments",
2832 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002833 return NULL;
2834 }
2835 arg0 = PyTuple_GET_ITEM(args, 0);
2836 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002837 PyErr_Format(PyExc_TypeError,
2838 "%s.__new__(X): X is not a type object (%s)",
2839 type->tp_name,
2840 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002841 return NULL;
2842 }
2843 subtype = (PyTypeObject *)arg0;
2844 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002845 PyErr_Format(PyExc_TypeError,
2846 "%s.__new__(%s): %s is not a subtype of %s",
2847 type->tp_name,
2848 subtype->tp_name,
2849 subtype->tp_name,
2850 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002851 return NULL;
2852 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002853
2854 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002855 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002856 most derived base that's not a heap type is this type. */
2857 staticbase = subtype;
2858 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2859 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002860 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002861 PyErr_Format(PyExc_TypeError,
2862 "%s.__new__(%s) is not safe, use %s.__new__()",
2863 type->tp_name,
2864 subtype->tp_name,
2865 staticbase == NULL ? "?" : staticbase->tp_name);
2866 return NULL;
2867 }
2868
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002869 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2870 if (args == NULL)
2871 return NULL;
2872 res = type->tp_new(subtype, args, kwds);
2873 Py_DECREF(args);
2874 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002875}
2876
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002877static struct PyMethodDef tp_new_methoddef[] = {
2878 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2879 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002880 {0}
2881};
2882
2883static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002884add_tp_new_wrapper(PyTypeObject *type)
2885{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002886 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002887
Guido van Rossum687ae002001-10-15 22:03:32 +00002888 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002889 return 0;
2890 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002891 if (func == NULL)
2892 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002893 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002894}
2895
Guido van Rossumf040ede2001-08-07 16:40:56 +00002896/* Slot wrappers that call the corresponding __foo__ slot. See comments
2897 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898
Guido van Rossumdc91b992001-08-08 22:26:22 +00002899#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002901FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002903 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002904 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002905}
2906
Guido van Rossumdc91b992001-08-08 22:26:22 +00002907#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002909FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002911 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002912 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002913}
2914
Guido van Rossumdc91b992001-08-08 22:26:22 +00002915
2916#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002918FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002919{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002920 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002921 int do_other = self->ob_type != other->ob_type && \
2922 other->ob_type->tp_as_number != NULL && \
2923 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002924 if (self->ob_type->tp_as_number != NULL && \
2925 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2926 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002927 if (do_other && \
2928 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2929 r = call_maybe( \
2930 other, ROPSTR, &rcache_str, "(O)", self); \
2931 if (r != Py_NotImplemented) \
2932 return r; \
2933 Py_DECREF(r); \
2934 do_other = 0; \
2935 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002936 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002937 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002938 if (r != Py_NotImplemented || \
2939 other->ob_type == self->ob_type) \
2940 return r; \
2941 Py_DECREF(r); \
2942 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002943 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002944 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002945 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002946 } \
2947 Py_INCREF(Py_NotImplemented); \
2948 return Py_NotImplemented; \
2949}
2950
2951#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2952 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2953
2954#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2955static PyObject * \
2956FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2957{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002958 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002959 return call_method(self, OPSTR, &cache_str, \
2960 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961}
2962
2963static int
2964slot_sq_length(PyObject *self)
2965{
Guido van Rossum2730b132001-08-28 18:22:14 +00002966 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002967 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002968 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969
2970 if (res == NULL)
2971 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002972 len = (int)PyInt_AsLong(res);
2973 Py_DECREF(res);
2974 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002975}
2976
Guido van Rossumdc91b992001-08-08 22:26:22 +00002977SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2978SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002979
2980/* Super-optimized version of slot_sq_item.
2981 Other slots could do the same... */
2982static PyObject *
2983slot_sq_item(PyObject *self, int i)
2984{
2985 static PyObject *getitem_str;
2986 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2987 descrgetfunc f;
2988
2989 if (getitem_str == NULL) {
2990 getitem_str = PyString_InternFromString("__getitem__");
2991 if (getitem_str == NULL)
2992 return NULL;
2993 }
2994 func = _PyType_Lookup(self->ob_type, getitem_str);
2995 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002996 if ((f = func->ob_type->tp_descr_get) == NULL)
2997 Py_INCREF(func);
2998 else
2999 func = f(func, self, (PyObject *)(self->ob_type));
3000 ival = PyInt_FromLong(i);
3001 if (ival != NULL) {
3002 args = PyTuple_New(1);
3003 if (args != NULL) {
3004 PyTuple_SET_ITEM(args, 0, ival);
3005 retval = PyObject_Call(func, args, NULL);
3006 Py_XDECREF(args);
3007 Py_XDECREF(func);
3008 return retval;
3009 }
3010 }
3011 }
3012 else {
3013 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3014 }
3015 Py_XDECREF(args);
3016 Py_XDECREF(ival);
3017 Py_XDECREF(func);
3018 return NULL;
3019}
3020
Guido van Rossumdc91b992001-08-08 22:26:22 +00003021SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003022
3023static int
3024slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3025{
3026 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003027 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028
3029 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003030 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003031 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003033 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003034 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 if (res == NULL)
3036 return -1;
3037 Py_DECREF(res);
3038 return 0;
3039}
3040
3041static int
3042slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3043{
3044 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003045 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046
3047 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003048 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003049 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003051 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003052 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053 if (res == NULL)
3054 return -1;
3055 Py_DECREF(res);
3056 return 0;
3057}
3058
3059static int
3060slot_sq_contains(PyObject *self, PyObject *value)
3061{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003062 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003063 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064
Guido van Rossum55f20992001-10-01 17:18:22 +00003065 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003066
3067 if (func != NULL) {
3068 args = Py_BuildValue("(O)", value);
3069 if (args == NULL)
3070 res = NULL;
3071 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003072 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003073 Py_DECREF(args);
3074 }
3075 Py_DECREF(func);
3076 if (res == NULL)
3077 return -1;
3078 return PyObject_IsTrue(res);
3079 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003080 else if (PyErr_Occurred())
3081 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003082 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003083 return _PySequence_IterSearch(self, value,
3084 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003085 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086}
3087
Guido van Rossumdc91b992001-08-08 22:26:22 +00003088SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3089SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003090
3091#define slot_mp_length slot_sq_length
3092
Guido van Rossumdc91b992001-08-08 22:26:22 +00003093SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094
3095static int
3096slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3097{
3098 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003099 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003100
3101 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003102 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003103 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003105 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003106 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107 if (res == NULL)
3108 return -1;
3109 Py_DECREF(res);
3110 return 0;
3111}
3112
Guido van Rossumdc91b992001-08-08 22:26:22 +00003113SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3114SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3115SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3116SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3117SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3118SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3119
3120staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3121
3122SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3123 nb_power, "__pow__", "__rpow__")
3124
3125static PyObject *
3126slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3127{
Guido van Rossum2730b132001-08-28 18:22:14 +00003128 static PyObject *pow_str;
3129
Guido van Rossumdc91b992001-08-08 22:26:22 +00003130 if (modulus == Py_None)
3131 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003132 /* Three-arg power doesn't use __rpow__. But ternary_op
3133 can call this when the second argument's type uses
3134 slot_nb_power, so check before calling self.__pow__. */
3135 if (self->ob_type->tp_as_number != NULL &&
3136 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3137 return call_method(self, "__pow__", &pow_str,
3138 "(OO)", other, modulus);
3139 }
3140 Py_INCREF(Py_NotImplemented);
3141 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003142}
3143
3144SLOT0(slot_nb_negative, "__neg__")
3145SLOT0(slot_nb_positive, "__pos__")
3146SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147
3148static int
3149slot_nb_nonzero(PyObject *self)
3150{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003151 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003152 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153
Guido van Rossum55f20992001-10-01 17:18:22 +00003154 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003155 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003156 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003157 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003158 func = lookup_maybe(self, "__len__", &len_str);
3159 if (func == NULL) {
3160 if (PyErr_Occurred())
3161 return -1;
3162 else
3163 return 1;
3164 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003165 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003166 res = PyObject_CallObject(func, NULL);
3167 Py_DECREF(func);
3168 if (res == NULL)
3169 return -1;
3170 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171}
3172
Guido van Rossumdc91b992001-08-08 22:26:22 +00003173SLOT0(slot_nb_invert, "__invert__")
3174SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3175SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3176SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3177SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3178SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003179
3180static int
3181slot_nb_coerce(PyObject **a, PyObject **b)
3182{
3183 static PyObject *coerce_str;
3184 PyObject *self = *a, *other = *b;
3185
3186 if (self->ob_type->tp_as_number != NULL &&
3187 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3188 PyObject *r;
3189 r = call_maybe(
3190 self, "__coerce__", &coerce_str, "(O)", other);
3191 if (r == NULL)
3192 return -1;
3193 if (r == Py_NotImplemented) {
3194 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003195 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003196 else {
3197 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3198 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003199 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003200 Py_DECREF(r);
3201 return -1;
3202 }
3203 *a = PyTuple_GET_ITEM(r, 0);
3204 Py_INCREF(*a);
3205 *b = PyTuple_GET_ITEM(r, 1);
3206 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003207 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003208 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003209 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003210 }
3211 if (other->ob_type->tp_as_number != NULL &&
3212 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3213 PyObject *r;
3214 r = call_maybe(
3215 other, "__coerce__", &coerce_str, "(O)", self);
3216 if (r == NULL)
3217 return -1;
3218 if (r == Py_NotImplemented) {
3219 Py_DECREF(r);
3220 return 1;
3221 }
3222 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3223 PyErr_SetString(PyExc_TypeError,
3224 "__coerce__ didn't return a 2-tuple");
3225 Py_DECREF(r);
3226 return -1;
3227 }
3228 *a = PyTuple_GET_ITEM(r, 1);
3229 Py_INCREF(*a);
3230 *b = PyTuple_GET_ITEM(r, 0);
3231 Py_INCREF(*b);
3232 Py_DECREF(r);
3233 return 0;
3234 }
3235 return 1;
3236}
3237
Guido van Rossumdc91b992001-08-08 22:26:22 +00003238SLOT0(slot_nb_int, "__int__")
3239SLOT0(slot_nb_long, "__long__")
3240SLOT0(slot_nb_float, "__float__")
3241SLOT0(slot_nb_oct, "__oct__")
3242SLOT0(slot_nb_hex, "__hex__")
3243SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3244SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3245SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3246SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3247SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3248SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3249SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3250SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3251SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3252SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3253SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3254SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3255 "__floordiv__", "__rfloordiv__")
3256SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3257SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3258SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003259
3260static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003261half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003263 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003264 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003265 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003266
Guido van Rossum60718732001-08-28 17:47:51 +00003267 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003268 if (func == NULL) {
3269 PyErr_Clear();
3270 }
3271 else {
3272 args = Py_BuildValue("(O)", other);
3273 if (args == NULL)
3274 res = NULL;
3275 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003276 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003277 Py_DECREF(args);
3278 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003279 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003280 if (res != Py_NotImplemented) {
3281 if (res == NULL)
3282 return -2;
3283 c = PyInt_AsLong(res);
3284 Py_DECREF(res);
3285 if (c == -1 && PyErr_Occurred())
3286 return -2;
3287 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3288 }
3289 Py_DECREF(res);
3290 }
3291 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003292}
3293
Guido van Rossumab3b0342001-09-18 20:38:53 +00003294/* This slot is published for the benefit of try_3way_compare in object.c */
3295int
3296_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003297{
3298 int c;
3299
Guido van Rossumab3b0342001-09-18 20:38:53 +00003300 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003301 c = half_compare(self, other);
3302 if (c <= 1)
3303 return c;
3304 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003305 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003306 c = half_compare(other, self);
3307 if (c < -1)
3308 return -2;
3309 if (c <= 1)
3310 return -c;
3311 }
3312 return (void *)self < (void *)other ? -1 :
3313 (void *)self > (void *)other ? 1 : 0;
3314}
3315
3316static PyObject *
3317slot_tp_repr(PyObject *self)
3318{
3319 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003320 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003321
Guido van Rossum60718732001-08-28 17:47:51 +00003322 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003323 if (func != NULL) {
3324 res = PyEval_CallObject(func, NULL);
3325 Py_DECREF(func);
3326 return res;
3327 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003328 PyErr_Clear();
3329 return PyString_FromFormat("<%s object at %p>",
3330 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003331}
3332
3333static PyObject *
3334slot_tp_str(PyObject *self)
3335{
3336 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003337 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003338
Guido van Rossum60718732001-08-28 17:47:51 +00003339 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003340 if (func != NULL) {
3341 res = PyEval_CallObject(func, NULL);
3342 Py_DECREF(func);
3343 return res;
3344 }
3345 else {
3346 PyErr_Clear();
3347 return slot_tp_repr(self);
3348 }
3349}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003350
3351static long
3352slot_tp_hash(PyObject *self)
3353{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003354 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003355 static PyObject *hash_str, *eq_str, *cmp_str;
3356
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357 long h;
3358
Guido van Rossum60718732001-08-28 17:47:51 +00003359 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003360
3361 if (func != NULL) {
3362 res = PyEval_CallObject(func, NULL);
3363 Py_DECREF(func);
3364 if (res == NULL)
3365 return -1;
3366 h = PyInt_AsLong(res);
3367 }
3368 else {
3369 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003370 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003371 if (func == NULL) {
3372 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003373 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003374 }
3375 if (func != NULL) {
3376 Py_DECREF(func);
3377 PyErr_SetString(PyExc_TypeError, "unhashable type");
3378 return -1;
3379 }
3380 PyErr_Clear();
3381 h = _Py_HashPointer((void *)self);
3382 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383 if (h == -1 && !PyErr_Occurred())
3384 h = -2;
3385 return h;
3386}
3387
3388static PyObject *
3389slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3390{
Guido van Rossum60718732001-08-28 17:47:51 +00003391 static PyObject *call_str;
3392 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393 PyObject *res;
3394
3395 if (meth == NULL)
3396 return NULL;
3397 res = PyObject_Call(meth, args, kwds);
3398 Py_DECREF(meth);
3399 return res;
3400}
3401
Guido van Rossum14a6f832001-10-17 13:59:09 +00003402/* There are two slot dispatch functions for tp_getattro.
3403
3404 - slot_tp_getattro() is used when __getattribute__ is overridden
3405 but no __getattr__ hook is present;
3406
3407 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3408
Guido van Rossumc334df52002-04-04 23:44:47 +00003409 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3410 detects the absence of __getattr__ and then installs the simpler slot if
3411 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003412
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413static PyObject *
3414slot_tp_getattro(PyObject *self, PyObject *name)
3415{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003416 static PyObject *getattribute_str = NULL;
3417 return call_method(self, "__getattribute__", &getattribute_str,
3418 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419}
3420
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003421static PyObject *
3422slot_tp_getattr_hook(PyObject *self, PyObject *name)
3423{
3424 PyTypeObject *tp = self->ob_type;
3425 PyObject *getattr, *getattribute, *res;
3426 static PyObject *getattribute_str = NULL;
3427 static PyObject *getattr_str = NULL;
3428
3429 if (getattr_str == NULL) {
3430 getattr_str = PyString_InternFromString("__getattr__");
3431 if (getattr_str == NULL)
3432 return NULL;
3433 }
3434 if (getattribute_str == NULL) {
3435 getattribute_str =
3436 PyString_InternFromString("__getattribute__");
3437 if (getattribute_str == NULL)
3438 return NULL;
3439 }
3440 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003441 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003442 /* No __getattr__ hook: use a simpler dispatcher */
3443 tp->tp_getattro = slot_tp_getattro;
3444 return slot_tp_getattro(self, name);
3445 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003446 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003447 if (getattribute == NULL ||
3448 (getattribute->ob_type == &PyWrapperDescr_Type &&
3449 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3450 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003451 res = PyObject_GenericGetAttr(self, name);
3452 else
3453 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003454 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003455 PyErr_Clear();
3456 res = PyObject_CallFunction(getattr, "OO", self, name);
3457 }
3458 return res;
3459}
3460
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461static int
3462slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3463{
3464 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003465 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003466
3467 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003468 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003469 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003471 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003472 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473 if (res == NULL)
3474 return -1;
3475 Py_DECREF(res);
3476 return 0;
3477}
3478
3479/* Map rich comparison operators to their __xx__ namesakes */
3480static char *name_op[] = {
3481 "__lt__",
3482 "__le__",
3483 "__eq__",
3484 "__ne__",
3485 "__gt__",
3486 "__ge__",
3487};
3488
3489static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003490half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003491{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003492 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003493 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494
Guido van Rossum60718732001-08-28 17:47:51 +00003495 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003496 if (func == NULL) {
3497 PyErr_Clear();
3498 Py_INCREF(Py_NotImplemented);
3499 return Py_NotImplemented;
3500 }
3501 args = Py_BuildValue("(O)", other);
3502 if (args == NULL)
3503 res = NULL;
3504 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003505 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003506 Py_DECREF(args);
3507 }
3508 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509 return res;
3510}
3511
Guido van Rossumb8f63662001-08-15 23:57:02 +00003512/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3513static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3514
3515static PyObject *
3516slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3517{
3518 PyObject *res;
3519
3520 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3521 res = half_richcompare(self, other, op);
3522 if (res != Py_NotImplemented)
3523 return res;
3524 Py_DECREF(res);
3525 }
3526 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3527 res = half_richcompare(other, self, swapped_op[op]);
3528 if (res != Py_NotImplemented) {
3529 return res;
3530 }
3531 Py_DECREF(res);
3532 }
3533 Py_INCREF(Py_NotImplemented);
3534 return Py_NotImplemented;
3535}
3536
3537static PyObject *
3538slot_tp_iter(PyObject *self)
3539{
3540 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003541 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003542
Guido van Rossum60718732001-08-28 17:47:51 +00003543 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003544 if (func != NULL) {
3545 res = PyObject_CallObject(func, NULL);
3546 Py_DECREF(func);
3547 return res;
3548 }
3549 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003550 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003551 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003552 PyErr_SetString(PyExc_TypeError,
3553 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003554 return NULL;
3555 }
3556 Py_DECREF(func);
3557 return PySeqIter_New(self);
3558}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003559
3560static PyObject *
3561slot_tp_iternext(PyObject *self)
3562{
Guido van Rossum2730b132001-08-28 18:22:14 +00003563 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003564 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003565}
3566
Guido van Rossum1a493502001-08-17 16:47:50 +00003567static PyObject *
3568slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3569{
3570 PyTypeObject *tp = self->ob_type;
3571 PyObject *get;
3572 static PyObject *get_str = NULL;
3573
3574 if (get_str == NULL) {
3575 get_str = PyString_InternFromString("__get__");
3576 if (get_str == NULL)
3577 return NULL;
3578 }
3579 get = _PyType_Lookup(tp, get_str);
3580 if (get == NULL) {
3581 /* Avoid further slowdowns */
3582 if (tp->tp_descr_get == slot_tp_descr_get)
3583 tp->tp_descr_get = NULL;
3584 Py_INCREF(self);
3585 return self;
3586 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003587 if (obj == NULL)
3588 obj = Py_None;
3589 if (type == NULL)
3590 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003591 return PyObject_CallFunction(get, "OOO", self, obj, type);
3592}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593
3594static int
3595slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3596{
Guido van Rossum2c252392001-08-24 10:13:31 +00003597 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003598 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003599
3600 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003601 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003602 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003603 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003604 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003605 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606 if (res == NULL)
3607 return -1;
3608 Py_DECREF(res);
3609 return 0;
3610}
3611
3612static int
3613slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3614{
Guido van Rossum60718732001-08-28 17:47:51 +00003615 static PyObject *init_str;
3616 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617 PyObject *res;
3618
3619 if (meth == NULL)
3620 return -1;
3621 res = PyObject_Call(meth, args, kwds);
3622 Py_DECREF(meth);
3623 if (res == NULL)
3624 return -1;
3625 Py_DECREF(res);
3626 return 0;
3627}
3628
3629static PyObject *
3630slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3631{
3632 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3633 PyObject *newargs, *x;
3634 int i, n;
3635
3636 if (func == NULL)
3637 return NULL;
3638 assert(PyTuple_Check(args));
3639 n = PyTuple_GET_SIZE(args);
3640 newargs = PyTuple_New(n+1);
3641 if (newargs == NULL)
3642 return NULL;
3643 Py_INCREF(type);
3644 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3645 for (i = 0; i < n; i++) {
3646 x = PyTuple_GET_ITEM(args, i);
3647 Py_INCREF(x);
3648 PyTuple_SET_ITEM(newargs, i+1, x);
3649 }
3650 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003651 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652 Py_DECREF(func);
3653 return x;
3654}
3655
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003656
3657/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3658 functions. The offsets here are relative to the 'etype' structure, which
3659 incorporates the additional structures used for numbers, sequences and
3660 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3661 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003662 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3663 terminated with an all-zero entry. (This table is further initialized and
3664 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003665
Guido van Rossum6d204072001-10-21 00:44:31 +00003666typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003667
3668#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003669#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003670#undef ETSLOT
3671#undef SQSLOT
3672#undef MPSLOT
3673#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003674#undef UNSLOT
3675#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003676#undef BINSLOT
3677#undef RBINSLOT
3678
Guido van Rossum6d204072001-10-21 00:44:31 +00003679#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3680 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003681#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3682 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3683 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003684#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3685 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3686#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3687 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3688#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3689 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3690#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3691 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3692#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3693 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3694 "x." NAME "() <==> " DOC)
3695#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3696 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3697 "x." NAME "(y) <==> x" DOC "y")
3698#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3699 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3700 "x." NAME "(y) <==> x" DOC "y")
3701#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3702 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3703 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003704
3705static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003706 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3707 "x.__len__() <==> len(x)"),
3708 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3709 "x.__add__(y) <==> x+y"),
3710 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3711 "x.__mul__(n) <==> x*n"),
3712 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3713 "x.__rmul__(n) <==> n*x"),
3714 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3715 "x.__getitem__(y) <==> x[y]"),
3716 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3717 "x.__getslice__(i, j) <==> x[i:j]"),
3718 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3719 "x.__setitem__(i, y) <==> x[i]=y"),
3720 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3721 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003722 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003723 wrap_intintobjargproc,
3724 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3725 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3726 "x.__delslice__(i, j) <==> del x[i:j]"),
3727 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3728 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003729 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003730 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003731 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003732 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003733
Guido van Rossum6d204072001-10-21 00:44:31 +00003734 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3735 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003736 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003737 wrap_binaryfunc,
3738 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003739 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003740 wrap_objobjargproc,
3741 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003742 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003743 wrap_delitem,
3744 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003745
Guido van Rossum6d204072001-10-21 00:44:31 +00003746 BINSLOT("__add__", nb_add, slot_nb_add,
3747 "+"),
3748 RBINSLOT("__radd__", nb_add, slot_nb_add,
3749 "+"),
3750 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3751 "-"),
3752 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3753 "-"),
3754 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3755 "*"),
3756 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3757 "*"),
3758 BINSLOT("__div__", nb_divide, slot_nb_divide,
3759 "/"),
3760 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3761 "/"),
3762 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3763 "%"),
3764 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3765 "%"),
3766 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3767 "divmod(x, y)"),
3768 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3769 "divmod(y, x)"),
3770 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3771 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3772 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3773 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3774 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3775 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3776 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3777 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003778 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003779 "x != 0"),
3780 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3781 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3782 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3783 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3784 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3785 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3786 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3787 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3788 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3789 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3790 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3791 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3792 "x.__coerce__(y) <==> coerce(x, y)"),
3793 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3794 "int(x)"),
3795 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3796 "long(x)"),
3797 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3798 "float(x)"),
3799 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3800 "oct(x)"),
3801 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3802 "hex(x)"),
3803 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3804 wrap_binaryfunc, "+"),
3805 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3806 wrap_binaryfunc, "-"),
3807 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3808 wrap_binaryfunc, "*"),
3809 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3810 wrap_binaryfunc, "/"),
3811 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3812 wrap_binaryfunc, "%"),
3813 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3814 wrap_ternaryfunc, "**"),
3815 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3816 wrap_binaryfunc, "<<"),
3817 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3818 wrap_binaryfunc, ">>"),
3819 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3820 wrap_binaryfunc, "&"),
3821 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3822 wrap_binaryfunc, "^"),
3823 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3824 wrap_binaryfunc, "|"),
3825 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3826 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3827 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3828 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3829 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3830 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3831 IBSLOT("__itruediv__", nb_inplace_true_divide,
3832 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003833
Guido van Rossum6d204072001-10-21 00:44:31 +00003834 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3835 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003836 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003837 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3838 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003839 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003840 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3841 "x.__cmp__(y) <==> cmp(x,y)"),
3842 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3843 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003844 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3845 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003846 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003847 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3848 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3849 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3850 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3851 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3852 "x.__setattr__('name', value) <==> x.name = value"),
3853 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3854 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3855 "x.__delattr__('name') <==> del x.name"),
3856 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3857 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3858 "x.__lt__(y) <==> x<y"),
3859 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3860 "x.__le__(y) <==> x<=y"),
3861 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3862 "x.__eq__(y) <==> x==y"),
3863 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3864 "x.__ne__(y) <==> x!=y"),
3865 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3866 "x.__gt__(y) <==> x>y"),
3867 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3868 "x.__ge__(y) <==> x>=y"),
3869 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3870 "x.__iter__() <==> iter(x)"),
3871 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3872 "x.next() -> the next value, or raise StopIteration"),
3873 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3874 "descr.__get__(obj[, type]) -> value"),
3875 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3876 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003877 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003878 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003879 "see x.__class__.__doc__ for signature",
3880 PyWrapperFlag_KEYWORDS),
3881 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003882 {NULL}
3883};
3884
Guido van Rossumc334df52002-04-04 23:44:47 +00003885/* Given a type pointer and an offset gotten from a slotdef entry, return a
3886 pointer to the actual slot. This is not quite the same as simply adding
3887 the offset to the type pointer, since it takes care to indirect through the
3888 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3889 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003890static void **
3891slotptr(PyTypeObject *type, int offset)
3892{
3893 char *ptr;
3894
Guido van Rossum09638c12002-06-13 19:17:46 +00003895 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003896 assert(offset >= 0);
3897 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003898 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003899 ptr = (void *)type->tp_as_sequence;
3900 offset -= offsetof(etype, as_sequence);
3901 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003902 else if (offset >= offsetof(etype, as_mapping)) {
3903 ptr = (void *)type->tp_as_mapping;
3904 offset -= offsetof(etype, as_mapping);
3905 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003906 else if (offset >= offsetof(etype, as_number)) {
3907 ptr = (void *)type->tp_as_number;
3908 offset -= offsetof(etype, as_number);
3909 }
3910 else {
3911 ptr = (void *)type;
3912 }
3913 if (ptr != NULL)
3914 ptr += offset;
3915 return (void **)ptr;
3916}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003917
Guido van Rossumc334df52002-04-04 23:44:47 +00003918/* Length of array of slotdef pointers used to store slots with the
3919 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3920 the same __name__, for any __name__. Since that's a static property, it is
3921 appropriate to declare fixed-size arrays for this. */
3922#define MAX_EQUIV 10
3923
3924/* Return a slot pointer for a given name, but ONLY if the attribute has
3925 exactly one slot function. The name must be an interned string. */
3926static void **
3927resolve_slotdups(PyTypeObject *type, PyObject *name)
3928{
3929 /* XXX Maybe this could be optimized more -- but is it worth it? */
3930
3931 /* pname and ptrs act as a little cache */
3932 static PyObject *pname;
3933 static slotdef *ptrs[MAX_EQUIV];
3934 slotdef *p, **pp;
3935 void **res, **ptr;
3936
3937 if (pname != name) {
3938 /* Collect all slotdefs that match name into ptrs. */
3939 pname = name;
3940 pp = ptrs;
3941 for (p = slotdefs; p->name_strobj; p++) {
3942 if (p->name_strobj == name)
3943 *pp++ = p;
3944 }
3945 *pp = NULL;
3946 }
3947
3948 /* Look in all matching slots of the type; if exactly one of these has
3949 a filled-in slot, return its value. Otherwise return NULL. */
3950 res = NULL;
3951 for (pp = ptrs; *pp; pp++) {
3952 ptr = slotptr(type, (*pp)->offset);
3953 if (ptr == NULL || *ptr == NULL)
3954 continue;
3955 if (res != NULL)
3956 return NULL;
3957 res = ptr;
3958 }
3959 return res;
3960}
3961
3962/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3963 does some incredibly complex thinking and then sticks something into the
3964 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3965 interests, and then stores a generic wrapper or a specific function into
3966 the slot.) Return a pointer to the next slotdef with a different offset,
3967 because that's convenient for fixup_slot_dispatchers(). */
3968static slotdef *
3969update_one_slot(PyTypeObject *type, slotdef *p)
3970{
3971 PyObject *descr;
3972 PyWrapperDescrObject *d;
3973 void *generic = NULL, *specific = NULL;
3974 int use_generic = 0;
3975 int offset = p->offset;
3976 void **ptr = slotptr(type, offset);
3977
3978 if (ptr == NULL) {
3979 do {
3980 ++p;
3981 } while (p->offset == offset);
3982 return p;
3983 }
3984 do {
3985 descr = _PyType_Lookup(type, p->name_strobj);
3986 if (descr == NULL)
3987 continue;
3988 if (descr->ob_type == &PyWrapperDescr_Type) {
3989 void **tptr = resolve_slotdups(type, p->name_strobj);
3990 if (tptr == NULL || tptr == ptr)
3991 generic = p->function;
3992 d = (PyWrapperDescrObject *)descr;
3993 if (d->d_base->wrapper == p->wrapper &&
3994 PyType_IsSubtype(type, d->d_type))
3995 {
3996 if (specific == NULL ||
3997 specific == d->d_wrapped)
3998 specific = d->d_wrapped;
3999 else
4000 use_generic = 1;
4001 }
4002 }
4003 else {
4004 use_generic = 1;
4005 generic = p->function;
4006 }
4007 } while ((++p)->offset == offset);
4008 if (specific && !use_generic)
4009 *ptr = specific;
4010 else
4011 *ptr = generic;
4012 return p;
4013}
4014
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004015staticforward int recurse_down_subclasses(PyTypeObject *type,
4016 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004017
Guido van Rossumc334df52002-04-04 23:44:47 +00004018/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4019 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004020static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004021update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004022{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004023 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004024
Guido van Rossumc334df52002-04-04 23:44:47 +00004025 for (pp = pp0; *pp; pp++)
4026 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004027 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004028}
4029
Guido van Rossumc334df52002-04-04 23:44:47 +00004030/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4031 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004032static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004033recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004034{
4035 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004036 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004037 int i, n;
4038
4039 subclasses = type->tp_subclasses;
4040 if (subclasses == NULL)
4041 return 0;
4042 assert(PyList_Check(subclasses));
4043 n = PyList_GET_SIZE(subclasses);
4044 for (i = 0; i < n; i++) {
4045 ref = PyList_GET_ITEM(subclasses, i);
4046 assert(PyWeakref_CheckRef(ref));
4047 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004048 assert(subclass != NULL);
4049 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004050 continue;
4051 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004052 /* Avoid recursing down into unaffected classes */
4053 dict = subclass->tp_dict;
4054 if (dict != NULL && PyDict_Check(dict) &&
4055 PyDict_GetItem(dict, name) != NULL)
4056 continue;
4057 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004058 return -1;
4059 }
4060 return 0;
4061}
4062
Guido van Rossumc334df52002-04-04 23:44:47 +00004063/* Comparison function for qsort() to compare slotdefs by their offset, and
4064 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004065static int
4066slotdef_cmp(const void *aa, const void *bb)
4067{
4068 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4069 int c = a->offset - b->offset;
4070 if (c != 0)
4071 return c;
4072 else
4073 return a - b;
4074}
4075
Guido van Rossumc334df52002-04-04 23:44:47 +00004076/* Initialize the slotdefs table by adding interned string objects for the
4077 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004078static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004079init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004080{
4081 slotdef *p;
4082 static int initialized = 0;
4083
4084 if (initialized)
4085 return;
4086 for (p = slotdefs; p->name; p++) {
4087 p->name_strobj = PyString_InternFromString(p->name);
4088 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004089 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004090 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004091 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4092 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004093 initialized = 1;
4094}
4095
Guido van Rossumc334df52002-04-04 23:44:47 +00004096/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004097static int
4098update_slot(PyTypeObject *type, PyObject *name)
4099{
Guido van Rossumc334df52002-04-04 23:44:47 +00004100 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004101 slotdef *p;
4102 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004103 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004104
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004105 init_slotdefs();
4106 pp = ptrs;
4107 for (p = slotdefs; p->name; p++) {
4108 /* XXX assume name is interned! */
4109 if (p->name_strobj == name)
4110 *pp++ = p;
4111 }
4112 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004113 for (pp = ptrs; *pp; pp++) {
4114 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004115 offset = p->offset;
4116 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004117 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004118 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004119 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004120 if (ptrs[0] == NULL)
4121 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004122 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004123}
4124
Guido van Rossumc334df52002-04-04 23:44:47 +00004125/* Store the proper functions in the slot dispatches at class (type)
4126 definition time, based upon which operations the class overrides in its
4127 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004129fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004131 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004132
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004133 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004134 for (p = slotdefs; p->name; )
4135 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004137
Guido van Rossum6d204072001-10-21 00:44:31 +00004138/* This function is called by PyType_Ready() to populate the type's
4139 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004140 function slot (like tp_repr) that's defined in the type, one or more
4141 corresponding descriptors are added in the type's tp_dict dictionary
4142 under the appropriate name (like __repr__). Some function slots
4143 cause more than one descriptor to be added (for example, the nb_add
4144 slot adds both __add__ and __radd__ descriptors) and some function
4145 slots compete for the same descriptor (for example both sq_item and
4146 mp_subscript generate a __getitem__ descriptor).
4147
4148 In the latter case, the first slotdef entry encoutered wins. Since
4149 slotdef entries are sorted by the offset of the slot in the etype
4150 struct, this gives us some control over disambiguating between
4151 competing slots: the members of struct etype are listed from most
4152 general to least general, so the most general slot is preferred. In
4153 particular, because as_mapping comes before as_sequence, for a type
4154 that defines both mp_subscript and sq_item, mp_subscript wins.
4155
4156 This only adds new descriptors and doesn't overwrite entries in
4157 tp_dict that were previously defined. The descriptors contain a
4158 reference to the C function they must call, so that it's safe if they
4159 are copied into a subtype's __dict__ and the subtype has a different
4160 C function in its slot -- calling the method defined by the
4161 descriptor will call the C function that was used to create it,
4162 rather than the C function present in the slot when it is called.
4163 (This is important because a subtype may have a C function in the
4164 slot that calls the method from the dictionary, and we want to avoid
4165 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004166
4167static int
4168add_operators(PyTypeObject *type)
4169{
4170 PyObject *dict = type->tp_dict;
4171 slotdef *p;
4172 PyObject *descr;
4173 void **ptr;
4174
4175 init_slotdefs();
4176 for (p = slotdefs; p->name; p++) {
4177 if (p->wrapper == NULL)
4178 continue;
4179 ptr = slotptr(type, p->offset);
4180 if (!ptr || !*ptr)
4181 continue;
4182 if (PyDict_GetItem(dict, p->name_strobj))
4183 continue;
4184 descr = PyDescr_NewWrapper(type, p, *ptr);
4185 if (descr == NULL)
4186 return -1;
4187 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4188 return -1;
4189 Py_DECREF(descr);
4190 }
4191 if (type->tp_new != NULL) {
4192 if (add_tp_new_wrapper(type) < 0)
4193 return -1;
4194 }
4195 return 0;
4196}
4197
Guido van Rossum705f0f52001-08-24 16:47:00 +00004198
4199/* Cooperative 'super' */
4200
4201typedef struct {
4202 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004203 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004204 PyObject *obj;
4205} superobject;
4206
Guido van Rossum6f799372001-09-20 20:46:19 +00004207static PyMemberDef super_members[] = {
4208 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4209 "the class invoking super()"},
4210 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4211 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004212 {0}
4213};
4214
Guido van Rossum705f0f52001-08-24 16:47:00 +00004215static void
4216super_dealloc(PyObject *self)
4217{
4218 superobject *su = (superobject *)self;
4219
Guido van Rossum048eb752001-10-02 21:24:57 +00004220 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004221 Py_XDECREF(su->obj);
4222 Py_XDECREF(su->type);
4223 self->ob_type->tp_free(self);
4224}
4225
4226static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004227super_repr(PyObject *self)
4228{
4229 superobject *su = (superobject *)self;
4230
4231 if (su->obj)
4232 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004233 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004234 su->type ? su->type->tp_name : "NULL",
4235 su->obj->ob_type->tp_name);
4236 else
4237 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004238 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004239 su->type ? su->type->tp_name : "NULL");
4240}
4241
4242static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004243super_getattro(PyObject *self, PyObject *name)
4244{
4245 superobject *su = (superobject *)self;
4246
4247 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004248 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004249 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004250 descrgetfunc f;
4251 int i, n;
4252
Guido van Rossum155db9a2002-04-02 17:53:47 +00004253 starttype = su->obj->ob_type;
4254 mro = starttype->tp_mro;
4255
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004256 if (mro == NULL)
4257 n = 0;
4258 else {
4259 assert(PyTuple_Check(mro));
4260 n = PyTuple_GET_SIZE(mro);
4261 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004262 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004263 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004264 break;
4265 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004266 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004267 starttype = (PyTypeObject *)(su->obj);
4268 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004269 if (mro == NULL)
4270 n = 0;
4271 else {
4272 assert(PyTuple_Check(mro));
4273 n = PyTuple_GET_SIZE(mro);
4274 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004275 for (i = 0; i < n; i++) {
4276 if ((PyObject *)(su->type) ==
4277 PyTuple_GET_ITEM(mro, i))
4278 break;
4279 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004280 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004281 i++;
4282 res = NULL;
4283 for (; i < n; i++) {
4284 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004285 if (PyType_Check(tmp))
4286 dict = ((PyTypeObject *)tmp)->tp_dict;
4287 else if (PyClass_Check(tmp))
4288 dict = ((PyClassObject *)tmp)->cl_dict;
4289 else
4290 continue;
4291 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004292 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004293 Py_INCREF(res);
4294 f = res->ob_type->tp_descr_get;
4295 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004296 tmp = f(res, su->obj,
4297 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004298 Py_DECREF(res);
4299 res = tmp;
4300 }
4301 return res;
4302 }
4303 }
4304 }
4305 return PyObject_GenericGetAttr(self, name);
4306}
4307
Guido van Rossum5b443c62001-12-03 15:38:28 +00004308static int
4309supercheck(PyTypeObject *type, PyObject *obj)
4310{
4311 if (!PyType_IsSubtype(obj->ob_type, type) &&
4312 !(PyType_Check(obj) &&
4313 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4314 PyErr_SetString(PyExc_TypeError,
4315 "super(type, obj): "
4316 "obj must be an instance or subtype of type");
4317 return -1;
4318 }
4319 else
4320 return 0;
4321}
4322
Guido van Rossum705f0f52001-08-24 16:47:00 +00004323static PyObject *
4324super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4325{
4326 superobject *su = (superobject *)self;
4327 superobject *new;
4328
4329 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4330 /* Not binding to an object, or already bound */
4331 Py_INCREF(self);
4332 return self;
4333 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004334 if (su->ob_type != &PySuper_Type)
4335 /* If su is an instance of a subclass of super,
4336 call its type */
4337 return PyObject_CallFunction((PyObject *)su->ob_type,
4338 "OO", su->type, obj);
4339 else {
4340 /* Inline the common case */
4341 if (supercheck(su->type, obj) < 0)
4342 return NULL;
4343 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4344 NULL, NULL);
4345 if (new == NULL)
4346 return NULL;
4347 Py_INCREF(su->type);
4348 Py_INCREF(obj);
4349 new->type = su->type;
4350 new->obj = obj;
4351 return (PyObject *)new;
4352 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004353}
4354
4355static int
4356super_init(PyObject *self, PyObject *args, PyObject *kwds)
4357{
4358 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004359 PyTypeObject *type;
4360 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004361
4362 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4363 return -1;
4364 if (obj == Py_None)
4365 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004366 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004367 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004368 Py_INCREF(type);
4369 Py_XINCREF(obj);
4370 su->type = type;
4371 su->obj = obj;
4372 return 0;
4373}
4374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004375PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004376"super(type) -> unbound super object\n"
4377"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004378"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004379"Typical use to call a cooperative superclass method:\n"
4380"class C(B):\n"
4381" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004382" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004383
Guido van Rossum048eb752001-10-02 21:24:57 +00004384static int
4385super_traverse(PyObject *self, visitproc visit, void *arg)
4386{
4387 superobject *su = (superobject *)self;
4388 int err;
4389
4390#define VISIT(SLOT) \
4391 if (SLOT) { \
4392 err = visit((PyObject *)(SLOT), arg); \
4393 if (err) \
4394 return err; \
4395 }
4396
4397 VISIT(su->obj);
4398 VISIT(su->type);
4399
4400#undef VISIT
4401
4402 return 0;
4403}
4404
Guido van Rossum705f0f52001-08-24 16:47:00 +00004405PyTypeObject PySuper_Type = {
4406 PyObject_HEAD_INIT(&PyType_Type)
4407 0, /* ob_size */
4408 "super", /* tp_name */
4409 sizeof(superobject), /* tp_basicsize */
4410 0, /* tp_itemsize */
4411 /* methods */
4412 super_dealloc, /* tp_dealloc */
4413 0, /* tp_print */
4414 0, /* tp_getattr */
4415 0, /* tp_setattr */
4416 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004417 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004418 0, /* tp_as_number */
4419 0, /* tp_as_sequence */
4420 0, /* tp_as_mapping */
4421 0, /* tp_hash */
4422 0, /* tp_call */
4423 0, /* tp_str */
4424 super_getattro, /* tp_getattro */
4425 0, /* tp_setattro */
4426 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004427 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4428 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004429 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004430 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004431 0, /* tp_clear */
4432 0, /* tp_richcompare */
4433 0, /* tp_weaklistoffset */
4434 0, /* tp_iter */
4435 0, /* tp_iternext */
4436 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004437 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004438 0, /* tp_getset */
4439 0, /* tp_base */
4440 0, /* tp_dict */
4441 super_descr_get, /* tp_descr_get */
4442 0, /* tp_descr_set */
4443 0, /* tp_dictoffset */
4444 super_init, /* tp_init */
4445 PyType_GenericAlloc, /* tp_alloc */
4446 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004447 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004448};