blob: 2beb3b32a84a47e7718a26546111699c8d07e91b [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. */
368#ifdef Py_TRACE_REFS
369#ifndef Py_REF_DEBUG
370# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
371#endif
372 /* much too complicated if Py_TRACE_REFS defined */
373 _Py_NewReference((PyObject *)self);
374#ifdef COUNT_ALLOCS
375 /* compensate for boost in _Py_NewReference; note that
376 * _Py_RefTotal was also boosted; we'll knock that down later.
377 */
378 self->ob_type->tp_allocs--;
379#endif
380#else /* !Py_TRACE_REFS */
381 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
382 Py_INCREF(self);
383#endif /* !Py_TRACE_REFS */
384
385 /* Save the current exception, if any. */
386 PyErr_Fetch(&error_type, &error_value, &error_traceback);
387
388 /* Execute __del__ method, if any. */
389 del = lookup_maybe(self, "__del__", &del_str);
390 if (del != NULL) {
391 res = PyEval_CallObject(del, NULL);
392 if (res == NULL)
393 PyErr_WriteUnraisable(del);
394 else
395 Py_DECREF(res);
396 Py_DECREF(del);
397 }
398
399 /* Restore the saved exception. */
400 PyErr_Restore(error_type, error_value, error_traceback);
401
402 /* Undo the temporary resurrection; can't use DECREF here, it would
403 * cause a recursive call.
404 */
405#ifdef Py_REF_DEBUG
406 /* _Py_RefTotal was boosted either by _Py_NewReference or
407 * Py_INCREF above.
408 */
409 _Py_RefTotal--;
410#endif
411 if (--self->ob_refcnt > 0) {
412#ifdef COUNT_ALLOCS
413 self->ob_type->tp_frees--;
414#endif
415 _PyObject_GC_TRACK(self);
416 return -1; /* __del__ added a reference; don't delete now */
417 }
418#ifdef Py_TRACE_REFS
419 _Py_ForgetReference((PyObject *)self);
420#ifdef COUNT_ALLOCS
421 /* compensate for increment in _Py_ForgetReference */
422 self->ob_type->tp_frees--;
423#endif
424#endif
425
426 return 0;
427}
428
Tim Peters6d6c1a32001-08-02 04:15:00 +0000429static void
430subtype_dealloc(PyObject *self)
431{
Guido van Rossum14227b42001-12-06 02:35:58 +0000432 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000433 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000434
435 /* This exists so we can DECREF self->ob_type */
436
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000437 if (call_finalizer(self) < 0)
438 return;
439
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000440 /* Find the nearest base with a different tp_dealloc
441 and clear slots while we're at it */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000442 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000443 base = type;
444 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
445 if (base->ob_size)
446 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447 base = base->tp_base;
448 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000449 }
450
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000452 if (type->tp_dictoffset && !base->tp_dictoffset) {
453 PyObject **dictptr = _PyObject_GetDictPtr(self);
454 if (dictptr != NULL) {
455 PyObject *dict = *dictptr;
456 if (dict != NULL) {
457 Py_DECREF(dict);
458 *dictptr = NULL;
459 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 }
461 }
462
Guido van Rossum9676b222001-08-17 20:32:36 +0000463 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000464 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000465 PyObject_ClearWeakRefs(self);
466
Tim Peters6d6c1a32001-08-02 04:15:00 +0000467 /* Finalize GC if the base doesn't do GC and we do */
468 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000469 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000470
471 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000472 assert(basedealloc);
473 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474
475 /* Can't reference self beyond this point */
476 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
477 Py_DECREF(type);
478 }
479}
480
Tim Peters6d6c1a32001-08-02 04:15:00 +0000481staticforward PyTypeObject *solid_base(PyTypeObject *type);
482
Tim Peters6d6c1a32001-08-02 04:15:00 +0000483/* type test with subclassing support */
484
485int
486PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
487{
488 PyObject *mro;
489
Guido van Rossum9478d072001-09-07 18:52:13 +0000490 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
491 return b == a || b == &PyBaseObject_Type;
492
Tim Peters6d6c1a32001-08-02 04:15:00 +0000493 mro = a->tp_mro;
494 if (mro != NULL) {
495 /* Deal with multiple inheritance without recursion
496 by walking the MRO tuple */
497 int i, n;
498 assert(PyTuple_Check(mro));
499 n = PyTuple_GET_SIZE(mro);
500 for (i = 0; i < n; i++) {
501 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
502 return 1;
503 }
504 return 0;
505 }
506 else {
507 /* a is not completely initilized yet; follow tp_base */
508 do {
509 if (a == b)
510 return 1;
511 a = a->tp_base;
512 } while (a != NULL);
513 return b == &PyBaseObject_Type;
514 }
515}
516
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000517/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000518 without looking in the instance dictionary
519 (so we can't use PyObject_GetAttr) but still binding
520 it to the instance. The arguments are the object,
521 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000522 static variable used to cache the interned Python string.
523
524 Two variants:
525
526 - lookup_maybe() returns NULL without raising an exception
527 when the _PyType_Lookup() call fails;
528
529 - lookup_method() always raises an exception upon errors.
530*/
Guido van Rossum60718732001-08-28 17:47:51 +0000531
532static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000533lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000534{
535 PyObject *res;
536
537 if (*attrobj == NULL) {
538 *attrobj = PyString_InternFromString(attrstr);
539 if (*attrobj == NULL)
540 return NULL;
541 }
542 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000543 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000544 descrgetfunc f;
545 if ((f = res->ob_type->tp_descr_get) == NULL)
546 Py_INCREF(res);
547 else
548 res = f(res, self, (PyObject *)(self->ob_type));
549 }
550 return res;
551}
552
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000553static PyObject *
554lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
555{
556 PyObject *res = lookup_maybe(self, attrstr, attrobj);
557 if (res == NULL && !PyErr_Occurred())
558 PyErr_SetObject(PyExc_AttributeError, *attrobj);
559 return res;
560}
561
Guido van Rossum2730b132001-08-28 18:22:14 +0000562/* A variation of PyObject_CallMethod that uses lookup_method()
563 instead of PyObject_GetAttrString(). This uses the same convention
564 as lookup_method to cache the interned name string object. */
565
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000566static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000567call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
568{
569 va_list va;
570 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000571 va_start(va, format);
572
Guido van Rossumda21c012001-10-03 00:50:18 +0000573 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000574 if (func == NULL) {
575 va_end(va);
576 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000577 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000578 return NULL;
579 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000580
581 if (format && *format)
582 args = Py_VaBuildValue(format, va);
583 else
584 args = PyTuple_New(0);
585
586 va_end(va);
587
588 if (args == NULL)
589 return NULL;
590
591 assert(PyTuple_Check(args));
592 retval = PyObject_Call(func, args, NULL);
593
594 Py_DECREF(args);
595 Py_DECREF(func);
596
597 return retval;
598}
599
600/* Clone of call_method() that returns NotImplemented when the lookup fails. */
601
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000602static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000603call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
604{
605 va_list va;
606 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000607 va_start(va, format);
608
Guido van Rossumda21c012001-10-03 00:50:18 +0000609 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000610 if (func == NULL) {
611 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000612 if (!PyErr_Occurred()) {
613 Py_INCREF(Py_NotImplemented);
614 return Py_NotImplemented;
615 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000616 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000617 }
618
619 if (format && *format)
620 args = Py_VaBuildValue(format, va);
621 else
622 args = PyTuple_New(0);
623
624 va_end(va);
625
Guido van Rossum717ce002001-09-14 16:58:08 +0000626 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000627 return NULL;
628
Guido van Rossum717ce002001-09-14 16:58:08 +0000629 assert(PyTuple_Check(args));
630 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000631
632 Py_DECREF(args);
633 Py_DECREF(func);
634
635 return retval;
636}
637
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638/* Method resolution order algorithm from "Putting Metaclasses to Work"
639 by Forman and Danforth (Addison-Wesley 1999). */
640
641static int
642conservative_merge(PyObject *left, PyObject *right)
643{
644 int left_size;
645 int right_size;
646 int i, j, r, ok;
647 PyObject *temp, *rr;
648
649 assert(PyList_Check(left));
650 assert(PyList_Check(right));
651
652 again:
653 left_size = PyList_GET_SIZE(left);
654 right_size = PyList_GET_SIZE(right);
655 for (i = 0; i < left_size; i++) {
656 for (j = 0; j < right_size; j++) {
657 if (PyList_GET_ITEM(left, i) ==
658 PyList_GET_ITEM(right, j)) {
659 /* found a merge point */
660 temp = PyList_New(0);
661 if (temp == NULL)
662 return -1;
663 for (r = 0; r < j; r++) {
664 rr = PyList_GET_ITEM(right, r);
665 ok = PySequence_Contains(left, rr);
666 if (ok < 0) {
667 Py_DECREF(temp);
668 return -1;
669 }
670 if (!ok) {
671 ok = PyList_Append(temp, rr);
672 if (ok < 0) {
673 Py_DECREF(temp);
674 return -1;
675 }
676 }
677 }
678 ok = PyList_SetSlice(left, i, i, temp);
679 Py_DECREF(temp);
680 if (ok < 0)
681 return -1;
682 ok = PyList_SetSlice(right, 0, j+1, NULL);
683 if (ok < 0)
684 return -1;
685 goto again;
686 }
687 }
688 }
689 return PyList_SetSlice(left, left_size, left_size, right);
690}
691
692static int
693serious_order_disagreements(PyObject *left, PyObject *right)
694{
695 return 0; /* XXX later -- for now, we cheat: "don't do that" */
696}
697
Tim Petersa91e9642001-11-14 23:32:33 +0000698static int
699fill_classic_mro(PyObject *mro, PyObject *cls)
700{
701 PyObject *bases, *base;
702 int i, n;
703
704 assert(PyList_Check(mro));
705 assert(PyClass_Check(cls));
706 i = PySequence_Contains(mro, cls);
707 if (i < 0)
708 return -1;
709 if (!i) {
710 if (PyList_Append(mro, cls) < 0)
711 return -1;
712 }
713 bases = ((PyClassObject *)cls)->cl_bases;
714 assert(bases && PyTuple_Check(bases));
715 n = PyTuple_GET_SIZE(bases);
716 for (i = 0; i < n; i++) {
717 base = PyTuple_GET_ITEM(bases, i);
718 if (fill_classic_mro(mro, base) < 0)
719 return -1;
720 }
721 return 0;
722}
723
724static PyObject *
725classic_mro(PyObject *cls)
726{
727 PyObject *mro;
728
729 assert(PyClass_Check(cls));
730 mro = PyList_New(0);
731 if (mro != NULL) {
732 if (fill_classic_mro(mro, cls) == 0)
733 return mro;
734 Py_DECREF(mro);
735 }
736 return NULL;
737}
738
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739static PyObject *
740mro_implementation(PyTypeObject *type)
741{
742 int i, n, ok;
743 PyObject *bases, *result;
744
Guido van Rossum63517572002-06-18 16:44:57 +0000745 if(type->tp_dict == NULL) {
746 if(PyType_Ready(type) < 0)
747 return NULL;
748 }
749
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750 bases = type->tp_bases;
751 n = PyTuple_GET_SIZE(bases);
752 result = Py_BuildValue("[O]", (PyObject *)type);
753 if (result == NULL)
754 return NULL;
755 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000756 PyObject *base = PyTuple_GET_ITEM(bases, i);
757 PyObject *parentMRO;
758 if (PyType_Check(base))
759 parentMRO = PySequence_List(
760 ((PyTypeObject*)base)->tp_mro);
761 else
762 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000763 if (parentMRO == NULL) {
764 Py_DECREF(result);
765 return NULL;
766 }
767 if (serious_order_disagreements(result, parentMRO)) {
768 Py_DECREF(result);
769 return NULL;
770 }
771 ok = conservative_merge(result, parentMRO);
772 Py_DECREF(parentMRO);
773 if (ok < 0) {
774 Py_DECREF(result);
775 return NULL;
776 }
777 }
778 return result;
779}
780
781static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000782mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783{
784 PyTypeObject *type = (PyTypeObject *)self;
785
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786 return mro_implementation(type);
787}
788
789static int
790mro_internal(PyTypeObject *type)
791{
792 PyObject *mro, *result, *tuple;
793
794 if (type->ob_type == &PyType_Type) {
795 result = mro_implementation(type);
796 }
797 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000798 static PyObject *mro_str;
799 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800 if (mro == NULL)
801 return -1;
802 result = PyObject_CallObject(mro, NULL);
803 Py_DECREF(mro);
804 }
805 if (result == NULL)
806 return -1;
807 tuple = PySequence_Tuple(result);
808 Py_DECREF(result);
809 type->tp_mro = tuple;
810 return 0;
811}
812
813
814/* Calculate the best base amongst multiple base classes.
815 This is the first one that's on the path to the "solid base". */
816
817static PyTypeObject *
818best_base(PyObject *bases)
819{
820 int i, n;
821 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000822 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823
824 assert(PyTuple_Check(bases));
825 n = PyTuple_GET_SIZE(bases);
826 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000827 base = NULL;
828 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000829 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000830 base_proto = PyTuple_GET_ITEM(bases, i);
831 if (PyClass_Check(base_proto))
832 continue;
833 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 PyErr_SetString(
835 PyExc_TypeError,
836 "bases must be types");
837 return NULL;
838 }
Tim Petersa91e9642001-11-14 23:32:33 +0000839 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000841 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 return NULL;
843 }
844 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000845 if (winner == NULL) {
846 winner = candidate;
847 base = base_i;
848 }
849 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850 ;
851 else if (PyType_IsSubtype(candidate, winner)) {
852 winner = candidate;
853 base = base_i;
854 }
855 else {
856 PyErr_SetString(
857 PyExc_TypeError,
858 "multiple bases have "
859 "instance lay-out conflict");
860 return NULL;
861 }
862 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000863 if (base == NULL)
864 PyErr_SetString(PyExc_TypeError,
865 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866 return base;
867}
868
869static int
870extra_ivars(PyTypeObject *type, PyTypeObject *base)
871{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000872 size_t t_size = type->tp_basicsize;
873 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874
Guido van Rossum9676b222001-08-17 20:32:36 +0000875 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000876 if (type->tp_itemsize || base->tp_itemsize) {
877 /* If itemsize is involved, stricter rules */
878 return t_size != b_size ||
879 type->tp_itemsize != base->tp_itemsize;
880 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000881 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
882 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
883 t_size -= sizeof(PyObject *);
884 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
885 type->tp_dictoffset + sizeof(PyObject *) == t_size)
886 t_size -= sizeof(PyObject *);
887
888 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889}
890
891static PyTypeObject *
892solid_base(PyTypeObject *type)
893{
894 PyTypeObject *base;
895
896 if (type->tp_base)
897 base = solid_base(type->tp_base);
898 else
899 base = &PyBaseObject_Type;
900 if (extra_ivars(type, base))
901 return type;
902 else
903 return base;
904}
905
906staticforward void object_dealloc(PyObject *);
907staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000908staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000909staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910
911static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000912subtype_dict(PyObject *obj, void *context)
913{
914 PyObject **dictptr = _PyObject_GetDictPtr(obj);
915 PyObject *dict;
916
917 if (dictptr == NULL) {
918 PyErr_SetString(PyExc_AttributeError,
919 "This object has no __dict__");
920 return NULL;
921 }
922 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000923 if (dict == NULL)
924 *dictptr = dict = PyDict_New();
925 Py_XINCREF(dict);
926 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000927}
928
Guido van Rossum6661be32001-10-26 04:26:12 +0000929static int
930subtype_setdict(PyObject *obj, PyObject *value, void *context)
931{
932 PyObject **dictptr = _PyObject_GetDictPtr(obj);
933 PyObject *dict;
934
935 if (dictptr == NULL) {
936 PyErr_SetString(PyExc_AttributeError,
937 "This object has no __dict__");
938 return -1;
939 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000940 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000941 PyErr_SetString(PyExc_TypeError,
942 "__dict__ must be set to a dictionary");
943 return -1;
944 }
945 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000946 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000947 *dictptr = value;
948 Py_XDECREF(dict);
949 return 0;
950}
951
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000952static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000953 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000954 {0},
955};
956
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000957/* bozo: __getstate__ that raises TypeError */
958
959static PyObject *
960bozo_func(PyObject *self, PyObject *args)
961{
962 PyErr_SetString(PyExc_TypeError,
963 "a class that defines __slots__ without "
964 "defining __getstate__ cannot be pickled");
965 return NULL;
966}
967
Neal Norwitz93c1e232002-03-31 16:06:11 +0000968static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000969
970static PyObject *bozo_obj = NULL;
971
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000972static int
973valid_identifier(PyObject *s)
974{
975 char *p;
976 int i, n;
977
978 if (!PyString_Check(s)) {
979 PyErr_SetString(PyExc_TypeError,
980 "__slots__ must be strings");
981 return 0;
982 }
983 p = PyString_AS_STRING(s);
984 n = PyString_GET_SIZE(s);
985 /* We must reject an empty name. As a hack, we bump the
986 length to 1 so that the loop will balk on the trailing \0. */
987 if (n == 0)
988 n = 1;
989 for (i = 0; i < n; i++, p++) {
990 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
991 PyErr_SetString(PyExc_TypeError,
992 "__slots__ must be identifiers");
993 return 0;
994 }
995 }
996 return 1;
997}
998
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000999static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1001{
1002 PyObject *name, *bases, *dict;
1003 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001004 static char buffer[256];
1005 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001006 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001008 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001009 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001010
Tim Peters3abca122001-10-27 19:37:48 +00001011 assert(args != NULL && PyTuple_Check(args));
1012 assert(kwds == NULL || PyDict_Check(kwds));
1013
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001014 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001015 {
1016 const int nargs = PyTuple_GET_SIZE(args);
1017 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1018
1019 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1020 PyObject *x = PyTuple_GET_ITEM(args, 0);
1021 Py_INCREF(x->ob_type);
1022 return (PyObject *) x->ob_type;
1023 }
1024
1025 /* SF bug 475327 -- if that didn't trigger, we need 3
1026 arguments. but PyArg_ParseTupleAndKeywords below may give
1027 a msg saying type() needs exactly 3. */
1028 if (nargs + nkwds != 3) {
1029 PyErr_SetString(PyExc_TypeError,
1030 "type() takes 1 or 3 arguments");
1031 return NULL;
1032 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033 }
1034
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001035 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1037 &name,
1038 &PyTuple_Type, &bases,
1039 &PyDict_Type, &dict))
1040 return NULL;
1041
1042 /* Determine the proper metatype to deal with this,
1043 and check for metatype conflicts while we're at it.
1044 Note that if some other metatype wins to contract,
1045 it's possible that its instances are not types. */
1046 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001047 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001048 for (i = 0; i < nbases; i++) {
1049 tmp = PyTuple_GET_ITEM(bases, i);
1050 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001051 if (tmptype == &PyClass_Type)
1052 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001053 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001055 if (PyType_IsSubtype(tmptype, winner)) {
1056 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001057 continue;
1058 }
1059 PyErr_SetString(PyExc_TypeError,
1060 "metatype conflict among bases");
1061 return NULL;
1062 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001063 if (winner != metatype) {
1064 if (winner->tp_new != type_new) /* Pass it to the winner */
1065 return winner->tp_new(winner, args, kwds);
1066 metatype = winner;
1067 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001068
1069 /* Adjust for empty tuple bases */
1070 if (nbases == 0) {
1071 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1072 if (bases == NULL)
1073 return NULL;
1074 nbases = 1;
1075 }
1076 else
1077 Py_INCREF(bases);
1078
1079 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1080
1081 /* Calculate best base, and check that all bases are type objects */
1082 base = best_base(bases);
1083 if (base == NULL)
1084 return NULL;
1085 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1086 PyErr_Format(PyExc_TypeError,
1087 "type '%.100s' is not an acceptable base type",
1088 base->tp_name);
1089 return NULL;
1090 }
1091
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 /* Check for a __slots__ sequence variable in dict, and count it */
1093 slots = PyDict_GetItemString(dict, "__slots__");
1094 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001095 add_dict = 0;
1096 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001097 if (slots != NULL) {
1098 /* Make it into a tuple */
1099 if (PyString_Check(slots))
1100 slots = Py_BuildValue("(O)", slots);
1101 else
1102 slots = PySequence_Tuple(slots);
1103 if (slots == NULL)
1104 return NULL;
1105 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001106 if (nslots > 0 && base->tp_itemsize != 0) {
1107 PyErr_Format(PyExc_TypeError,
1108 "nonempty __slots__ "
1109 "not supported for subtype of '%s'",
1110 base->tp_name);
1111 return NULL;
1112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001114 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115 Py_DECREF(slots);
1116 return NULL;
1117 }
1118 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001119
1120 newslots = PyTuple_New(nslots);
1121 if (newslots == NULL)
1122 return NULL;
1123 for (i = 0; i < nslots; i++) {
1124 tmp = PyTuple_GET_ITEM(slots, i);
1125 if (_Py_Mangle(PyString_AS_STRING(name),
1126 PyString_AS_STRING(tmp),
1127 buffer, sizeof(buffer)))
1128 {
1129 tmp = PyString_FromString(buffer);
1130 } else {
1131 Py_INCREF(tmp);
1132 }
1133 PyTuple_SET_ITEM(newslots, i, tmp);
1134 }
1135 Py_DECREF(slots);
1136 slots = newslots;
1137
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001139 if (slots != NULL) {
1140 /* See if *this* class defines __getstate__ */
1141 PyObject *getstate = PyDict_GetItemString(dict,
1142 "__getstate__");
1143 if (getstate == NULL) {
1144 /* If not, provide a bozo that raises TypeError */
1145 if (bozo_obj == NULL) {
1146 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1147 if (bozo_obj == NULL) {
1148 /* XXX decref various things */
1149 return NULL;
1150 }
1151 }
1152 if (PyDict_SetItemString(dict,
1153 "__getstate__",
1154 bozo_obj) < 0) {
1155 /* XXX decref various things */
1156 return NULL;
1157 }
1158 }
1159 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160 if (slots == NULL && base->tp_dictoffset == 0 &&
1161 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001162 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001163 add_dict++;
1164 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001165 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1166 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001167 nslots++;
1168 add_weak++;
1169 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170
1171 /* XXX From here until type is safely allocated,
1172 "return NULL" may leak slots! */
1173
1174 /* Allocate the type object */
1175 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1176 if (type == NULL)
1177 return NULL;
1178
1179 /* Keep name and slots alive in the extended type object */
1180 et = (etype *)type;
1181 Py_INCREF(name);
1182 et->name = name;
1183 et->slots = slots;
1184
Guido van Rossumdc91b992001-08-08 22:26:22 +00001185 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001186 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1187 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001188 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1189 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001190
1191 /* It's a new-style number unless it specifically inherits any
1192 old-style numeric behavior */
1193 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1194 (base->tp_as_number == NULL))
1195 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1196
1197 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001198 type->tp_as_number = &et->as_number;
1199 type->tp_as_sequence = &et->as_sequence;
1200 type->tp_as_mapping = &et->as_mapping;
1201 type->tp_as_buffer = &et->as_buffer;
1202 type->tp_name = PyString_AS_STRING(name);
1203
1204 /* Set tp_base and tp_bases */
1205 type->tp_bases = bases;
1206 Py_INCREF(base);
1207 type->tp_base = base;
1208
Guido van Rossum687ae002001-10-15 22:03:32 +00001209 /* Initialize tp_dict from passed-in dict */
1210 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 if (dict == NULL) {
1212 Py_DECREF(type);
1213 return NULL;
1214 }
1215
Guido van Rossumc3542212001-08-16 09:18:56 +00001216 /* Set __module__ in the dict */
1217 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1218 tmp = PyEval_GetGlobals();
1219 if (tmp != NULL) {
1220 tmp = PyDict_GetItemString(tmp, "__name__");
1221 if (tmp != NULL) {
1222 if (PyDict_SetItemString(dict, "__module__",
1223 tmp) < 0)
1224 return NULL;
1225 }
1226 }
1227 }
1228
Tim Peters2f93e282001-10-04 05:27:00 +00001229 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001230 and is a string. The __doc__ accessor will first look for tp_doc;
1231 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001232 */
1233 {
1234 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1235 if (doc != NULL && PyString_Check(doc)) {
1236 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001237 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001238 if (type->tp_doc == NULL) {
1239 Py_DECREF(type);
1240 return NULL;
1241 }
1242 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1243 }
1244 }
1245
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 /* Special-case __new__: if it's a plain function,
1247 make it a static function */
1248 tmp = PyDict_GetItemString(dict, "__new__");
1249 if (tmp != NULL && PyFunction_Check(tmp)) {
1250 tmp = PyStaticMethod_New(tmp);
1251 if (tmp == NULL) {
1252 Py_DECREF(type);
1253 return NULL;
1254 }
1255 PyDict_SetItemString(dict, "__new__", tmp);
1256 Py_DECREF(tmp);
1257 }
1258
1259 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1260 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001261 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262 if (slots != NULL) {
1263 for (i = 0; i < nslots; i++, mp++) {
1264 mp->name = PyString_AS_STRING(
1265 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001266 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001268 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001269 strcmp(mp->name, "__weakref__") == 0) {
1270 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001271 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001272 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001273 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274 slotoffset += sizeof(PyObject *);
1275 }
1276 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001277 else {
1278 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001279 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001280 type->tp_dictoffset =
1281 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001282 else
1283 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001284 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001285 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001286 }
1287 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001288 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001289 type->tp_weaklistoffset = slotoffset;
1290 mp->name = "__weakref__";
1291 mp->type = T_OBJECT;
1292 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001293 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001294 mp++;
1295 slotoffset += sizeof(PyObject *);
1296 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297 }
1298 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001299 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001300 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301
1302 /* Special case some slots */
1303 if (type->tp_dictoffset != 0 || nslots > 0) {
1304 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1305 type->tp_getattro = PyObject_GenericGetAttr;
1306 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1307 type->tp_setattro = PyObject_GenericSetAttr;
1308 }
1309 type->tp_dealloc = subtype_dealloc;
1310
Guido van Rossum9475a232001-10-05 20:51:39 +00001311 /* Enable GC unless there are really no instance variables possible */
1312 if (!(type->tp_basicsize == sizeof(PyObject) &&
1313 type->tp_itemsize == 0))
1314 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1315
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 /* Always override allocation strategy to use regular heap */
1317 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001318 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001319 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001320 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001321 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001322 }
1323 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001324 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325
1326 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001327 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001328 Py_DECREF(type);
1329 return NULL;
1330 }
1331
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001332 /* Put the proper slots in place */
1333 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001334
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 return (PyObject *)type;
1336}
1337
1338/* Internal API to look for a name through the MRO.
1339 This returns a borrowed reference, and doesn't set an exception! */
1340PyObject *
1341_PyType_Lookup(PyTypeObject *type, PyObject *name)
1342{
1343 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001344 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345
Guido van Rossum687ae002001-10-15 22:03:32 +00001346 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001348
1349 /* If mro is NULL, the type is either not yet initialized
1350 by PyType_Ready(), or already cleared by type_clear().
1351 Either way the safest thing to do is to return NULL. */
1352 if (mro == NULL)
1353 return NULL;
1354
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355 assert(PyTuple_Check(mro));
1356 n = PyTuple_GET_SIZE(mro);
1357 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001358 base = PyTuple_GET_ITEM(mro, i);
1359 if (PyClass_Check(base))
1360 dict = ((PyClassObject *)base)->cl_dict;
1361 else {
1362 assert(PyType_Check(base));
1363 dict = ((PyTypeObject *)base)->tp_dict;
1364 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001365 assert(dict && PyDict_Check(dict));
1366 res = PyDict_GetItem(dict, name);
1367 if (res != NULL)
1368 return res;
1369 }
1370 return NULL;
1371}
1372
1373/* This is similar to PyObject_GenericGetAttr(),
1374 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1375static PyObject *
1376type_getattro(PyTypeObject *type, PyObject *name)
1377{
1378 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001379 PyObject *meta_attribute, *attribute;
1380 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381
1382 /* Initialize this type (we'll assume the metatype is initialized) */
1383 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001384 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 return NULL;
1386 }
1387
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001388 /* No readable descriptor found yet */
1389 meta_get = NULL;
1390
1391 /* Look for the attribute in the metatype */
1392 meta_attribute = _PyType_Lookup(metatype, name);
1393
1394 if (meta_attribute != NULL) {
1395 meta_get = meta_attribute->ob_type->tp_descr_get;
1396
1397 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1398 /* Data descriptors implement tp_descr_set to intercept
1399 * writes. Assume the attribute is not overridden in
1400 * type's tp_dict (and bases): call the descriptor now.
1401 */
1402 return meta_get(meta_attribute, (PyObject *)type,
1403 (PyObject *)metatype);
1404 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405 }
1406
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001407 /* No data descriptor found on metatype. Look in tp_dict of this
1408 * type and its bases */
1409 attribute = _PyType_Lookup(type, name);
1410 if (attribute != NULL) {
1411 /* Implement descriptor functionality, if any */
1412 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1413 if (local_get != NULL) {
1414 /* NULL 2nd argument indicates the descriptor was
1415 * found on the target object itself (or a base) */
1416 return local_get(attribute, (PyObject *)NULL,
1417 (PyObject *)type);
1418 }
1419
1420 Py_INCREF(attribute);
1421 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422 }
1423
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001424 /* No attribute found in local __dict__ (or bases): use the
1425 * descriptor from the metatype, if any */
1426 if (meta_get != NULL)
1427 return meta_get(meta_attribute, (PyObject *)type,
1428 (PyObject *)metatype);
1429
1430 /* If an ordinary attribute was found on the metatype, return it now */
1431 if (meta_attribute != NULL) {
1432 Py_INCREF(meta_attribute);
1433 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434 }
1435
1436 /* Give up */
1437 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001438 "type object '%.50s' has no attribute '%.400s'",
1439 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 return NULL;
1441}
1442
1443static int
1444type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1445{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001446 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1447 PyErr_Format(
1448 PyExc_TypeError,
1449 "can't set attributes of built-in/extension type '%s'",
1450 type->tp_name);
1451 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001452 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001453 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1454 return -1;
1455 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001456}
1457
1458static void
1459type_dealloc(PyTypeObject *type)
1460{
1461 etype *et;
1462
1463 /* Assert this is a heap-allocated type object */
1464 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001465 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001466 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467 et = (etype *)type;
1468 Py_XDECREF(type->tp_base);
1469 Py_XDECREF(type->tp_dict);
1470 Py_XDECREF(type->tp_bases);
1471 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001472 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001473 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474 Py_XDECREF(et->name);
1475 Py_XDECREF(et->slots);
1476 type->ob_type->tp_free((PyObject *)type);
1477}
1478
Guido van Rossum1c450732001-10-08 15:18:27 +00001479static PyObject *
1480type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1481{
1482 PyObject *list, *raw, *ref;
1483 int i, n;
1484
1485 list = PyList_New(0);
1486 if (list == NULL)
1487 return NULL;
1488 raw = type->tp_subclasses;
1489 if (raw == NULL)
1490 return list;
1491 assert(PyList_Check(raw));
1492 n = PyList_GET_SIZE(raw);
1493 for (i = 0; i < n; i++) {
1494 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001495 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001496 ref = PyWeakref_GET_OBJECT(ref);
1497 if (ref != Py_None) {
1498 if (PyList_Append(list, ref) < 0) {
1499 Py_DECREF(list);
1500 return NULL;
1501 }
1502 }
1503 }
1504 return list;
1505}
1506
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001508 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001510 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1511 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001512 {0}
1513};
1514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001515PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001517"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518
Guido van Rossum048eb752001-10-02 21:24:57 +00001519static int
1520type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1521{
Guido van Rossum048eb752001-10-02 21:24:57 +00001522 int err;
1523
Guido van Rossuma3862092002-06-10 15:24:42 +00001524 /* Because of type_is_gc(), the collector only calls this
1525 for heaptypes. */
1526 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001527
1528#define VISIT(SLOT) \
1529 if (SLOT) { \
1530 err = visit((PyObject *)(SLOT), arg); \
1531 if (err) \
1532 return err; \
1533 }
1534
1535 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001536 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001537 VISIT(type->tp_mro);
1538 VISIT(type->tp_bases);
1539 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001540
1541 /* There's no need to visit type->tp_subclasses or
1542 ((etype *)type)->slots, because they can't be involved
1543 in cycles; tp_subclasses is a list of weak references,
1544 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001545
1546#undef VISIT
1547
1548 return 0;
1549}
1550
1551static int
1552type_clear(PyTypeObject *type)
1553{
Guido van Rossum048eb752001-10-02 21:24:57 +00001554 PyObject *tmp;
1555
Guido van Rossuma3862092002-06-10 15:24:42 +00001556 /* Because of type_is_gc(), the collector only calls this
1557 for heaptypes. */
1558 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001559
1560#define CLEAR(SLOT) \
1561 if (SLOT) { \
1562 tmp = (PyObject *)(SLOT); \
1563 SLOT = NULL; \
1564 Py_DECREF(tmp); \
1565 }
1566
Guido van Rossuma3862092002-06-10 15:24:42 +00001567 /* The only field we need to clear is tp_mro, which is part of a
1568 hard cycle (its first element is the class itself) that won't
1569 be broken otherwise (it's a tuple and tuples don't have a
1570 tp_clear handler). None of the other fields need to be
1571 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001572
Guido van Rossuma3862092002-06-10 15:24:42 +00001573 tp_dict:
1574 It is a dict, so the collector will call its tp_clear.
1575
1576 tp_cache:
1577 Not used; if it were, it would be a dict.
1578
1579 tp_bases, tp_base:
1580 If these are involved in a cycle, there must be at least
1581 one other, mutable object in the cycle, e.g. a base
1582 class's dict; the cycle will be broken that way.
1583
1584 tp_subclasses:
1585 A list of weak references can't be part of a cycle; and
1586 lists have their own tp_clear.
1587
1588 slots (in etype):
1589 A tuple of strings can't be part of a cycle.
1590 */
1591
1592 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001593
Guido van Rossum048eb752001-10-02 21:24:57 +00001594#undef CLEAR
1595
1596 return 0;
1597}
1598
1599static int
1600type_is_gc(PyTypeObject *type)
1601{
1602 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1603}
1604
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001605PyTypeObject PyType_Type = {
1606 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 0, /* ob_size */
1608 "type", /* tp_name */
1609 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001610 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611 (destructor)type_dealloc, /* tp_dealloc */
1612 0, /* tp_print */
1613 0, /* tp_getattr */
1614 0, /* tp_setattr */
1615 type_compare, /* tp_compare */
1616 (reprfunc)type_repr, /* tp_repr */
1617 0, /* tp_as_number */
1618 0, /* tp_as_sequence */
1619 0, /* tp_as_mapping */
1620 (hashfunc)_Py_HashPointer, /* tp_hash */
1621 (ternaryfunc)type_call, /* tp_call */
1622 0, /* tp_str */
1623 (getattrofunc)type_getattro, /* tp_getattro */
1624 (setattrofunc)type_setattro, /* tp_setattro */
1625 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001626 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1627 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001629 (traverseproc)type_traverse, /* tp_traverse */
1630 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001632 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001633 0, /* tp_iter */
1634 0, /* tp_iternext */
1635 type_methods, /* tp_methods */
1636 type_members, /* tp_members */
1637 type_getsets, /* tp_getset */
1638 0, /* tp_base */
1639 0, /* tp_dict */
1640 0, /* tp_descr_get */
1641 0, /* tp_descr_set */
1642 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1643 0, /* tp_init */
1644 0, /* tp_alloc */
1645 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001646 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001647 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001648};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649
1650
1651/* The base type of all types (eventually)... except itself. */
1652
1653static int
1654object_init(PyObject *self, PyObject *args, PyObject *kwds)
1655{
1656 return 0;
1657}
1658
1659static void
1660object_dealloc(PyObject *self)
1661{
1662 self->ob_type->tp_free(self);
1663}
1664
Guido van Rossum8e248182001-08-12 05:17:56 +00001665static PyObject *
1666object_repr(PyObject *self)
1667{
Guido van Rossum76e69632001-08-16 18:52:43 +00001668 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001669 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001670
Guido van Rossum76e69632001-08-16 18:52:43 +00001671 type = self->ob_type;
1672 mod = type_module(type, NULL);
1673 if (mod == NULL)
1674 PyErr_Clear();
1675 else if (!PyString_Check(mod)) {
1676 Py_DECREF(mod);
1677 mod = NULL;
1678 }
1679 name = type_name(type, NULL);
1680 if (name == NULL)
1681 return NULL;
1682 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001683 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001684 PyString_AS_STRING(mod),
1685 PyString_AS_STRING(name),
1686 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001687 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001688 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001689 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001690 Py_XDECREF(mod);
1691 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001692 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001693}
1694
Guido van Rossumb8f63662001-08-15 23:57:02 +00001695static PyObject *
1696object_str(PyObject *self)
1697{
1698 unaryfunc f;
1699
1700 f = self->ob_type->tp_repr;
1701 if (f == NULL)
1702 f = object_repr;
1703 return f(self);
1704}
1705
Guido van Rossum8e248182001-08-12 05:17:56 +00001706static long
1707object_hash(PyObject *self)
1708{
1709 return _Py_HashPointer(self);
1710}
Guido van Rossum8e248182001-08-12 05:17:56 +00001711
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001712static PyObject *
1713object_get_class(PyObject *self, void *closure)
1714{
1715 Py_INCREF(self->ob_type);
1716 return (PyObject *)(self->ob_type);
1717}
1718
1719static int
1720equiv_structs(PyTypeObject *a, PyTypeObject *b)
1721{
1722 return a == b ||
1723 (a != NULL &&
1724 b != NULL &&
1725 a->tp_basicsize == b->tp_basicsize &&
1726 a->tp_itemsize == b->tp_itemsize &&
1727 a->tp_dictoffset == b->tp_dictoffset &&
1728 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1729 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1730 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1731}
1732
1733static int
1734same_slots_added(PyTypeObject *a, PyTypeObject *b)
1735{
1736 PyTypeObject *base = a->tp_base;
1737 int size;
1738
1739 if (base != b->tp_base)
1740 return 0;
1741 if (equiv_structs(a, base) && equiv_structs(b, base))
1742 return 1;
1743 size = base->tp_basicsize;
1744 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1745 size += sizeof(PyObject *);
1746 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1747 size += sizeof(PyObject *);
1748 return size == a->tp_basicsize && size == b->tp_basicsize;
1749}
1750
1751static int
1752object_set_class(PyObject *self, PyObject *value, void *closure)
1753{
1754 PyTypeObject *old = self->ob_type;
1755 PyTypeObject *new, *newbase, *oldbase;
1756
Guido van Rossumb6b89422002-04-15 01:03:30 +00001757 if (value == NULL) {
1758 PyErr_SetString(PyExc_TypeError,
1759 "can't delete __class__ attribute");
1760 return -1;
1761 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001762 if (!PyType_Check(value)) {
1763 PyErr_Format(PyExc_TypeError,
1764 "__class__ must be set to new-style class, not '%s' object",
1765 value->ob_type->tp_name);
1766 return -1;
1767 }
1768 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001769 if (new->tp_dealloc != old->tp_dealloc ||
1770 new->tp_free != old->tp_free)
1771 {
1772 PyErr_Format(PyExc_TypeError,
1773 "__class__ assignment: "
1774 "'%s' deallocator differs from '%s'",
1775 new->tp_name,
1776 old->tp_name);
1777 return -1;
1778 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001779 newbase = new;
1780 oldbase = old;
1781 while (equiv_structs(newbase, newbase->tp_base))
1782 newbase = newbase->tp_base;
1783 while (equiv_structs(oldbase, oldbase->tp_base))
1784 oldbase = oldbase->tp_base;
1785 if (newbase != oldbase &&
1786 (newbase->tp_base != oldbase->tp_base ||
1787 !same_slots_added(newbase, oldbase))) {
1788 PyErr_Format(PyExc_TypeError,
1789 "__class__ assignment: "
1790 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001791 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001792 old->tp_name);
1793 return -1;
1794 }
1795 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1796 Py_INCREF(new);
1797 }
1798 self->ob_type = new;
1799 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1800 Py_DECREF(old);
1801 }
1802 return 0;
1803}
1804
1805static PyGetSetDef object_getsets[] = {
1806 {"__class__", object_get_class, object_set_class,
1807 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808 {0}
1809};
1810
Guido van Rossum3926a632001-09-25 16:25:58 +00001811static PyObject *
1812object_reduce(PyObject *self, PyObject *args)
1813{
1814 /* Call copy_reg._reduce(self) */
1815 static PyObject *copy_reg_str;
1816 PyObject *copy_reg, *res;
1817
1818 if (!copy_reg_str) {
1819 copy_reg_str = PyString_InternFromString("copy_reg");
1820 if (copy_reg_str == NULL)
1821 return NULL;
1822 }
1823 copy_reg = PyImport_Import(copy_reg_str);
1824 if (!copy_reg)
1825 return NULL;
1826 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1827 Py_DECREF(copy_reg);
1828 return res;
1829}
1830
1831static PyMethodDef object_methods[] = {
1832 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1833 {0}
1834};
1835
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836PyTypeObject PyBaseObject_Type = {
1837 PyObject_HEAD_INIT(&PyType_Type)
1838 0, /* ob_size */
1839 "object", /* tp_name */
1840 sizeof(PyObject), /* tp_basicsize */
1841 0, /* tp_itemsize */
1842 (destructor)object_dealloc, /* tp_dealloc */
1843 0, /* tp_print */
1844 0, /* tp_getattr */
1845 0, /* tp_setattr */
1846 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001847 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 0, /* tp_as_number */
1849 0, /* tp_as_sequence */
1850 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001851 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001853 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001854 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001855 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856 0, /* tp_as_buffer */
1857 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1858 "The most base type", /* tp_doc */
1859 0, /* tp_traverse */
1860 0, /* tp_clear */
1861 0, /* tp_richcompare */
1862 0, /* tp_weaklistoffset */
1863 0, /* tp_iter */
1864 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001865 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001866 0, /* tp_members */
1867 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868 0, /* tp_base */
1869 0, /* tp_dict */
1870 0, /* tp_descr_get */
1871 0, /* tp_descr_set */
1872 0, /* tp_dictoffset */
1873 object_init, /* tp_init */
1874 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001875 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001876 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877};
1878
1879
1880/* Initialize the __dict__ in a type object */
1881
Fred Drake7bf97152002-03-28 05:33:33 +00001882static PyObject *
1883create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1884{
1885 PyObject *cfunc;
1886 PyObject *result;
1887
1888 cfunc = PyCFunction_New(meth, NULL);
1889 if (cfunc == NULL)
1890 return NULL;
1891 result = func(cfunc);
1892 Py_DECREF(cfunc);
1893 return result;
1894}
1895
Tim Peters6d6c1a32001-08-02 04:15:00 +00001896static int
1897add_methods(PyTypeObject *type, PyMethodDef *meth)
1898{
Guido van Rossum687ae002001-10-15 22:03:32 +00001899 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001900
1901 for (; meth->ml_name != NULL; meth++) {
1902 PyObject *descr;
1903 if (PyDict_GetItemString(dict, meth->ml_name))
1904 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001905 if (meth->ml_flags & METH_CLASS) {
1906 if (meth->ml_flags & METH_STATIC) {
1907 PyErr_SetString(PyExc_ValueError,
1908 "method cannot be both class and static");
1909 return -1;
1910 }
1911 descr = create_specialmethod(meth, PyClassMethod_New);
1912 }
1913 else if (meth->ml_flags & METH_STATIC) {
1914 descr = create_specialmethod(meth, PyStaticMethod_New);
1915 }
1916 else {
1917 descr = PyDescr_NewMethod(type, meth);
1918 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001919 if (descr == NULL)
1920 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001921 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 return -1;
1923 Py_DECREF(descr);
1924 }
1925 return 0;
1926}
1927
1928static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001929add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930{
Guido van Rossum687ae002001-10-15 22:03:32 +00001931 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932
1933 for (; memb->name != NULL; memb++) {
1934 PyObject *descr;
1935 if (PyDict_GetItemString(dict, memb->name))
1936 continue;
1937 descr = PyDescr_NewMember(type, memb);
1938 if (descr == NULL)
1939 return -1;
1940 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1941 return -1;
1942 Py_DECREF(descr);
1943 }
1944 return 0;
1945}
1946
1947static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001948add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949{
Guido van Rossum687ae002001-10-15 22:03:32 +00001950 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951
1952 for (; gsp->name != NULL; gsp++) {
1953 PyObject *descr;
1954 if (PyDict_GetItemString(dict, gsp->name))
1955 continue;
1956 descr = PyDescr_NewGetSet(type, gsp);
1957
1958 if (descr == NULL)
1959 return -1;
1960 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1961 return -1;
1962 Py_DECREF(descr);
1963 }
1964 return 0;
1965}
1966
Guido van Rossum13d52f02001-08-10 21:24:08 +00001967static void
1968inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969{
1970 int oldsize, newsize;
1971
Guido van Rossum13d52f02001-08-10 21:24:08 +00001972 /* Special flag magic */
1973 if (!type->tp_as_buffer && base->tp_as_buffer) {
1974 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1975 type->tp_flags |=
1976 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1977 }
1978 if (!type->tp_as_sequence && base->tp_as_sequence) {
1979 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1980 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1981 }
1982 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1983 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1984 if ((!type->tp_as_number && base->tp_as_number) ||
1985 (!type->tp_as_sequence && base->tp_as_sequence)) {
1986 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1987 if (!type->tp_as_number && !type->tp_as_sequence) {
1988 type->tp_flags |= base->tp_flags &
1989 Py_TPFLAGS_HAVE_INPLACEOPS;
1990 }
1991 }
1992 /* Wow */
1993 }
1994 if (!type->tp_as_number && base->tp_as_number) {
1995 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1996 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1997 }
1998
1999 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002000 oldsize = base->tp_basicsize;
2001 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2002 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2003 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002004 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2005 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002006 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002007 if (type->tp_traverse == NULL)
2008 type->tp_traverse = base->tp_traverse;
2009 if (type->tp_clear == NULL)
2010 type->tp_clear = base->tp_clear;
2011 }
2012 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002013 /* The condition below could use some explanation.
2014 It appears that tp_new is not inherited for static types
2015 whose base class is 'object'; this seems to be a precaution
2016 so that old extension types don't suddenly become
2017 callable (object.__new__ wouldn't insure the invariants
2018 that the extension type's own factory function ensures).
2019 Heap types, of course, are under our control, so they do
2020 inherit tp_new; static extension types that specify some
2021 other built-in type as the default are considered
2022 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002023 if (base != &PyBaseObject_Type ||
2024 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2025 if (type->tp_new == NULL)
2026 type->tp_new = base->tp_new;
2027 }
2028 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002029 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002030
2031 /* Copy other non-function slots */
2032
2033#undef COPYVAL
2034#define COPYVAL(SLOT) \
2035 if (type->SLOT == 0) type->SLOT = base->SLOT
2036
2037 COPYVAL(tp_itemsize);
2038 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2039 COPYVAL(tp_weaklistoffset);
2040 }
2041 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2042 COPYVAL(tp_dictoffset);
2043 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002044}
2045
2046static void
2047inherit_slots(PyTypeObject *type, PyTypeObject *base)
2048{
2049 PyTypeObject *basebase;
2050
2051#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052#undef COPYSLOT
2053#undef COPYNUM
2054#undef COPYSEQ
2055#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002056#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002057
2058#define SLOTDEFINED(SLOT) \
2059 (base->SLOT != 0 && \
2060 (basebase == NULL || base->SLOT != basebase->SLOT))
2061
Tim Peters6d6c1a32001-08-02 04:15:00 +00002062#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002063 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064
2065#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2066#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2067#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002068#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002069
Guido van Rossum13d52f02001-08-10 21:24:08 +00002070 /* This won't inherit indirect slots (from tp_as_number etc.)
2071 if type doesn't provide the space. */
2072
2073 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2074 basebase = base->tp_base;
2075 if (basebase->tp_as_number == NULL)
2076 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077 COPYNUM(nb_add);
2078 COPYNUM(nb_subtract);
2079 COPYNUM(nb_multiply);
2080 COPYNUM(nb_divide);
2081 COPYNUM(nb_remainder);
2082 COPYNUM(nb_divmod);
2083 COPYNUM(nb_power);
2084 COPYNUM(nb_negative);
2085 COPYNUM(nb_positive);
2086 COPYNUM(nb_absolute);
2087 COPYNUM(nb_nonzero);
2088 COPYNUM(nb_invert);
2089 COPYNUM(nb_lshift);
2090 COPYNUM(nb_rshift);
2091 COPYNUM(nb_and);
2092 COPYNUM(nb_xor);
2093 COPYNUM(nb_or);
2094 COPYNUM(nb_coerce);
2095 COPYNUM(nb_int);
2096 COPYNUM(nb_long);
2097 COPYNUM(nb_float);
2098 COPYNUM(nb_oct);
2099 COPYNUM(nb_hex);
2100 COPYNUM(nb_inplace_add);
2101 COPYNUM(nb_inplace_subtract);
2102 COPYNUM(nb_inplace_multiply);
2103 COPYNUM(nb_inplace_divide);
2104 COPYNUM(nb_inplace_remainder);
2105 COPYNUM(nb_inplace_power);
2106 COPYNUM(nb_inplace_lshift);
2107 COPYNUM(nb_inplace_rshift);
2108 COPYNUM(nb_inplace_and);
2109 COPYNUM(nb_inplace_xor);
2110 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002111 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2112 COPYNUM(nb_true_divide);
2113 COPYNUM(nb_floor_divide);
2114 COPYNUM(nb_inplace_true_divide);
2115 COPYNUM(nb_inplace_floor_divide);
2116 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002117 }
2118
Guido van Rossum13d52f02001-08-10 21:24:08 +00002119 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2120 basebase = base->tp_base;
2121 if (basebase->tp_as_sequence == NULL)
2122 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002123 COPYSEQ(sq_length);
2124 COPYSEQ(sq_concat);
2125 COPYSEQ(sq_repeat);
2126 COPYSEQ(sq_item);
2127 COPYSEQ(sq_slice);
2128 COPYSEQ(sq_ass_item);
2129 COPYSEQ(sq_ass_slice);
2130 COPYSEQ(sq_contains);
2131 COPYSEQ(sq_inplace_concat);
2132 COPYSEQ(sq_inplace_repeat);
2133 }
2134
Guido van Rossum13d52f02001-08-10 21:24:08 +00002135 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2136 basebase = base->tp_base;
2137 if (basebase->tp_as_mapping == NULL)
2138 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002139 COPYMAP(mp_length);
2140 COPYMAP(mp_subscript);
2141 COPYMAP(mp_ass_subscript);
2142 }
2143
Tim Petersfc57ccb2001-10-12 02:38:24 +00002144 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2145 basebase = base->tp_base;
2146 if (basebase->tp_as_buffer == NULL)
2147 basebase = NULL;
2148 COPYBUF(bf_getreadbuffer);
2149 COPYBUF(bf_getwritebuffer);
2150 COPYBUF(bf_getsegcount);
2151 COPYBUF(bf_getcharbuffer);
2152 }
2153
Guido van Rossum13d52f02001-08-10 21:24:08 +00002154 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002155
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156 COPYSLOT(tp_dealloc);
2157 COPYSLOT(tp_print);
2158 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2159 type->tp_getattr = base->tp_getattr;
2160 type->tp_getattro = base->tp_getattro;
2161 }
2162 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2163 type->tp_setattr = base->tp_setattr;
2164 type->tp_setattro = base->tp_setattro;
2165 }
2166 /* tp_compare see tp_richcompare */
2167 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002168 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002169 COPYSLOT(tp_call);
2170 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002171 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002172 if (type->tp_compare == NULL &&
2173 type->tp_richcompare == NULL &&
2174 type->tp_hash == NULL)
2175 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176 type->tp_compare = base->tp_compare;
2177 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002178 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002179 }
2180 }
2181 else {
2182 COPYSLOT(tp_compare);
2183 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2185 COPYSLOT(tp_iter);
2186 COPYSLOT(tp_iternext);
2187 }
2188 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2189 COPYSLOT(tp_descr_get);
2190 COPYSLOT(tp_descr_set);
2191 COPYSLOT(tp_dictoffset);
2192 COPYSLOT(tp_init);
2193 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002194 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002195 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197}
2198
Guido van Rossum13d52f02001-08-10 21:24:08 +00002199staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002200staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002201
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002203PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002205 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002206 PyTypeObject *base;
2207 int i, n;
2208
Guido van Rossumcab05802002-06-10 15:29:03 +00002209 if (type->tp_flags & Py_TPFLAGS_READY) {
2210 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002211 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002212 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002213 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002214
2215 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002216
2217 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2218 base = type->tp_base;
2219 if (base == NULL && type != &PyBaseObject_Type)
2220 base = type->tp_base = &PyBaseObject_Type;
2221
Guido van Rossum0986d822002-04-08 01:38:42 +00002222 /* Initialize ob_type if NULL. This means extensions that want to be
2223 compilable separately on Windows can call PyType_Ready() instead of
2224 initializing the ob_type field of their type objects. */
2225 if (type->ob_type == NULL)
2226 type->ob_type = base->ob_type;
2227
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228 /* Initialize tp_bases */
2229 bases = type->tp_bases;
2230 if (bases == NULL) {
2231 if (base == NULL)
2232 bases = PyTuple_New(0);
2233 else
2234 bases = Py_BuildValue("(O)", base);
2235 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002236 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237 type->tp_bases = bases;
2238 }
2239
2240 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002241 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002242 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002243 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244 }
2245
Guido van Rossum687ae002001-10-15 22:03:32 +00002246 /* Initialize tp_dict */
2247 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002248 if (dict == NULL) {
2249 dict = PyDict_New();
2250 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002251 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002252 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253 }
2254
Guido van Rossum687ae002001-10-15 22:03:32 +00002255 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002256 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002257 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258 if (type->tp_methods != NULL) {
2259 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002260 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002261 }
2262 if (type->tp_members != NULL) {
2263 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002264 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002265 }
2266 if (type->tp_getset != NULL) {
2267 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002268 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269 }
2270
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 /* Calculate method resolution order */
2272 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002273 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274 }
2275
Guido van Rossum13d52f02001-08-10 21:24:08 +00002276 /* Inherit special flags from dominant base */
2277 if (type->tp_base != NULL)
2278 inherit_special(type, type->tp_base);
2279
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002281 bases = type->tp_mro;
2282 assert(bases != NULL);
2283 assert(PyTuple_Check(bases));
2284 n = PyTuple_GET_SIZE(bases);
2285 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002286 PyObject *b = PyTuple_GET_ITEM(bases, i);
2287 if (PyType_Check(b))
2288 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002289 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002291 /* if the type dictionary doesn't contain a __doc__, set it from
2292 the tp_doc slot.
2293 */
2294 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2295 if (type->tp_doc != NULL) {
2296 PyObject *doc = PyString_FromString(type->tp_doc);
2297 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2298 Py_DECREF(doc);
2299 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002300 PyDict_SetItemString(type->tp_dict,
2301 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002302 }
2303 }
2304
Guido van Rossum13d52f02001-08-10 21:24:08 +00002305 /* Some more special stuff */
2306 base = type->tp_base;
2307 if (base != NULL) {
2308 if (type->tp_as_number == NULL)
2309 type->tp_as_number = base->tp_as_number;
2310 if (type->tp_as_sequence == NULL)
2311 type->tp_as_sequence = base->tp_as_sequence;
2312 if (type->tp_as_mapping == NULL)
2313 type->tp_as_mapping = base->tp_as_mapping;
2314 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315
Guido van Rossum1c450732001-10-08 15:18:27 +00002316 /* Link into each base class's list of subclasses */
2317 bases = type->tp_bases;
2318 n = PyTuple_GET_SIZE(bases);
2319 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002320 PyObject *b = PyTuple_GET_ITEM(bases, i);
2321 if (PyType_Check(b) &&
2322 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002323 goto error;
2324 }
2325
Guido van Rossum13d52f02001-08-10 21:24:08 +00002326 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002327 assert(type->tp_dict != NULL);
2328 type->tp_flags =
2329 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002331
2332 error:
2333 type->tp_flags &= ~Py_TPFLAGS_READYING;
2334 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335}
2336
Guido van Rossum1c450732001-10-08 15:18:27 +00002337static int
2338add_subclass(PyTypeObject *base, PyTypeObject *type)
2339{
2340 int i;
2341 PyObject *list, *ref, *new;
2342
2343 list = base->tp_subclasses;
2344 if (list == NULL) {
2345 base->tp_subclasses = list = PyList_New(0);
2346 if (list == NULL)
2347 return -1;
2348 }
2349 assert(PyList_Check(list));
2350 new = PyWeakref_NewRef((PyObject *)type, NULL);
2351 i = PyList_GET_SIZE(list);
2352 while (--i >= 0) {
2353 ref = PyList_GET_ITEM(list, i);
2354 assert(PyWeakref_CheckRef(ref));
2355 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2356 return PyList_SetItem(list, i, new);
2357 }
2358 i = PyList_Append(list, new);
2359 Py_DECREF(new);
2360 return i;
2361}
2362
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363
2364/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2365
2366/* There's a wrapper *function* for each distinct function typedef used
2367 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2368 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2369 Most tables have only one entry; the tables for binary operators have two
2370 entries, one regular and one with reversed arguments. */
2371
2372static PyObject *
2373wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2374{
2375 inquiry func = (inquiry)wrapped;
2376 int res;
2377
2378 if (!PyArg_ParseTuple(args, ""))
2379 return NULL;
2380 res = (*func)(self);
2381 if (res == -1 && PyErr_Occurred())
2382 return NULL;
2383 return PyInt_FromLong((long)res);
2384}
2385
Tim Peters6d6c1a32001-08-02 04:15:00 +00002386static PyObject *
2387wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2388{
2389 binaryfunc func = (binaryfunc)wrapped;
2390 PyObject *other;
2391
2392 if (!PyArg_ParseTuple(args, "O", &other))
2393 return NULL;
2394 return (*func)(self, other);
2395}
2396
2397static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002398wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2399{
2400 binaryfunc func = (binaryfunc)wrapped;
2401 PyObject *other;
2402
2403 if (!PyArg_ParseTuple(args, "O", &other))
2404 return NULL;
2405 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002406 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002407 Py_INCREF(Py_NotImplemented);
2408 return Py_NotImplemented;
2409 }
2410 return (*func)(self, other);
2411}
2412
2413static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002414wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2415{
2416 binaryfunc func = (binaryfunc)wrapped;
2417 PyObject *other;
2418
2419 if (!PyArg_ParseTuple(args, "O", &other))
2420 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002421 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002422 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002423 Py_INCREF(Py_NotImplemented);
2424 return Py_NotImplemented;
2425 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002426 return (*func)(other, self);
2427}
2428
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002429static PyObject *
2430wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2431{
2432 coercion func = (coercion)wrapped;
2433 PyObject *other, *res;
2434 int ok;
2435
2436 if (!PyArg_ParseTuple(args, "O", &other))
2437 return NULL;
2438 ok = func(&self, &other);
2439 if (ok < 0)
2440 return NULL;
2441 if (ok > 0) {
2442 Py_INCREF(Py_NotImplemented);
2443 return Py_NotImplemented;
2444 }
2445 res = PyTuple_New(2);
2446 if (res == NULL) {
2447 Py_DECREF(self);
2448 Py_DECREF(other);
2449 return NULL;
2450 }
2451 PyTuple_SET_ITEM(res, 0, self);
2452 PyTuple_SET_ITEM(res, 1, other);
2453 return res;
2454}
2455
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456static PyObject *
2457wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2458{
2459 ternaryfunc func = (ternaryfunc)wrapped;
2460 PyObject *other;
2461 PyObject *third = Py_None;
2462
2463 /* Note: This wrapper only works for __pow__() */
2464
2465 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2466 return NULL;
2467 return (*func)(self, other, third);
2468}
2469
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002470static PyObject *
2471wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2472{
2473 ternaryfunc func = (ternaryfunc)wrapped;
2474 PyObject *other;
2475 PyObject *third = Py_None;
2476
2477 /* Note: This wrapper only works for __pow__() */
2478
2479 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2480 return NULL;
2481 return (*func)(other, self, third);
2482}
2483
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484static PyObject *
2485wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2486{
2487 unaryfunc func = (unaryfunc)wrapped;
2488
2489 if (!PyArg_ParseTuple(args, ""))
2490 return NULL;
2491 return (*func)(self);
2492}
2493
Tim Peters6d6c1a32001-08-02 04:15:00 +00002494static PyObject *
2495wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2496{
2497 intargfunc func = (intargfunc)wrapped;
2498 int i;
2499
2500 if (!PyArg_ParseTuple(args, "i", &i))
2501 return NULL;
2502 return (*func)(self, i);
2503}
2504
Guido van Rossum5d815f32001-08-17 21:57:47 +00002505static int
2506getindex(PyObject *self, PyObject *arg)
2507{
2508 int i;
2509
2510 i = PyInt_AsLong(arg);
2511 if (i == -1 && PyErr_Occurred())
2512 return -1;
2513 if (i < 0) {
2514 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2515 if (sq && sq->sq_length) {
2516 int n = (*sq->sq_length)(self);
2517 if (n < 0)
2518 return -1;
2519 i += n;
2520 }
2521 }
2522 return i;
2523}
2524
2525static PyObject *
2526wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2527{
2528 intargfunc func = (intargfunc)wrapped;
2529 PyObject *arg;
2530 int i;
2531
Guido van Rossumf4593e02001-10-03 12:09:30 +00002532 if (PyTuple_GET_SIZE(args) == 1) {
2533 arg = PyTuple_GET_ITEM(args, 0);
2534 i = getindex(self, arg);
2535 if (i == -1 && PyErr_Occurred())
2536 return NULL;
2537 return (*func)(self, i);
2538 }
2539 PyArg_ParseTuple(args, "O", &arg);
2540 assert(PyErr_Occurred());
2541 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002542}
2543
Tim Peters6d6c1a32001-08-02 04:15:00 +00002544static PyObject *
2545wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2546{
2547 intintargfunc func = (intintargfunc)wrapped;
2548 int i, j;
2549
2550 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2551 return NULL;
2552 return (*func)(self, i, j);
2553}
2554
Tim Peters6d6c1a32001-08-02 04:15:00 +00002555static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002556wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002557{
2558 intobjargproc func = (intobjargproc)wrapped;
2559 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002560 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561
Guido van Rossum5d815f32001-08-17 21:57:47 +00002562 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2563 return NULL;
2564 i = getindex(self, arg);
2565 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002566 return NULL;
2567 res = (*func)(self, i, value);
2568 if (res == -1 && PyErr_Occurred())
2569 return NULL;
2570 Py_INCREF(Py_None);
2571 return Py_None;
2572}
2573
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002574static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002575wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002576{
2577 intobjargproc func = (intobjargproc)wrapped;
2578 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002579 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002580
Guido van Rossum5d815f32001-08-17 21:57:47 +00002581 if (!PyArg_ParseTuple(args, "O", &arg))
2582 return NULL;
2583 i = getindex(self, arg);
2584 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002585 return NULL;
2586 res = (*func)(self, i, NULL);
2587 if (res == -1 && PyErr_Occurred())
2588 return NULL;
2589 Py_INCREF(Py_None);
2590 return Py_None;
2591}
2592
Tim Peters6d6c1a32001-08-02 04:15:00 +00002593static PyObject *
2594wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2595{
2596 intintobjargproc func = (intintobjargproc)wrapped;
2597 int i, j, res;
2598 PyObject *value;
2599
2600 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2601 return NULL;
2602 res = (*func)(self, i, j, value);
2603 if (res == -1 && PyErr_Occurred())
2604 return NULL;
2605 Py_INCREF(Py_None);
2606 return Py_None;
2607}
2608
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002609static PyObject *
2610wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2611{
2612 intintobjargproc func = (intintobjargproc)wrapped;
2613 int i, j, res;
2614
2615 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2616 return NULL;
2617 res = (*func)(self, i, j, NULL);
2618 if (res == -1 && PyErr_Occurred())
2619 return NULL;
2620 Py_INCREF(Py_None);
2621 return Py_None;
2622}
2623
Tim Peters6d6c1a32001-08-02 04:15:00 +00002624/* XXX objobjproc is a misnomer; should be objargpred */
2625static PyObject *
2626wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2627{
2628 objobjproc func = (objobjproc)wrapped;
2629 int res;
2630 PyObject *value;
2631
2632 if (!PyArg_ParseTuple(args, "O", &value))
2633 return NULL;
2634 res = (*func)(self, value);
2635 if (res == -1 && PyErr_Occurred())
2636 return NULL;
2637 return PyInt_FromLong((long)res);
2638}
2639
Tim Peters6d6c1a32001-08-02 04:15:00 +00002640static PyObject *
2641wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2642{
2643 objobjargproc func = (objobjargproc)wrapped;
2644 int res;
2645 PyObject *key, *value;
2646
2647 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2648 return NULL;
2649 res = (*func)(self, key, value);
2650 if (res == -1 && PyErr_Occurred())
2651 return NULL;
2652 Py_INCREF(Py_None);
2653 return Py_None;
2654}
2655
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002656static PyObject *
2657wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2658{
2659 objobjargproc func = (objobjargproc)wrapped;
2660 int res;
2661 PyObject *key;
2662
2663 if (!PyArg_ParseTuple(args, "O", &key))
2664 return NULL;
2665 res = (*func)(self, key, NULL);
2666 if (res == -1 && PyErr_Occurred())
2667 return NULL;
2668 Py_INCREF(Py_None);
2669 return Py_None;
2670}
2671
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672static PyObject *
2673wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2674{
2675 cmpfunc func = (cmpfunc)wrapped;
2676 int res;
2677 PyObject *other;
2678
2679 if (!PyArg_ParseTuple(args, "O", &other))
2680 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002681 if (other->ob_type->tp_compare != func &&
2682 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002683 PyErr_Format(
2684 PyExc_TypeError,
2685 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2686 self->ob_type->tp_name,
2687 self->ob_type->tp_name,
2688 other->ob_type->tp_name);
2689 return NULL;
2690 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002691 res = (*func)(self, other);
2692 if (PyErr_Occurred())
2693 return NULL;
2694 return PyInt_FromLong((long)res);
2695}
2696
Tim Peters6d6c1a32001-08-02 04:15:00 +00002697static PyObject *
2698wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2699{
2700 setattrofunc func = (setattrofunc)wrapped;
2701 int res;
2702 PyObject *name, *value;
2703
2704 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2705 return NULL;
2706 res = (*func)(self, name, value);
2707 if (res < 0)
2708 return NULL;
2709 Py_INCREF(Py_None);
2710 return Py_None;
2711}
2712
2713static PyObject *
2714wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2715{
2716 setattrofunc func = (setattrofunc)wrapped;
2717 int res;
2718 PyObject *name;
2719
2720 if (!PyArg_ParseTuple(args, "O", &name))
2721 return NULL;
2722 res = (*func)(self, name, NULL);
2723 if (res < 0)
2724 return NULL;
2725 Py_INCREF(Py_None);
2726 return Py_None;
2727}
2728
Tim Peters6d6c1a32001-08-02 04:15:00 +00002729static PyObject *
2730wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2731{
2732 hashfunc func = (hashfunc)wrapped;
2733 long res;
2734
2735 if (!PyArg_ParseTuple(args, ""))
2736 return NULL;
2737 res = (*func)(self);
2738 if (res == -1 && PyErr_Occurred())
2739 return NULL;
2740 return PyInt_FromLong(res);
2741}
2742
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002744wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745{
2746 ternaryfunc func = (ternaryfunc)wrapped;
2747
Guido van Rossumc8e56452001-10-22 00:43:43 +00002748 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002749}
2750
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751static PyObject *
2752wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2753{
2754 richcmpfunc func = (richcmpfunc)wrapped;
2755 PyObject *other;
2756
2757 if (!PyArg_ParseTuple(args, "O", &other))
2758 return NULL;
2759 return (*func)(self, other, op);
2760}
2761
2762#undef RICHCMP_WRAPPER
2763#define RICHCMP_WRAPPER(NAME, OP) \
2764static PyObject * \
2765richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2766{ \
2767 return wrap_richcmpfunc(self, args, wrapped, OP); \
2768}
2769
Jack Jansen8e938b42001-08-08 15:29:49 +00002770RICHCMP_WRAPPER(lt, Py_LT)
2771RICHCMP_WRAPPER(le, Py_LE)
2772RICHCMP_WRAPPER(eq, Py_EQ)
2773RICHCMP_WRAPPER(ne, Py_NE)
2774RICHCMP_WRAPPER(gt, Py_GT)
2775RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776
Tim Peters6d6c1a32001-08-02 04:15:00 +00002777static PyObject *
2778wrap_next(PyObject *self, PyObject *args, void *wrapped)
2779{
2780 unaryfunc func = (unaryfunc)wrapped;
2781 PyObject *res;
2782
2783 if (!PyArg_ParseTuple(args, ""))
2784 return NULL;
2785 res = (*func)(self);
2786 if (res == NULL && !PyErr_Occurred())
2787 PyErr_SetNone(PyExc_StopIteration);
2788 return res;
2789}
2790
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791static PyObject *
2792wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2793{
2794 descrgetfunc func = (descrgetfunc)wrapped;
2795 PyObject *obj;
2796 PyObject *type = NULL;
2797
2798 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2799 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002800 return (*func)(self, obj, type);
2801}
2802
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002804wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805{
2806 descrsetfunc func = (descrsetfunc)wrapped;
2807 PyObject *obj, *value;
2808 int ret;
2809
2810 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2811 return NULL;
2812 ret = (*func)(self, obj, value);
2813 if (ret < 0)
2814 return NULL;
2815 Py_INCREF(Py_None);
2816 return Py_None;
2817}
2818
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002820wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821{
2822 initproc func = (initproc)wrapped;
2823
Guido van Rossumc8e56452001-10-22 00:43:43 +00002824 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825 return NULL;
2826 Py_INCREF(Py_None);
2827 return Py_None;
2828}
2829
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002831tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832{
Barry Warsaw60f01882001-08-22 19:24:42 +00002833 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002834 PyObject *arg0, *res;
2835
2836 if (self == NULL || !PyType_Check(self))
2837 Py_FatalError("__new__() called with non-type 'self'");
2838 type = (PyTypeObject *)self;
2839 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002840 PyErr_Format(PyExc_TypeError,
2841 "%s.__new__(): not enough arguments",
2842 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002843 return NULL;
2844 }
2845 arg0 = PyTuple_GET_ITEM(args, 0);
2846 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002847 PyErr_Format(PyExc_TypeError,
2848 "%s.__new__(X): X is not a type object (%s)",
2849 type->tp_name,
2850 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002851 return NULL;
2852 }
2853 subtype = (PyTypeObject *)arg0;
2854 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002855 PyErr_Format(PyExc_TypeError,
2856 "%s.__new__(%s): %s is not a subtype of %s",
2857 type->tp_name,
2858 subtype->tp_name,
2859 subtype->tp_name,
2860 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002861 return NULL;
2862 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002863
2864 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002865 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002866 most derived base that's not a heap type is this type. */
2867 staticbase = subtype;
2868 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2869 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002870 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002871 PyErr_Format(PyExc_TypeError,
2872 "%s.__new__(%s) is not safe, use %s.__new__()",
2873 type->tp_name,
2874 subtype->tp_name,
2875 staticbase == NULL ? "?" : staticbase->tp_name);
2876 return NULL;
2877 }
2878
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002879 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2880 if (args == NULL)
2881 return NULL;
2882 res = type->tp_new(subtype, args, kwds);
2883 Py_DECREF(args);
2884 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002885}
2886
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002887static struct PyMethodDef tp_new_methoddef[] = {
2888 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2889 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890 {0}
2891};
2892
2893static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002894add_tp_new_wrapper(PyTypeObject *type)
2895{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002896 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002897
Guido van Rossum687ae002001-10-15 22:03:32 +00002898 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002899 return 0;
2900 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002901 if (func == NULL)
2902 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002903 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002904}
2905
Guido van Rossumf040ede2001-08-07 16:40:56 +00002906/* Slot wrappers that call the corresponding __foo__ slot. See comments
2907 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908
Guido van Rossumdc91b992001-08-08 22:26:22 +00002909#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002911FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002913 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002914 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915}
2916
Guido van Rossumdc91b992001-08-08 22:26:22 +00002917#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002919FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002921 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002922 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002923}
2924
Guido van Rossumdc91b992001-08-08 22:26:22 +00002925
2926#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002928FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002929{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002930 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002931 int do_other = self->ob_type != other->ob_type && \
2932 other->ob_type->tp_as_number != NULL && \
2933 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002934 if (self->ob_type->tp_as_number != NULL && \
2935 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2936 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002937 if (do_other && \
2938 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2939 r = call_maybe( \
2940 other, ROPSTR, &rcache_str, "(O)", self); \
2941 if (r != Py_NotImplemented) \
2942 return r; \
2943 Py_DECREF(r); \
2944 do_other = 0; \
2945 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002946 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002947 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002948 if (r != Py_NotImplemented || \
2949 other->ob_type == self->ob_type) \
2950 return r; \
2951 Py_DECREF(r); \
2952 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002953 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002954 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002955 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002956 } \
2957 Py_INCREF(Py_NotImplemented); \
2958 return Py_NotImplemented; \
2959}
2960
2961#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2962 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2963
2964#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2965static PyObject * \
2966FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2967{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002968 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002969 return call_method(self, OPSTR, &cache_str, \
2970 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971}
2972
2973static int
2974slot_sq_length(PyObject *self)
2975{
Guido van Rossum2730b132001-08-28 18:22:14 +00002976 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002977 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002978 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979
2980 if (res == NULL)
2981 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002982 len = (int)PyInt_AsLong(res);
2983 Py_DECREF(res);
2984 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985}
2986
Guido van Rossumdc91b992001-08-08 22:26:22 +00002987SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2988SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002989
2990/* Super-optimized version of slot_sq_item.
2991 Other slots could do the same... */
2992static PyObject *
2993slot_sq_item(PyObject *self, int i)
2994{
2995 static PyObject *getitem_str;
2996 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2997 descrgetfunc f;
2998
2999 if (getitem_str == NULL) {
3000 getitem_str = PyString_InternFromString("__getitem__");
3001 if (getitem_str == NULL)
3002 return NULL;
3003 }
3004 func = _PyType_Lookup(self->ob_type, getitem_str);
3005 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003006 if ((f = func->ob_type->tp_descr_get) == NULL)
3007 Py_INCREF(func);
3008 else
3009 func = f(func, self, (PyObject *)(self->ob_type));
3010 ival = PyInt_FromLong(i);
3011 if (ival != NULL) {
3012 args = PyTuple_New(1);
3013 if (args != NULL) {
3014 PyTuple_SET_ITEM(args, 0, ival);
3015 retval = PyObject_Call(func, args, NULL);
3016 Py_XDECREF(args);
3017 Py_XDECREF(func);
3018 return retval;
3019 }
3020 }
3021 }
3022 else {
3023 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3024 }
3025 Py_XDECREF(args);
3026 Py_XDECREF(ival);
3027 Py_XDECREF(func);
3028 return NULL;
3029}
3030
Guido van Rossumdc91b992001-08-08 22:26:22 +00003031SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032
3033static int
3034slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3035{
3036 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003037 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003038
3039 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003040 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003041 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003043 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003044 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045 if (res == NULL)
3046 return -1;
3047 Py_DECREF(res);
3048 return 0;
3049}
3050
3051static int
3052slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3053{
3054 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003055 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056
3057 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003058 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003059 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003060 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003061 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003062 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063 if (res == NULL)
3064 return -1;
3065 Py_DECREF(res);
3066 return 0;
3067}
3068
3069static int
3070slot_sq_contains(PyObject *self, PyObject *value)
3071{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003072 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003073 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074
Guido van Rossum55f20992001-10-01 17:18:22 +00003075 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003076
3077 if (func != NULL) {
3078 args = Py_BuildValue("(O)", value);
3079 if (args == NULL)
3080 res = NULL;
3081 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003082 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003083 Py_DECREF(args);
3084 }
3085 Py_DECREF(func);
3086 if (res == NULL)
3087 return -1;
3088 return PyObject_IsTrue(res);
3089 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003090 else if (PyErr_Occurred())
3091 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003092 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003093 return _PySequence_IterSearch(self, value,
3094 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003095 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096}
3097
Guido van Rossumdc91b992001-08-08 22:26:22 +00003098SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3099SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003100
3101#define slot_mp_length slot_sq_length
3102
Guido van Rossumdc91b992001-08-08 22:26:22 +00003103SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104
3105static int
3106slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3107{
3108 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003109 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110
3111 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003112 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003113 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003115 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003116 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003117 if (res == NULL)
3118 return -1;
3119 Py_DECREF(res);
3120 return 0;
3121}
3122
Guido van Rossumdc91b992001-08-08 22:26:22 +00003123SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3124SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3125SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3126SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3127SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3128SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3129
3130staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3131
3132SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3133 nb_power, "__pow__", "__rpow__")
3134
3135static PyObject *
3136slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3137{
Guido van Rossum2730b132001-08-28 18:22:14 +00003138 static PyObject *pow_str;
3139
Guido van Rossumdc91b992001-08-08 22:26:22 +00003140 if (modulus == Py_None)
3141 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003142 /* Three-arg power doesn't use __rpow__. But ternary_op
3143 can call this when the second argument's type uses
3144 slot_nb_power, so check before calling self.__pow__. */
3145 if (self->ob_type->tp_as_number != NULL &&
3146 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3147 return call_method(self, "__pow__", &pow_str,
3148 "(OO)", other, modulus);
3149 }
3150 Py_INCREF(Py_NotImplemented);
3151 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003152}
3153
3154SLOT0(slot_nb_negative, "__neg__")
3155SLOT0(slot_nb_positive, "__pos__")
3156SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157
3158static int
3159slot_nb_nonzero(PyObject *self)
3160{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003161 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003162 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003163
Guido van Rossum55f20992001-10-01 17:18:22 +00003164 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003165 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003166 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003167 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003168 func = lookup_maybe(self, "__len__", &len_str);
3169 if (func == NULL) {
3170 if (PyErr_Occurred())
3171 return -1;
3172 else
3173 return 1;
3174 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003175 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003176 res = PyObject_CallObject(func, NULL);
3177 Py_DECREF(func);
3178 if (res == NULL)
3179 return -1;
3180 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181}
3182
Guido van Rossumdc91b992001-08-08 22:26:22 +00003183SLOT0(slot_nb_invert, "__invert__")
3184SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3185SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3186SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3187SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3188SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003189
3190static int
3191slot_nb_coerce(PyObject **a, PyObject **b)
3192{
3193 static PyObject *coerce_str;
3194 PyObject *self = *a, *other = *b;
3195
3196 if (self->ob_type->tp_as_number != NULL &&
3197 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3198 PyObject *r;
3199 r = call_maybe(
3200 self, "__coerce__", &coerce_str, "(O)", other);
3201 if (r == NULL)
3202 return -1;
3203 if (r == Py_NotImplemented) {
3204 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003205 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003206 else {
3207 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3208 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003209 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003210 Py_DECREF(r);
3211 return -1;
3212 }
3213 *a = PyTuple_GET_ITEM(r, 0);
3214 Py_INCREF(*a);
3215 *b = PyTuple_GET_ITEM(r, 1);
3216 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003217 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003218 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003219 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003220 }
3221 if (other->ob_type->tp_as_number != NULL &&
3222 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3223 PyObject *r;
3224 r = call_maybe(
3225 other, "__coerce__", &coerce_str, "(O)", self);
3226 if (r == NULL)
3227 return -1;
3228 if (r == Py_NotImplemented) {
3229 Py_DECREF(r);
3230 return 1;
3231 }
3232 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3233 PyErr_SetString(PyExc_TypeError,
3234 "__coerce__ didn't return a 2-tuple");
3235 Py_DECREF(r);
3236 return -1;
3237 }
3238 *a = PyTuple_GET_ITEM(r, 1);
3239 Py_INCREF(*a);
3240 *b = PyTuple_GET_ITEM(r, 0);
3241 Py_INCREF(*b);
3242 Py_DECREF(r);
3243 return 0;
3244 }
3245 return 1;
3246}
3247
Guido van Rossumdc91b992001-08-08 22:26:22 +00003248SLOT0(slot_nb_int, "__int__")
3249SLOT0(slot_nb_long, "__long__")
3250SLOT0(slot_nb_float, "__float__")
3251SLOT0(slot_nb_oct, "__oct__")
3252SLOT0(slot_nb_hex, "__hex__")
3253SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3254SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3255SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3256SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3257SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3258SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3259SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3260SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3261SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3262SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3263SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3264SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3265 "__floordiv__", "__rfloordiv__")
3266SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3267SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3268SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003269
3270static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003271half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003274 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003275 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003276
Guido van Rossum60718732001-08-28 17:47:51 +00003277 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278 if (func == NULL) {
3279 PyErr_Clear();
3280 }
3281 else {
3282 args = Py_BuildValue("(O)", other);
3283 if (args == NULL)
3284 res = NULL;
3285 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003286 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003287 Py_DECREF(args);
3288 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003289 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003290 if (res != Py_NotImplemented) {
3291 if (res == NULL)
3292 return -2;
3293 c = PyInt_AsLong(res);
3294 Py_DECREF(res);
3295 if (c == -1 && PyErr_Occurred())
3296 return -2;
3297 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3298 }
3299 Py_DECREF(res);
3300 }
3301 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003302}
3303
Guido van Rossumab3b0342001-09-18 20:38:53 +00003304/* This slot is published for the benefit of try_3way_compare in object.c */
3305int
3306_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003307{
3308 int c;
3309
Guido van Rossumab3b0342001-09-18 20:38:53 +00003310 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003311 c = half_compare(self, other);
3312 if (c <= 1)
3313 return c;
3314 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003315 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003316 c = half_compare(other, self);
3317 if (c < -1)
3318 return -2;
3319 if (c <= 1)
3320 return -c;
3321 }
3322 return (void *)self < (void *)other ? -1 :
3323 (void *)self > (void *)other ? 1 : 0;
3324}
3325
3326static PyObject *
3327slot_tp_repr(PyObject *self)
3328{
3329 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003330 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003331
Guido van Rossum60718732001-08-28 17:47:51 +00003332 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003333 if (func != NULL) {
3334 res = PyEval_CallObject(func, NULL);
3335 Py_DECREF(func);
3336 return res;
3337 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003338 PyErr_Clear();
3339 return PyString_FromFormat("<%s object at %p>",
3340 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003341}
3342
3343static PyObject *
3344slot_tp_str(PyObject *self)
3345{
3346 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003347 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003348
Guido van Rossum60718732001-08-28 17:47:51 +00003349 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003350 if (func != NULL) {
3351 res = PyEval_CallObject(func, NULL);
3352 Py_DECREF(func);
3353 return res;
3354 }
3355 else {
3356 PyErr_Clear();
3357 return slot_tp_repr(self);
3358 }
3359}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360
3361static long
3362slot_tp_hash(PyObject *self)
3363{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003364 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003365 static PyObject *hash_str, *eq_str, *cmp_str;
3366
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367 long h;
3368
Guido van Rossum60718732001-08-28 17:47:51 +00003369 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003370
3371 if (func != NULL) {
3372 res = PyEval_CallObject(func, NULL);
3373 Py_DECREF(func);
3374 if (res == NULL)
3375 return -1;
3376 h = PyInt_AsLong(res);
3377 }
3378 else {
3379 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003380 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003381 if (func == NULL) {
3382 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003383 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003384 }
3385 if (func != NULL) {
3386 Py_DECREF(func);
3387 PyErr_SetString(PyExc_TypeError, "unhashable type");
3388 return -1;
3389 }
3390 PyErr_Clear();
3391 h = _Py_HashPointer((void *)self);
3392 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393 if (h == -1 && !PyErr_Occurred())
3394 h = -2;
3395 return h;
3396}
3397
3398static PyObject *
3399slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3400{
Guido van Rossum60718732001-08-28 17:47:51 +00003401 static PyObject *call_str;
3402 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403 PyObject *res;
3404
3405 if (meth == NULL)
3406 return NULL;
3407 res = PyObject_Call(meth, args, kwds);
3408 Py_DECREF(meth);
3409 return res;
3410}
3411
Guido van Rossum14a6f832001-10-17 13:59:09 +00003412/* There are two slot dispatch functions for tp_getattro.
3413
3414 - slot_tp_getattro() is used when __getattribute__ is overridden
3415 but no __getattr__ hook is present;
3416
3417 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3418
Guido van Rossumc334df52002-04-04 23:44:47 +00003419 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3420 detects the absence of __getattr__ and then installs the simpler slot if
3421 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003422
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423static PyObject *
3424slot_tp_getattro(PyObject *self, PyObject *name)
3425{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003426 static PyObject *getattribute_str = NULL;
3427 return call_method(self, "__getattribute__", &getattribute_str,
3428 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003429}
3430
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003431static PyObject *
3432slot_tp_getattr_hook(PyObject *self, PyObject *name)
3433{
3434 PyTypeObject *tp = self->ob_type;
3435 PyObject *getattr, *getattribute, *res;
3436 static PyObject *getattribute_str = NULL;
3437 static PyObject *getattr_str = NULL;
3438
3439 if (getattr_str == NULL) {
3440 getattr_str = PyString_InternFromString("__getattr__");
3441 if (getattr_str == NULL)
3442 return NULL;
3443 }
3444 if (getattribute_str == NULL) {
3445 getattribute_str =
3446 PyString_InternFromString("__getattribute__");
3447 if (getattribute_str == NULL)
3448 return NULL;
3449 }
3450 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003451 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003452 /* No __getattr__ hook: use a simpler dispatcher */
3453 tp->tp_getattro = slot_tp_getattro;
3454 return slot_tp_getattro(self, name);
3455 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003456 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003457 if (getattribute == NULL ||
3458 (getattribute->ob_type == &PyWrapperDescr_Type &&
3459 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3460 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003461 res = PyObject_GenericGetAttr(self, name);
3462 else
3463 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003464 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003465 PyErr_Clear();
3466 res = PyObject_CallFunction(getattr, "OO", self, name);
3467 }
3468 return res;
3469}
3470
Tim Peters6d6c1a32001-08-02 04:15:00 +00003471static int
3472slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3473{
3474 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003475 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476
3477 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003478 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003479 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003481 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003482 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483 if (res == NULL)
3484 return -1;
3485 Py_DECREF(res);
3486 return 0;
3487}
3488
3489/* Map rich comparison operators to their __xx__ namesakes */
3490static char *name_op[] = {
3491 "__lt__",
3492 "__le__",
3493 "__eq__",
3494 "__ne__",
3495 "__gt__",
3496 "__ge__",
3497};
3498
3499static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003500half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003501{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003502 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003503 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504
Guido van Rossum60718732001-08-28 17:47:51 +00003505 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003506 if (func == NULL) {
3507 PyErr_Clear();
3508 Py_INCREF(Py_NotImplemented);
3509 return Py_NotImplemented;
3510 }
3511 args = Py_BuildValue("(O)", other);
3512 if (args == NULL)
3513 res = NULL;
3514 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003515 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003516 Py_DECREF(args);
3517 }
3518 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003519 return res;
3520}
3521
Guido van Rossumb8f63662001-08-15 23:57:02 +00003522/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3523static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3524
3525static PyObject *
3526slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3527{
3528 PyObject *res;
3529
3530 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3531 res = half_richcompare(self, other, op);
3532 if (res != Py_NotImplemented)
3533 return res;
3534 Py_DECREF(res);
3535 }
3536 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3537 res = half_richcompare(other, self, swapped_op[op]);
3538 if (res != Py_NotImplemented) {
3539 return res;
3540 }
3541 Py_DECREF(res);
3542 }
3543 Py_INCREF(Py_NotImplemented);
3544 return Py_NotImplemented;
3545}
3546
3547static PyObject *
3548slot_tp_iter(PyObject *self)
3549{
3550 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003551 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003552
Guido van Rossum60718732001-08-28 17:47:51 +00003553 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003554 if (func != NULL) {
3555 res = PyObject_CallObject(func, NULL);
3556 Py_DECREF(func);
3557 return res;
3558 }
3559 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003560 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003561 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003562 PyErr_SetString(PyExc_TypeError,
3563 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003564 return NULL;
3565 }
3566 Py_DECREF(func);
3567 return PySeqIter_New(self);
3568}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003569
3570static PyObject *
3571slot_tp_iternext(PyObject *self)
3572{
Guido van Rossum2730b132001-08-28 18:22:14 +00003573 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003574 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575}
3576
Guido van Rossum1a493502001-08-17 16:47:50 +00003577static PyObject *
3578slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3579{
3580 PyTypeObject *tp = self->ob_type;
3581 PyObject *get;
3582 static PyObject *get_str = NULL;
3583
3584 if (get_str == NULL) {
3585 get_str = PyString_InternFromString("__get__");
3586 if (get_str == NULL)
3587 return NULL;
3588 }
3589 get = _PyType_Lookup(tp, get_str);
3590 if (get == NULL) {
3591 /* Avoid further slowdowns */
3592 if (tp->tp_descr_get == slot_tp_descr_get)
3593 tp->tp_descr_get = NULL;
3594 Py_INCREF(self);
3595 return self;
3596 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003597 if (obj == NULL)
3598 obj = Py_None;
3599 if (type == NULL)
3600 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003601 return PyObject_CallFunction(get, "OOO", self, obj, type);
3602}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003603
3604static int
3605slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3606{
Guido van Rossum2c252392001-08-24 10:13:31 +00003607 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003608 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003609
3610 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003611 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003612 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003613 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003614 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003615 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616 if (res == NULL)
3617 return -1;
3618 Py_DECREF(res);
3619 return 0;
3620}
3621
3622static int
3623slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3624{
Guido van Rossum60718732001-08-28 17:47:51 +00003625 static PyObject *init_str;
3626 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627 PyObject *res;
3628
3629 if (meth == NULL)
3630 return -1;
3631 res = PyObject_Call(meth, args, kwds);
3632 Py_DECREF(meth);
3633 if (res == NULL)
3634 return -1;
3635 Py_DECREF(res);
3636 return 0;
3637}
3638
3639static PyObject *
3640slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3641{
3642 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3643 PyObject *newargs, *x;
3644 int i, n;
3645
3646 if (func == NULL)
3647 return NULL;
3648 assert(PyTuple_Check(args));
3649 n = PyTuple_GET_SIZE(args);
3650 newargs = PyTuple_New(n+1);
3651 if (newargs == NULL)
3652 return NULL;
3653 Py_INCREF(type);
3654 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3655 for (i = 0; i < n; i++) {
3656 x = PyTuple_GET_ITEM(args, i);
3657 Py_INCREF(x);
3658 PyTuple_SET_ITEM(newargs, i+1, x);
3659 }
3660 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003661 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662 Py_DECREF(func);
3663 return x;
3664}
3665
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003666
3667/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3668 functions. The offsets here are relative to the 'etype' structure, which
3669 incorporates the additional structures used for numbers, sequences and
3670 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3671 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003672 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3673 terminated with an all-zero entry. (This table is further initialized and
3674 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003675
Guido van Rossum6d204072001-10-21 00:44:31 +00003676typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003677
3678#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003679#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003680#undef ETSLOT
3681#undef SQSLOT
3682#undef MPSLOT
3683#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003684#undef UNSLOT
3685#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003686#undef BINSLOT
3687#undef RBINSLOT
3688
Guido van Rossum6d204072001-10-21 00:44:31 +00003689#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3690 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003691#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3692 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3693 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003694#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3695 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3696#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3697 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3698#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3699 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3700#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3701 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3702#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3703 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3704 "x." NAME "() <==> " DOC)
3705#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3706 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3707 "x." NAME "(y) <==> x" DOC "y")
3708#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3709 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3710 "x." NAME "(y) <==> x" DOC "y")
3711#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3712 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3713 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003714
3715static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003716 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3717 "x.__len__() <==> len(x)"),
3718 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3719 "x.__add__(y) <==> x+y"),
3720 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3721 "x.__mul__(n) <==> x*n"),
3722 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3723 "x.__rmul__(n) <==> n*x"),
3724 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3725 "x.__getitem__(y) <==> x[y]"),
3726 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3727 "x.__getslice__(i, j) <==> x[i:j]"),
3728 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3729 "x.__setitem__(i, y) <==> x[i]=y"),
3730 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3731 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003732 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003733 wrap_intintobjargproc,
3734 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3735 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3736 "x.__delslice__(i, j) <==> del x[i:j]"),
3737 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3738 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003739 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003740 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003741 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003742 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003743
Guido van Rossum6d204072001-10-21 00:44:31 +00003744 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3745 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003746 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003747 wrap_binaryfunc,
3748 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003749 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003750 wrap_objobjargproc,
3751 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003752 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003753 wrap_delitem,
3754 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003755
Guido van Rossum6d204072001-10-21 00:44:31 +00003756 BINSLOT("__add__", nb_add, slot_nb_add,
3757 "+"),
3758 RBINSLOT("__radd__", nb_add, slot_nb_add,
3759 "+"),
3760 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3761 "-"),
3762 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3763 "-"),
3764 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3765 "*"),
3766 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3767 "*"),
3768 BINSLOT("__div__", nb_divide, slot_nb_divide,
3769 "/"),
3770 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3771 "/"),
3772 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3773 "%"),
3774 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3775 "%"),
3776 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3777 "divmod(x, y)"),
3778 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3779 "divmod(y, x)"),
3780 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3781 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3782 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3783 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3784 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3785 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3786 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3787 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003788 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003789 "x != 0"),
3790 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3791 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3792 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3793 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3794 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3795 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3796 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3797 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3798 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3799 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3800 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3801 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3802 "x.__coerce__(y) <==> coerce(x, y)"),
3803 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3804 "int(x)"),
3805 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3806 "long(x)"),
3807 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3808 "float(x)"),
3809 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3810 "oct(x)"),
3811 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3812 "hex(x)"),
3813 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3814 wrap_binaryfunc, "+"),
3815 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3816 wrap_binaryfunc, "-"),
3817 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3818 wrap_binaryfunc, "*"),
3819 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3820 wrap_binaryfunc, "/"),
3821 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3822 wrap_binaryfunc, "%"),
3823 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3824 wrap_ternaryfunc, "**"),
3825 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3826 wrap_binaryfunc, "<<"),
3827 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3828 wrap_binaryfunc, ">>"),
3829 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3830 wrap_binaryfunc, "&"),
3831 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3832 wrap_binaryfunc, "^"),
3833 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3834 wrap_binaryfunc, "|"),
3835 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3836 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3837 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3838 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3839 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3840 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3841 IBSLOT("__itruediv__", nb_inplace_true_divide,
3842 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003843
Guido van Rossum6d204072001-10-21 00:44:31 +00003844 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3845 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003846 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003847 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3848 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003849 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003850 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3851 "x.__cmp__(y) <==> cmp(x,y)"),
3852 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3853 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003854 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3855 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003856 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003857 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3858 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3859 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3860 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3861 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3862 "x.__setattr__('name', value) <==> x.name = value"),
3863 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3864 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3865 "x.__delattr__('name') <==> del x.name"),
3866 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3867 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3868 "x.__lt__(y) <==> x<y"),
3869 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3870 "x.__le__(y) <==> x<=y"),
3871 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3872 "x.__eq__(y) <==> x==y"),
3873 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3874 "x.__ne__(y) <==> x!=y"),
3875 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3876 "x.__gt__(y) <==> x>y"),
3877 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3878 "x.__ge__(y) <==> x>=y"),
3879 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3880 "x.__iter__() <==> iter(x)"),
3881 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3882 "x.next() -> the next value, or raise StopIteration"),
3883 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3884 "descr.__get__(obj[, type]) -> value"),
3885 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3886 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003887 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003888 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003889 "see x.__class__.__doc__ for signature",
3890 PyWrapperFlag_KEYWORDS),
3891 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003892 {NULL}
3893};
3894
Guido van Rossumc334df52002-04-04 23:44:47 +00003895/* Given a type pointer and an offset gotten from a slotdef entry, return a
3896 pointer to the actual slot. This is not quite the same as simply adding
3897 the offset to the type pointer, since it takes care to indirect through the
3898 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3899 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003900static void **
3901slotptr(PyTypeObject *type, int offset)
3902{
3903 char *ptr;
3904
Guido van Rossum09638c12002-06-13 19:17:46 +00003905 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003906 assert(offset >= 0);
3907 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003908 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003909 ptr = (void *)type->tp_as_sequence;
3910 offset -= offsetof(etype, as_sequence);
3911 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003912 else if (offset >= offsetof(etype, as_mapping)) {
3913 ptr = (void *)type->tp_as_mapping;
3914 offset -= offsetof(etype, as_mapping);
3915 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003916 else if (offset >= offsetof(etype, as_number)) {
3917 ptr = (void *)type->tp_as_number;
3918 offset -= offsetof(etype, as_number);
3919 }
3920 else {
3921 ptr = (void *)type;
3922 }
3923 if (ptr != NULL)
3924 ptr += offset;
3925 return (void **)ptr;
3926}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003927
Guido van Rossumc334df52002-04-04 23:44:47 +00003928/* Length of array of slotdef pointers used to store slots with the
3929 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3930 the same __name__, for any __name__. Since that's a static property, it is
3931 appropriate to declare fixed-size arrays for this. */
3932#define MAX_EQUIV 10
3933
3934/* Return a slot pointer for a given name, but ONLY if the attribute has
3935 exactly one slot function. The name must be an interned string. */
3936static void **
3937resolve_slotdups(PyTypeObject *type, PyObject *name)
3938{
3939 /* XXX Maybe this could be optimized more -- but is it worth it? */
3940
3941 /* pname and ptrs act as a little cache */
3942 static PyObject *pname;
3943 static slotdef *ptrs[MAX_EQUIV];
3944 slotdef *p, **pp;
3945 void **res, **ptr;
3946
3947 if (pname != name) {
3948 /* Collect all slotdefs that match name into ptrs. */
3949 pname = name;
3950 pp = ptrs;
3951 for (p = slotdefs; p->name_strobj; p++) {
3952 if (p->name_strobj == name)
3953 *pp++ = p;
3954 }
3955 *pp = NULL;
3956 }
3957
3958 /* Look in all matching slots of the type; if exactly one of these has
3959 a filled-in slot, return its value. Otherwise return NULL. */
3960 res = NULL;
3961 for (pp = ptrs; *pp; pp++) {
3962 ptr = slotptr(type, (*pp)->offset);
3963 if (ptr == NULL || *ptr == NULL)
3964 continue;
3965 if (res != NULL)
3966 return NULL;
3967 res = ptr;
3968 }
3969 return res;
3970}
3971
3972/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3973 does some incredibly complex thinking and then sticks something into the
3974 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3975 interests, and then stores a generic wrapper or a specific function into
3976 the slot.) Return a pointer to the next slotdef with a different offset,
3977 because that's convenient for fixup_slot_dispatchers(). */
3978static slotdef *
3979update_one_slot(PyTypeObject *type, slotdef *p)
3980{
3981 PyObject *descr;
3982 PyWrapperDescrObject *d;
3983 void *generic = NULL, *specific = NULL;
3984 int use_generic = 0;
3985 int offset = p->offset;
3986 void **ptr = slotptr(type, offset);
3987
3988 if (ptr == NULL) {
3989 do {
3990 ++p;
3991 } while (p->offset == offset);
3992 return p;
3993 }
3994 do {
3995 descr = _PyType_Lookup(type, p->name_strobj);
3996 if (descr == NULL)
3997 continue;
3998 if (descr->ob_type == &PyWrapperDescr_Type) {
3999 void **tptr = resolve_slotdups(type, p->name_strobj);
4000 if (tptr == NULL || tptr == ptr)
4001 generic = p->function;
4002 d = (PyWrapperDescrObject *)descr;
4003 if (d->d_base->wrapper == p->wrapper &&
4004 PyType_IsSubtype(type, d->d_type))
4005 {
4006 if (specific == NULL ||
4007 specific == d->d_wrapped)
4008 specific = d->d_wrapped;
4009 else
4010 use_generic = 1;
4011 }
4012 }
4013 else {
4014 use_generic = 1;
4015 generic = p->function;
4016 }
4017 } while ((++p)->offset == offset);
4018 if (specific && !use_generic)
4019 *ptr = specific;
4020 else
4021 *ptr = generic;
4022 return p;
4023}
4024
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004025staticforward int recurse_down_subclasses(PyTypeObject *type,
4026 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004027
Guido van Rossumc334df52002-04-04 23:44:47 +00004028/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4029 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004030static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004031update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004032{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004033 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004034
Guido van Rossumc334df52002-04-04 23:44:47 +00004035 for (pp = pp0; *pp; pp++)
4036 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004037 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004038}
4039
Guido van Rossumc334df52002-04-04 23:44:47 +00004040/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4041 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004042static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004043recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004044{
4045 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004046 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004047 int i, n;
4048
4049 subclasses = type->tp_subclasses;
4050 if (subclasses == NULL)
4051 return 0;
4052 assert(PyList_Check(subclasses));
4053 n = PyList_GET_SIZE(subclasses);
4054 for (i = 0; i < n; i++) {
4055 ref = PyList_GET_ITEM(subclasses, i);
4056 assert(PyWeakref_CheckRef(ref));
4057 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004058 assert(subclass != NULL);
4059 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004060 continue;
4061 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004062 /* Avoid recursing down into unaffected classes */
4063 dict = subclass->tp_dict;
4064 if (dict != NULL && PyDict_Check(dict) &&
4065 PyDict_GetItem(dict, name) != NULL)
4066 continue;
4067 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004068 return -1;
4069 }
4070 return 0;
4071}
4072
Guido van Rossumc334df52002-04-04 23:44:47 +00004073/* Comparison function for qsort() to compare slotdefs by their offset, and
4074 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004075static int
4076slotdef_cmp(const void *aa, const void *bb)
4077{
4078 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4079 int c = a->offset - b->offset;
4080 if (c != 0)
4081 return c;
4082 else
4083 return a - b;
4084}
4085
Guido van Rossumc334df52002-04-04 23:44:47 +00004086/* Initialize the slotdefs table by adding interned string objects for the
4087 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004088static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004089init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004090{
4091 slotdef *p;
4092 static int initialized = 0;
4093
4094 if (initialized)
4095 return;
4096 for (p = slotdefs; p->name; p++) {
4097 p->name_strobj = PyString_InternFromString(p->name);
4098 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004099 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004100 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004101 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4102 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004103 initialized = 1;
4104}
4105
Guido van Rossumc334df52002-04-04 23:44:47 +00004106/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004107static int
4108update_slot(PyTypeObject *type, PyObject *name)
4109{
Guido van Rossumc334df52002-04-04 23:44:47 +00004110 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004111 slotdef *p;
4112 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004113 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004114
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004115 init_slotdefs();
4116 pp = ptrs;
4117 for (p = slotdefs; p->name; p++) {
4118 /* XXX assume name is interned! */
4119 if (p->name_strobj == name)
4120 *pp++ = p;
4121 }
4122 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004123 for (pp = ptrs; *pp; pp++) {
4124 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004125 offset = p->offset;
4126 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004127 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004128 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004129 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004130 if (ptrs[0] == NULL)
4131 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004132 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004133}
4134
Guido van Rossumc334df52002-04-04 23:44:47 +00004135/* Store the proper functions in the slot dispatches at class (type)
4136 definition time, based upon which operations the class overrides in its
4137 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004139fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004141 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004142
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004143 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004144 for (p = slotdefs; p->name; )
4145 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004146}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004147
Guido van Rossum6d204072001-10-21 00:44:31 +00004148/* This function is called by PyType_Ready() to populate the type's
4149 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004150 function slot (like tp_repr) that's defined in the type, one or more
4151 corresponding descriptors are added in the type's tp_dict dictionary
4152 under the appropriate name (like __repr__). Some function slots
4153 cause more than one descriptor to be added (for example, the nb_add
4154 slot adds both __add__ and __radd__ descriptors) and some function
4155 slots compete for the same descriptor (for example both sq_item and
4156 mp_subscript generate a __getitem__ descriptor).
4157
4158 In the latter case, the first slotdef entry encoutered wins. Since
4159 slotdef entries are sorted by the offset of the slot in the etype
4160 struct, this gives us some control over disambiguating between
4161 competing slots: the members of struct etype are listed from most
4162 general to least general, so the most general slot is preferred. In
4163 particular, because as_mapping comes before as_sequence, for a type
4164 that defines both mp_subscript and sq_item, mp_subscript wins.
4165
4166 This only adds new descriptors and doesn't overwrite entries in
4167 tp_dict that were previously defined. The descriptors contain a
4168 reference to the C function they must call, so that it's safe if they
4169 are copied into a subtype's __dict__ and the subtype has a different
4170 C function in its slot -- calling the method defined by the
4171 descriptor will call the C function that was used to create it,
4172 rather than the C function present in the slot when it is called.
4173 (This is important because a subtype may have a C function in the
4174 slot that calls the method from the dictionary, and we want to avoid
4175 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004176
4177static int
4178add_operators(PyTypeObject *type)
4179{
4180 PyObject *dict = type->tp_dict;
4181 slotdef *p;
4182 PyObject *descr;
4183 void **ptr;
4184
4185 init_slotdefs();
4186 for (p = slotdefs; p->name; p++) {
4187 if (p->wrapper == NULL)
4188 continue;
4189 ptr = slotptr(type, p->offset);
4190 if (!ptr || !*ptr)
4191 continue;
4192 if (PyDict_GetItem(dict, p->name_strobj))
4193 continue;
4194 descr = PyDescr_NewWrapper(type, p, *ptr);
4195 if (descr == NULL)
4196 return -1;
4197 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4198 return -1;
4199 Py_DECREF(descr);
4200 }
4201 if (type->tp_new != NULL) {
4202 if (add_tp_new_wrapper(type) < 0)
4203 return -1;
4204 }
4205 return 0;
4206}
4207
Guido van Rossum705f0f52001-08-24 16:47:00 +00004208
4209/* Cooperative 'super' */
4210
4211typedef struct {
4212 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004213 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004214 PyObject *obj;
4215} superobject;
4216
Guido van Rossum6f799372001-09-20 20:46:19 +00004217static PyMemberDef super_members[] = {
4218 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4219 "the class invoking super()"},
4220 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4221 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004222 {0}
4223};
4224
Guido van Rossum705f0f52001-08-24 16:47:00 +00004225static void
4226super_dealloc(PyObject *self)
4227{
4228 superobject *su = (superobject *)self;
4229
Guido van Rossum048eb752001-10-02 21:24:57 +00004230 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004231 Py_XDECREF(su->obj);
4232 Py_XDECREF(su->type);
4233 self->ob_type->tp_free(self);
4234}
4235
4236static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004237super_repr(PyObject *self)
4238{
4239 superobject *su = (superobject *)self;
4240
4241 if (su->obj)
4242 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004243 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004244 su->type ? su->type->tp_name : "NULL",
4245 su->obj->ob_type->tp_name);
4246 else
4247 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004248 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004249 su->type ? su->type->tp_name : "NULL");
4250}
4251
4252static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004253super_getattro(PyObject *self, PyObject *name)
4254{
4255 superobject *su = (superobject *)self;
4256
4257 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004258 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004259 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004260 descrgetfunc f;
4261 int i, n;
4262
Guido van Rossum155db9a2002-04-02 17:53:47 +00004263 starttype = su->obj->ob_type;
4264 mro = starttype->tp_mro;
4265
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004266 if (mro == NULL)
4267 n = 0;
4268 else {
4269 assert(PyTuple_Check(mro));
4270 n = PyTuple_GET_SIZE(mro);
4271 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004272 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004273 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004274 break;
4275 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004276 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004277 starttype = (PyTypeObject *)(su->obj);
4278 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004279 if (mro == NULL)
4280 n = 0;
4281 else {
4282 assert(PyTuple_Check(mro));
4283 n = PyTuple_GET_SIZE(mro);
4284 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004285 for (i = 0; i < n; i++) {
4286 if ((PyObject *)(su->type) ==
4287 PyTuple_GET_ITEM(mro, i))
4288 break;
4289 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004290 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004291 i++;
4292 res = NULL;
4293 for (; i < n; i++) {
4294 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004295 if (PyType_Check(tmp))
4296 dict = ((PyTypeObject *)tmp)->tp_dict;
4297 else if (PyClass_Check(tmp))
4298 dict = ((PyClassObject *)tmp)->cl_dict;
4299 else
4300 continue;
4301 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004302 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004303 Py_INCREF(res);
4304 f = res->ob_type->tp_descr_get;
4305 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004306 tmp = f(res, su->obj,
4307 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004308 Py_DECREF(res);
4309 res = tmp;
4310 }
4311 return res;
4312 }
4313 }
4314 }
4315 return PyObject_GenericGetAttr(self, name);
4316}
4317
Guido van Rossum5b443c62001-12-03 15:38:28 +00004318static int
4319supercheck(PyTypeObject *type, PyObject *obj)
4320{
4321 if (!PyType_IsSubtype(obj->ob_type, type) &&
4322 !(PyType_Check(obj) &&
4323 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4324 PyErr_SetString(PyExc_TypeError,
4325 "super(type, obj): "
4326 "obj must be an instance or subtype of type");
4327 return -1;
4328 }
4329 else
4330 return 0;
4331}
4332
Guido van Rossum705f0f52001-08-24 16:47:00 +00004333static PyObject *
4334super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4335{
4336 superobject *su = (superobject *)self;
4337 superobject *new;
4338
4339 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4340 /* Not binding to an object, or already bound */
4341 Py_INCREF(self);
4342 return self;
4343 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004344 if (su->ob_type != &PySuper_Type)
4345 /* If su is an instance of a subclass of super,
4346 call its type */
4347 return PyObject_CallFunction((PyObject *)su->ob_type,
4348 "OO", su->type, obj);
4349 else {
4350 /* Inline the common case */
4351 if (supercheck(su->type, obj) < 0)
4352 return NULL;
4353 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4354 NULL, NULL);
4355 if (new == NULL)
4356 return NULL;
4357 Py_INCREF(su->type);
4358 Py_INCREF(obj);
4359 new->type = su->type;
4360 new->obj = obj;
4361 return (PyObject *)new;
4362 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004363}
4364
4365static int
4366super_init(PyObject *self, PyObject *args, PyObject *kwds)
4367{
4368 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004369 PyTypeObject *type;
4370 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004371
4372 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4373 return -1;
4374 if (obj == Py_None)
4375 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004376 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004377 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004378 Py_INCREF(type);
4379 Py_XINCREF(obj);
4380 su->type = type;
4381 su->obj = obj;
4382 return 0;
4383}
4384
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004385PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004386"super(type) -> unbound super object\n"
4387"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004388"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004389"Typical use to call a cooperative superclass method:\n"
4390"class C(B):\n"
4391" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004392" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004393
Guido van Rossum048eb752001-10-02 21:24:57 +00004394static int
4395super_traverse(PyObject *self, visitproc visit, void *arg)
4396{
4397 superobject *su = (superobject *)self;
4398 int err;
4399
4400#define VISIT(SLOT) \
4401 if (SLOT) { \
4402 err = visit((PyObject *)(SLOT), arg); \
4403 if (err) \
4404 return err; \
4405 }
4406
4407 VISIT(su->obj);
4408 VISIT(su->type);
4409
4410#undef VISIT
4411
4412 return 0;
4413}
4414
Guido van Rossum705f0f52001-08-24 16:47:00 +00004415PyTypeObject PySuper_Type = {
4416 PyObject_HEAD_INIT(&PyType_Type)
4417 0, /* ob_size */
4418 "super", /* tp_name */
4419 sizeof(superobject), /* tp_basicsize */
4420 0, /* tp_itemsize */
4421 /* methods */
4422 super_dealloc, /* tp_dealloc */
4423 0, /* tp_print */
4424 0, /* tp_getattr */
4425 0, /* tp_setattr */
4426 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004427 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004428 0, /* tp_as_number */
4429 0, /* tp_as_sequence */
4430 0, /* tp_as_mapping */
4431 0, /* tp_hash */
4432 0, /* tp_call */
4433 0, /* tp_str */
4434 super_getattro, /* tp_getattro */
4435 0, /* tp_setattro */
4436 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004437 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4438 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004439 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004440 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004441 0, /* tp_clear */
4442 0, /* tp_richcompare */
4443 0, /* tp_weaklistoffset */
4444 0, /* tp_iter */
4445 0, /* tp_iternext */
4446 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004447 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004448 0, /* tp_getset */
4449 0, /* tp_base */
4450 0, /* tp_dict */
4451 super_descr_get, /* tp_descr_get */
4452 0, /* tp_descr_set */
4453 0, /* tp_dictoffset */
4454 super_init, /* tp_init */
4455 PyType_GenericAlloc, /* tp_alloc */
4456 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004457 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004458};