blob: 26222fadcb1af16eb6d03d8e256f625f221ea3ac [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
745 bases = type->tp_bases;
746 n = PyTuple_GET_SIZE(bases);
747 result = Py_BuildValue("[O]", (PyObject *)type);
748 if (result == NULL)
749 return NULL;
750 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000751 PyObject *base = PyTuple_GET_ITEM(bases, i);
752 PyObject *parentMRO;
753 if (PyType_Check(base))
754 parentMRO = PySequence_List(
755 ((PyTypeObject*)base)->tp_mro);
756 else
757 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758 if (parentMRO == NULL) {
759 Py_DECREF(result);
760 return NULL;
761 }
762 if (serious_order_disagreements(result, parentMRO)) {
763 Py_DECREF(result);
764 return NULL;
765 }
766 ok = conservative_merge(result, parentMRO);
767 Py_DECREF(parentMRO);
768 if (ok < 0) {
769 Py_DECREF(result);
770 return NULL;
771 }
772 }
773 return result;
774}
775
776static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000777mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778{
779 PyTypeObject *type = (PyTypeObject *)self;
780
Tim Peters6d6c1a32001-08-02 04:15:00 +0000781 return mro_implementation(type);
782}
783
784static int
785mro_internal(PyTypeObject *type)
786{
787 PyObject *mro, *result, *tuple;
788
789 if (type->ob_type == &PyType_Type) {
790 result = mro_implementation(type);
791 }
792 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000793 static PyObject *mro_str;
794 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795 if (mro == NULL)
796 return -1;
797 result = PyObject_CallObject(mro, NULL);
798 Py_DECREF(mro);
799 }
800 if (result == NULL)
801 return -1;
802 tuple = PySequence_Tuple(result);
803 Py_DECREF(result);
804 type->tp_mro = tuple;
805 return 0;
806}
807
808
809/* Calculate the best base amongst multiple base classes.
810 This is the first one that's on the path to the "solid base". */
811
812static PyTypeObject *
813best_base(PyObject *bases)
814{
815 int i, n;
816 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000817 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818
819 assert(PyTuple_Check(bases));
820 n = PyTuple_GET_SIZE(bases);
821 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000822 base = NULL;
823 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000825 base_proto = PyTuple_GET_ITEM(bases, i);
826 if (PyClass_Check(base_proto))
827 continue;
828 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000829 PyErr_SetString(
830 PyExc_TypeError,
831 "bases must be types");
832 return NULL;
833 }
Tim Petersa91e9642001-11-14 23:32:33 +0000834 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000835 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000836 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000837 return NULL;
838 }
839 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000840 if (winner == NULL) {
841 winner = candidate;
842 base = base_i;
843 }
844 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000845 ;
846 else if (PyType_IsSubtype(candidate, winner)) {
847 winner = candidate;
848 base = base_i;
849 }
850 else {
851 PyErr_SetString(
852 PyExc_TypeError,
853 "multiple bases have "
854 "instance lay-out conflict");
855 return NULL;
856 }
857 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000858 if (base == NULL)
859 PyErr_SetString(PyExc_TypeError,
860 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000861 return base;
862}
863
864static int
865extra_ivars(PyTypeObject *type, PyTypeObject *base)
866{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000867 size_t t_size = type->tp_basicsize;
868 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869
Guido van Rossum9676b222001-08-17 20:32:36 +0000870 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000871 if (type->tp_itemsize || base->tp_itemsize) {
872 /* If itemsize is involved, stricter rules */
873 return t_size != b_size ||
874 type->tp_itemsize != base->tp_itemsize;
875 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000876 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
877 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
878 t_size -= sizeof(PyObject *);
879 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
880 type->tp_dictoffset + sizeof(PyObject *) == t_size)
881 t_size -= sizeof(PyObject *);
882
883 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884}
885
886static PyTypeObject *
887solid_base(PyTypeObject *type)
888{
889 PyTypeObject *base;
890
891 if (type->tp_base)
892 base = solid_base(type->tp_base);
893 else
894 base = &PyBaseObject_Type;
895 if (extra_ivars(type, base))
896 return type;
897 else
898 return base;
899}
900
901staticforward void object_dealloc(PyObject *);
902staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000903staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000904staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000905
906static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000907subtype_dict(PyObject *obj, void *context)
908{
909 PyObject **dictptr = _PyObject_GetDictPtr(obj);
910 PyObject *dict;
911
912 if (dictptr == NULL) {
913 PyErr_SetString(PyExc_AttributeError,
914 "This object has no __dict__");
915 return NULL;
916 }
917 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000918 if (dict == NULL)
919 *dictptr = dict = PyDict_New();
920 Py_XINCREF(dict);
921 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000922}
923
Guido van Rossum6661be32001-10-26 04:26:12 +0000924static int
925subtype_setdict(PyObject *obj, PyObject *value, void *context)
926{
927 PyObject **dictptr = _PyObject_GetDictPtr(obj);
928 PyObject *dict;
929
930 if (dictptr == NULL) {
931 PyErr_SetString(PyExc_AttributeError,
932 "This object has no __dict__");
933 return -1;
934 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000935 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000936 PyErr_SetString(PyExc_TypeError,
937 "__dict__ must be set to a dictionary");
938 return -1;
939 }
940 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000941 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000942 *dictptr = value;
943 Py_XDECREF(dict);
944 return 0;
945}
946
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000947static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000948 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000949 {0},
950};
951
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000952/* bozo: __getstate__ that raises TypeError */
953
954static PyObject *
955bozo_func(PyObject *self, PyObject *args)
956{
957 PyErr_SetString(PyExc_TypeError,
958 "a class that defines __slots__ without "
959 "defining __getstate__ cannot be pickled");
960 return NULL;
961}
962
Neal Norwitz93c1e232002-03-31 16:06:11 +0000963static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000964
965static PyObject *bozo_obj = NULL;
966
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000967static int
968valid_identifier(PyObject *s)
969{
970 char *p;
971 int i, n;
972
973 if (!PyString_Check(s)) {
974 PyErr_SetString(PyExc_TypeError,
975 "__slots__ must be strings");
976 return 0;
977 }
978 p = PyString_AS_STRING(s);
979 n = PyString_GET_SIZE(s);
980 /* We must reject an empty name. As a hack, we bump the
981 length to 1 so that the loop will balk on the trailing \0. */
982 if (n == 0)
983 n = 1;
984 for (i = 0; i < n; i++, p++) {
985 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
986 PyErr_SetString(PyExc_TypeError,
987 "__slots__ must be identifiers");
988 return 0;
989 }
990 }
991 return 1;
992}
993
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000994static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
996{
997 PyObject *name, *bases, *dict;
998 static char *kwlist[] = {"name", "bases", "dict", 0};
999 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001000 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001002 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001003 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001004
Tim Peters3abca122001-10-27 19:37:48 +00001005 assert(args != NULL && PyTuple_Check(args));
1006 assert(kwds == NULL || PyDict_Check(kwds));
1007
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001008 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001009 {
1010 const int nargs = PyTuple_GET_SIZE(args);
1011 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1012
1013 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1014 PyObject *x = PyTuple_GET_ITEM(args, 0);
1015 Py_INCREF(x->ob_type);
1016 return (PyObject *) x->ob_type;
1017 }
1018
1019 /* SF bug 475327 -- if that didn't trigger, we need 3
1020 arguments. but PyArg_ParseTupleAndKeywords below may give
1021 a msg saying type() needs exactly 3. */
1022 if (nargs + nkwds != 3) {
1023 PyErr_SetString(PyExc_TypeError,
1024 "type() takes 1 or 3 arguments");
1025 return NULL;
1026 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027 }
1028
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001029 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1031 &name,
1032 &PyTuple_Type, &bases,
1033 &PyDict_Type, &dict))
1034 return NULL;
1035
1036 /* Determine the proper metatype to deal with this,
1037 and check for metatype conflicts while we're at it.
1038 Note that if some other metatype wins to contract,
1039 it's possible that its instances are not types. */
1040 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001041 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042 for (i = 0; i < nbases; i++) {
1043 tmp = PyTuple_GET_ITEM(bases, i);
1044 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001045 if (tmptype == &PyClass_Type)
1046 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001047 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001048 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001049 if (PyType_IsSubtype(tmptype, winner)) {
1050 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051 continue;
1052 }
1053 PyErr_SetString(PyExc_TypeError,
1054 "metatype conflict among bases");
1055 return NULL;
1056 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001057 if (winner != metatype) {
1058 if (winner->tp_new != type_new) /* Pass it to the winner */
1059 return winner->tp_new(winner, args, kwds);
1060 metatype = winner;
1061 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001062
1063 /* Adjust for empty tuple bases */
1064 if (nbases == 0) {
1065 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1066 if (bases == NULL)
1067 return NULL;
1068 nbases = 1;
1069 }
1070 else
1071 Py_INCREF(bases);
1072
1073 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1074
1075 /* Calculate best base, and check that all bases are type objects */
1076 base = best_base(bases);
1077 if (base == NULL)
1078 return NULL;
1079 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1080 PyErr_Format(PyExc_TypeError,
1081 "type '%.100s' is not an acceptable base type",
1082 base->tp_name);
1083 return NULL;
1084 }
1085
Tim Peters6d6c1a32001-08-02 04:15:00 +00001086 /* Check for a __slots__ sequence variable in dict, and count it */
1087 slots = PyDict_GetItemString(dict, "__slots__");
1088 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001089 add_dict = 0;
1090 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 if (slots != NULL) {
1092 /* Make it into a tuple */
1093 if (PyString_Check(slots))
1094 slots = Py_BuildValue("(O)", slots);
1095 else
1096 slots = PySequence_Tuple(slots);
1097 if (slots == NULL)
1098 return NULL;
1099 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001100 if (nslots > 0 && base->tp_itemsize != 0) {
1101 PyErr_Format(PyExc_TypeError,
1102 "nonempty __slots__ "
1103 "not supported for subtype of '%s'",
1104 base->tp_name);
1105 return NULL;
1106 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001108 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001109 Py_DECREF(slots);
1110 return NULL;
1111 }
1112 }
1113 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001114 if (slots != NULL) {
1115 /* See if *this* class defines __getstate__ */
1116 PyObject *getstate = PyDict_GetItemString(dict,
1117 "__getstate__");
1118 if (getstate == NULL) {
1119 /* If not, provide a bozo that raises TypeError */
1120 if (bozo_obj == NULL) {
1121 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1122 if (bozo_obj == NULL) {
1123 /* XXX decref various things */
1124 return NULL;
1125 }
1126 }
1127 if (PyDict_SetItemString(dict,
1128 "__getstate__",
1129 bozo_obj) < 0) {
1130 /* XXX decref various things */
1131 return NULL;
1132 }
1133 }
1134 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 if (slots == NULL && base->tp_dictoffset == 0 &&
1136 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001137 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001138 add_dict++;
1139 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001140 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1141 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001142 nslots++;
1143 add_weak++;
1144 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001145
1146 /* XXX From here until type is safely allocated,
1147 "return NULL" may leak slots! */
1148
1149 /* Allocate the type object */
1150 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1151 if (type == NULL)
1152 return NULL;
1153
1154 /* Keep name and slots alive in the extended type object */
1155 et = (etype *)type;
1156 Py_INCREF(name);
1157 et->name = name;
1158 et->slots = slots;
1159
Guido van Rossumdc91b992001-08-08 22:26:22 +00001160 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1162 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001163 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1164 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001165
1166 /* It's a new-style number unless it specifically inherits any
1167 old-style numeric behavior */
1168 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1169 (base->tp_as_number == NULL))
1170 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1171
1172 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173 type->tp_as_number = &et->as_number;
1174 type->tp_as_sequence = &et->as_sequence;
1175 type->tp_as_mapping = &et->as_mapping;
1176 type->tp_as_buffer = &et->as_buffer;
1177 type->tp_name = PyString_AS_STRING(name);
1178
1179 /* Set tp_base and tp_bases */
1180 type->tp_bases = bases;
1181 Py_INCREF(base);
1182 type->tp_base = base;
1183
Guido van Rossum687ae002001-10-15 22:03:32 +00001184 /* Initialize tp_dict from passed-in dict */
1185 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001186 if (dict == NULL) {
1187 Py_DECREF(type);
1188 return NULL;
1189 }
1190
Guido van Rossumc3542212001-08-16 09:18:56 +00001191 /* Set __module__ in the dict */
1192 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1193 tmp = PyEval_GetGlobals();
1194 if (tmp != NULL) {
1195 tmp = PyDict_GetItemString(tmp, "__name__");
1196 if (tmp != NULL) {
1197 if (PyDict_SetItemString(dict, "__module__",
1198 tmp) < 0)
1199 return NULL;
1200 }
1201 }
1202 }
1203
Tim Peters2f93e282001-10-04 05:27:00 +00001204 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001205 and is a string. The __doc__ accessor will first look for tp_doc;
1206 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001207 */
1208 {
1209 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1210 if (doc != NULL && PyString_Check(doc)) {
1211 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001212 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001213 if (type->tp_doc == NULL) {
1214 Py_DECREF(type);
1215 return NULL;
1216 }
1217 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1218 }
1219 }
1220
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 /* Special-case __new__: if it's a plain function,
1222 make it a static function */
1223 tmp = PyDict_GetItemString(dict, "__new__");
1224 if (tmp != NULL && PyFunction_Check(tmp)) {
1225 tmp = PyStaticMethod_New(tmp);
1226 if (tmp == NULL) {
1227 Py_DECREF(type);
1228 return NULL;
1229 }
1230 PyDict_SetItemString(dict, "__new__", tmp);
1231 Py_DECREF(tmp);
1232 }
1233
1234 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1235 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001236 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 if (slots != NULL) {
1238 for (i = 0; i < nslots; i++, mp++) {
1239 mp->name = PyString_AS_STRING(
1240 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001241 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001243 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001244 strcmp(mp->name, "__weakref__") == 0) {
1245 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001246 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001247 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001248 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 slotoffset += sizeof(PyObject *);
1250 }
1251 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001252 else {
1253 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001254 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001255 type->tp_dictoffset =
1256 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001257 else
1258 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001259 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001260 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001261 }
1262 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001263 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001264 type->tp_weaklistoffset = slotoffset;
1265 mp->name = "__weakref__";
1266 mp->type = T_OBJECT;
1267 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001268 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001269 mp++;
1270 slotoffset += sizeof(PyObject *);
1271 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272 }
1273 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001274 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001275 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276
1277 /* Special case some slots */
1278 if (type->tp_dictoffset != 0 || nslots > 0) {
1279 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1280 type->tp_getattro = PyObject_GenericGetAttr;
1281 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1282 type->tp_setattro = PyObject_GenericSetAttr;
1283 }
1284 type->tp_dealloc = subtype_dealloc;
1285
Guido van Rossum9475a232001-10-05 20:51:39 +00001286 /* Enable GC unless there are really no instance variables possible */
1287 if (!(type->tp_basicsize == sizeof(PyObject) &&
1288 type->tp_itemsize == 0))
1289 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1290
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291 /* Always override allocation strategy to use regular heap */
1292 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001293 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001294 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001295 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001296 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001297 }
1298 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001299 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300
1301 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001302 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 Py_DECREF(type);
1304 return NULL;
1305 }
1306
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001307 /* Put the proper slots in place */
1308 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001309
Tim Peters6d6c1a32001-08-02 04:15:00 +00001310 return (PyObject *)type;
1311}
1312
1313/* Internal API to look for a name through the MRO.
1314 This returns a borrowed reference, and doesn't set an exception! */
1315PyObject *
1316_PyType_Lookup(PyTypeObject *type, PyObject *name)
1317{
1318 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001319 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001320
Guido van Rossum687ae002001-10-15 22:03:32 +00001321 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001323
1324 /* If mro is NULL, the type is either not yet initialized
1325 by PyType_Ready(), or already cleared by type_clear().
1326 Either way the safest thing to do is to return NULL. */
1327 if (mro == NULL)
1328 return NULL;
1329
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 assert(PyTuple_Check(mro));
1331 n = PyTuple_GET_SIZE(mro);
1332 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001333 base = PyTuple_GET_ITEM(mro, i);
1334 if (PyClass_Check(base))
1335 dict = ((PyClassObject *)base)->cl_dict;
1336 else {
1337 assert(PyType_Check(base));
1338 dict = ((PyTypeObject *)base)->tp_dict;
1339 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 assert(dict && PyDict_Check(dict));
1341 res = PyDict_GetItem(dict, name);
1342 if (res != NULL)
1343 return res;
1344 }
1345 return NULL;
1346}
1347
1348/* This is similar to PyObject_GenericGetAttr(),
1349 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1350static PyObject *
1351type_getattro(PyTypeObject *type, PyObject *name)
1352{
1353 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001354 PyObject *meta_attribute, *attribute;
1355 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356
1357 /* Initialize this type (we'll assume the metatype is initialized) */
1358 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001359 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360 return NULL;
1361 }
1362
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001363 /* No readable descriptor found yet */
1364 meta_get = NULL;
1365
1366 /* Look for the attribute in the metatype */
1367 meta_attribute = _PyType_Lookup(metatype, name);
1368
1369 if (meta_attribute != NULL) {
1370 meta_get = meta_attribute->ob_type->tp_descr_get;
1371
1372 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1373 /* Data descriptors implement tp_descr_set to intercept
1374 * writes. Assume the attribute is not overridden in
1375 * type's tp_dict (and bases): call the descriptor now.
1376 */
1377 return meta_get(meta_attribute, (PyObject *)type,
1378 (PyObject *)metatype);
1379 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 }
1381
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001382 /* No data descriptor found on metatype. Look in tp_dict of this
1383 * type and its bases */
1384 attribute = _PyType_Lookup(type, name);
1385 if (attribute != NULL) {
1386 /* Implement descriptor functionality, if any */
1387 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1388 if (local_get != NULL) {
1389 /* NULL 2nd argument indicates the descriptor was
1390 * found on the target object itself (or a base) */
1391 return local_get(attribute, (PyObject *)NULL,
1392 (PyObject *)type);
1393 }
1394
1395 Py_INCREF(attribute);
1396 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001397 }
1398
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001399 /* No attribute found in local __dict__ (or bases): use the
1400 * descriptor from the metatype, if any */
1401 if (meta_get != NULL)
1402 return meta_get(meta_attribute, (PyObject *)type,
1403 (PyObject *)metatype);
1404
1405 /* If an ordinary attribute was found on the metatype, return it now */
1406 if (meta_attribute != NULL) {
1407 Py_INCREF(meta_attribute);
1408 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 }
1410
1411 /* Give up */
1412 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001413 "type object '%.50s' has no attribute '%.400s'",
1414 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415 return NULL;
1416}
1417
1418static int
1419type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1420{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001421 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1422 PyErr_Format(
1423 PyExc_TypeError,
1424 "can't set attributes of built-in/extension type '%s'",
1425 type->tp_name);
1426 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001427 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001428 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1429 return -1;
1430 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431}
1432
1433static void
1434type_dealloc(PyTypeObject *type)
1435{
1436 etype *et;
1437
1438 /* Assert this is a heap-allocated type object */
1439 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001440 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001441 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442 et = (etype *)type;
1443 Py_XDECREF(type->tp_base);
1444 Py_XDECREF(type->tp_dict);
1445 Py_XDECREF(type->tp_bases);
1446 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001447 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001448 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449 Py_XDECREF(et->name);
1450 Py_XDECREF(et->slots);
1451 type->ob_type->tp_free((PyObject *)type);
1452}
1453
Guido van Rossum1c450732001-10-08 15:18:27 +00001454static PyObject *
1455type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1456{
1457 PyObject *list, *raw, *ref;
1458 int i, n;
1459
1460 list = PyList_New(0);
1461 if (list == NULL)
1462 return NULL;
1463 raw = type->tp_subclasses;
1464 if (raw == NULL)
1465 return list;
1466 assert(PyList_Check(raw));
1467 n = PyList_GET_SIZE(raw);
1468 for (i = 0; i < n; i++) {
1469 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001470 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001471 ref = PyWeakref_GET_OBJECT(ref);
1472 if (ref != Py_None) {
1473 if (PyList_Append(list, ref) < 0) {
1474 Py_DECREF(list);
1475 return NULL;
1476 }
1477 }
1478 }
1479 return list;
1480}
1481
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001483 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001485 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1486 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487 {0}
1488};
1489
1490static char type_doc[] =
1491"type(object) -> the object's type\n"
1492"type(name, bases, dict) -> a new type";
1493
Guido van Rossum048eb752001-10-02 21:24:57 +00001494static int
1495type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1496{
Guido van Rossum048eb752001-10-02 21:24:57 +00001497 int err;
1498
Guido van Rossuma3862092002-06-10 15:24:42 +00001499 /* Because of type_is_gc(), the collector only calls this
1500 for heaptypes. */
1501 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001502
1503#define VISIT(SLOT) \
1504 if (SLOT) { \
1505 err = visit((PyObject *)(SLOT), arg); \
1506 if (err) \
1507 return err; \
1508 }
1509
1510 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001511 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001512 VISIT(type->tp_mro);
1513 VISIT(type->tp_bases);
1514 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001515
1516 /* There's no need to visit type->tp_subclasses or
1517 ((etype *)type)->slots, because they can't be involved
1518 in cycles; tp_subclasses is a list of weak references,
1519 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001520
1521#undef VISIT
1522
1523 return 0;
1524}
1525
1526static int
1527type_clear(PyTypeObject *type)
1528{
Guido van Rossum048eb752001-10-02 21:24:57 +00001529 PyObject *tmp;
1530
Guido van Rossuma3862092002-06-10 15:24:42 +00001531 /* Because of type_is_gc(), the collector only calls this
1532 for heaptypes. */
1533 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001534
1535#define CLEAR(SLOT) \
1536 if (SLOT) { \
1537 tmp = (PyObject *)(SLOT); \
1538 SLOT = NULL; \
1539 Py_DECREF(tmp); \
1540 }
1541
Guido van Rossuma3862092002-06-10 15:24:42 +00001542 /* The only field we need to clear is tp_mro, which is part of a
1543 hard cycle (its first element is the class itself) that won't
1544 be broken otherwise (it's a tuple and tuples don't have a
1545 tp_clear handler). None of the other fields need to be
1546 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001547
Guido van Rossuma3862092002-06-10 15:24:42 +00001548 tp_dict:
1549 It is a dict, so the collector will call its tp_clear.
1550
1551 tp_cache:
1552 Not used; if it were, it would be a dict.
1553
1554 tp_bases, tp_base:
1555 If these are involved in a cycle, there must be at least
1556 one other, mutable object in the cycle, e.g. a base
1557 class's dict; the cycle will be broken that way.
1558
1559 tp_subclasses:
1560 A list of weak references can't be part of a cycle; and
1561 lists have their own tp_clear.
1562
1563 slots (in etype):
1564 A tuple of strings can't be part of a cycle.
1565 */
1566
1567 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001568
Guido van Rossum048eb752001-10-02 21:24:57 +00001569#undef CLEAR
1570
1571 return 0;
1572}
1573
1574static int
1575type_is_gc(PyTypeObject *type)
1576{
1577 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1578}
1579
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001580PyTypeObject PyType_Type = {
1581 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001582 0, /* ob_size */
1583 "type", /* tp_name */
1584 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001585 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 (destructor)type_dealloc, /* tp_dealloc */
1587 0, /* tp_print */
1588 0, /* tp_getattr */
1589 0, /* tp_setattr */
1590 type_compare, /* tp_compare */
1591 (reprfunc)type_repr, /* tp_repr */
1592 0, /* tp_as_number */
1593 0, /* tp_as_sequence */
1594 0, /* tp_as_mapping */
1595 (hashfunc)_Py_HashPointer, /* tp_hash */
1596 (ternaryfunc)type_call, /* tp_call */
1597 0, /* tp_str */
1598 (getattrofunc)type_getattro, /* tp_getattro */
1599 (setattrofunc)type_setattro, /* tp_setattro */
1600 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001601 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1602 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001604 (traverseproc)type_traverse, /* tp_traverse */
1605 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001607 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001608 0, /* tp_iter */
1609 0, /* tp_iternext */
1610 type_methods, /* tp_methods */
1611 type_members, /* tp_members */
1612 type_getsets, /* tp_getset */
1613 0, /* tp_base */
1614 0, /* tp_dict */
1615 0, /* tp_descr_get */
1616 0, /* tp_descr_set */
1617 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1618 0, /* tp_init */
1619 0, /* tp_alloc */
1620 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001621 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001622 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001623};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001624
1625
1626/* The base type of all types (eventually)... except itself. */
1627
1628static int
1629object_init(PyObject *self, PyObject *args, PyObject *kwds)
1630{
1631 return 0;
1632}
1633
1634static void
1635object_dealloc(PyObject *self)
1636{
1637 self->ob_type->tp_free(self);
1638}
1639
Guido van Rossum8e248182001-08-12 05:17:56 +00001640static PyObject *
1641object_repr(PyObject *self)
1642{
Guido van Rossum76e69632001-08-16 18:52:43 +00001643 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001644 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001645
Guido van Rossum76e69632001-08-16 18:52:43 +00001646 type = self->ob_type;
1647 mod = type_module(type, NULL);
1648 if (mod == NULL)
1649 PyErr_Clear();
1650 else if (!PyString_Check(mod)) {
1651 Py_DECREF(mod);
1652 mod = NULL;
1653 }
1654 name = type_name(type, NULL);
1655 if (name == NULL)
1656 return NULL;
1657 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001658 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001659 PyString_AS_STRING(mod),
1660 PyString_AS_STRING(name),
1661 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001662 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001663 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001664 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001665 Py_XDECREF(mod);
1666 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001667 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001668}
1669
Guido van Rossumb8f63662001-08-15 23:57:02 +00001670static PyObject *
1671object_str(PyObject *self)
1672{
1673 unaryfunc f;
1674
1675 f = self->ob_type->tp_repr;
1676 if (f == NULL)
1677 f = object_repr;
1678 return f(self);
1679}
1680
Guido van Rossum8e248182001-08-12 05:17:56 +00001681static long
1682object_hash(PyObject *self)
1683{
1684 return _Py_HashPointer(self);
1685}
Guido van Rossum8e248182001-08-12 05:17:56 +00001686
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001687static PyObject *
1688object_get_class(PyObject *self, void *closure)
1689{
1690 Py_INCREF(self->ob_type);
1691 return (PyObject *)(self->ob_type);
1692}
1693
1694static int
1695equiv_structs(PyTypeObject *a, PyTypeObject *b)
1696{
1697 return a == b ||
1698 (a != NULL &&
1699 b != NULL &&
1700 a->tp_basicsize == b->tp_basicsize &&
1701 a->tp_itemsize == b->tp_itemsize &&
1702 a->tp_dictoffset == b->tp_dictoffset &&
1703 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1704 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1705 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1706}
1707
1708static int
1709same_slots_added(PyTypeObject *a, PyTypeObject *b)
1710{
1711 PyTypeObject *base = a->tp_base;
1712 int size;
1713
1714 if (base != b->tp_base)
1715 return 0;
1716 if (equiv_structs(a, base) && equiv_structs(b, base))
1717 return 1;
1718 size = base->tp_basicsize;
1719 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1720 size += sizeof(PyObject *);
1721 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1722 size += sizeof(PyObject *);
1723 return size == a->tp_basicsize && size == b->tp_basicsize;
1724}
1725
1726static int
1727object_set_class(PyObject *self, PyObject *value, void *closure)
1728{
1729 PyTypeObject *old = self->ob_type;
1730 PyTypeObject *new, *newbase, *oldbase;
1731
Guido van Rossumb6b89422002-04-15 01:03:30 +00001732 if (value == NULL) {
1733 PyErr_SetString(PyExc_TypeError,
1734 "can't delete __class__ attribute");
1735 return -1;
1736 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001737 if (!PyType_Check(value)) {
1738 PyErr_Format(PyExc_TypeError,
1739 "__class__ must be set to new-style class, not '%s' object",
1740 value->ob_type->tp_name);
1741 return -1;
1742 }
1743 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001744 if (new->tp_dealloc != old->tp_dealloc ||
1745 new->tp_free != old->tp_free)
1746 {
1747 PyErr_Format(PyExc_TypeError,
1748 "__class__ assignment: "
1749 "'%s' deallocator differs from '%s'",
1750 new->tp_name,
1751 old->tp_name);
1752 return -1;
1753 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001754 newbase = new;
1755 oldbase = old;
1756 while (equiv_structs(newbase, newbase->tp_base))
1757 newbase = newbase->tp_base;
1758 while (equiv_structs(oldbase, oldbase->tp_base))
1759 oldbase = oldbase->tp_base;
1760 if (newbase != oldbase &&
1761 (newbase->tp_base != oldbase->tp_base ||
1762 !same_slots_added(newbase, oldbase))) {
1763 PyErr_Format(PyExc_TypeError,
1764 "__class__ assignment: "
1765 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001766 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001767 old->tp_name);
1768 return -1;
1769 }
1770 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1771 Py_INCREF(new);
1772 }
1773 self->ob_type = new;
1774 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1775 Py_DECREF(old);
1776 }
1777 return 0;
1778}
1779
1780static PyGetSetDef object_getsets[] = {
1781 {"__class__", object_get_class, object_set_class,
1782 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 {0}
1784};
1785
Guido van Rossum3926a632001-09-25 16:25:58 +00001786static PyObject *
1787object_reduce(PyObject *self, PyObject *args)
1788{
1789 /* Call copy_reg._reduce(self) */
1790 static PyObject *copy_reg_str;
1791 PyObject *copy_reg, *res;
1792
1793 if (!copy_reg_str) {
1794 copy_reg_str = PyString_InternFromString("copy_reg");
1795 if (copy_reg_str == NULL)
1796 return NULL;
1797 }
1798 copy_reg = PyImport_Import(copy_reg_str);
1799 if (!copy_reg)
1800 return NULL;
1801 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1802 Py_DECREF(copy_reg);
1803 return res;
1804}
1805
1806static PyMethodDef object_methods[] = {
1807 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1808 {0}
1809};
1810
Tim Peters6d6c1a32001-08-02 04:15:00 +00001811PyTypeObject PyBaseObject_Type = {
1812 PyObject_HEAD_INIT(&PyType_Type)
1813 0, /* ob_size */
1814 "object", /* tp_name */
1815 sizeof(PyObject), /* tp_basicsize */
1816 0, /* tp_itemsize */
1817 (destructor)object_dealloc, /* tp_dealloc */
1818 0, /* tp_print */
1819 0, /* tp_getattr */
1820 0, /* tp_setattr */
1821 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001822 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 0, /* tp_as_number */
1824 0, /* tp_as_sequence */
1825 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001826 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001827 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001828 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001830 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 0, /* tp_as_buffer */
1832 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1833 "The most base type", /* tp_doc */
1834 0, /* tp_traverse */
1835 0, /* tp_clear */
1836 0, /* tp_richcompare */
1837 0, /* tp_weaklistoffset */
1838 0, /* tp_iter */
1839 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001840 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001841 0, /* tp_members */
1842 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 0, /* tp_base */
1844 0, /* tp_dict */
1845 0, /* tp_descr_get */
1846 0, /* tp_descr_set */
1847 0, /* tp_dictoffset */
1848 object_init, /* tp_init */
1849 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001850 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001851 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852};
1853
1854
1855/* Initialize the __dict__ in a type object */
1856
Fred Drake7bf97152002-03-28 05:33:33 +00001857static PyObject *
1858create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1859{
1860 PyObject *cfunc;
1861 PyObject *result;
1862
1863 cfunc = PyCFunction_New(meth, NULL);
1864 if (cfunc == NULL)
1865 return NULL;
1866 result = func(cfunc);
1867 Py_DECREF(cfunc);
1868 return result;
1869}
1870
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871static int
1872add_methods(PyTypeObject *type, PyMethodDef *meth)
1873{
Guido van Rossum687ae002001-10-15 22:03:32 +00001874 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875
1876 for (; meth->ml_name != NULL; meth++) {
1877 PyObject *descr;
1878 if (PyDict_GetItemString(dict, meth->ml_name))
1879 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001880 if (meth->ml_flags & METH_CLASS) {
1881 if (meth->ml_flags & METH_STATIC) {
1882 PyErr_SetString(PyExc_ValueError,
1883 "method cannot be both class and static");
1884 return -1;
1885 }
1886 descr = create_specialmethod(meth, PyClassMethod_New);
1887 }
1888 else if (meth->ml_flags & METH_STATIC) {
1889 descr = create_specialmethod(meth, PyStaticMethod_New);
1890 }
1891 else {
1892 descr = PyDescr_NewMethod(type, meth);
1893 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001894 if (descr == NULL)
1895 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001896 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897 return -1;
1898 Py_DECREF(descr);
1899 }
1900 return 0;
1901}
1902
1903static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001904add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905{
Guido van Rossum687ae002001-10-15 22:03:32 +00001906 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001907
1908 for (; memb->name != NULL; memb++) {
1909 PyObject *descr;
1910 if (PyDict_GetItemString(dict, memb->name))
1911 continue;
1912 descr = PyDescr_NewMember(type, memb);
1913 if (descr == NULL)
1914 return -1;
1915 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1916 return -1;
1917 Py_DECREF(descr);
1918 }
1919 return 0;
1920}
1921
1922static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001923add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001924{
Guido van Rossum687ae002001-10-15 22:03:32 +00001925 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926
1927 for (; gsp->name != NULL; gsp++) {
1928 PyObject *descr;
1929 if (PyDict_GetItemString(dict, gsp->name))
1930 continue;
1931 descr = PyDescr_NewGetSet(type, gsp);
1932
1933 if (descr == NULL)
1934 return -1;
1935 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1936 return -1;
1937 Py_DECREF(descr);
1938 }
1939 return 0;
1940}
1941
Guido van Rossum13d52f02001-08-10 21:24:08 +00001942static void
1943inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001944{
1945 int oldsize, newsize;
1946
Guido van Rossum13d52f02001-08-10 21:24:08 +00001947 /* Special flag magic */
1948 if (!type->tp_as_buffer && base->tp_as_buffer) {
1949 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1950 type->tp_flags |=
1951 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1952 }
1953 if (!type->tp_as_sequence && base->tp_as_sequence) {
1954 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1955 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1956 }
1957 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1958 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1959 if ((!type->tp_as_number && base->tp_as_number) ||
1960 (!type->tp_as_sequence && base->tp_as_sequence)) {
1961 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1962 if (!type->tp_as_number && !type->tp_as_sequence) {
1963 type->tp_flags |= base->tp_flags &
1964 Py_TPFLAGS_HAVE_INPLACEOPS;
1965 }
1966 }
1967 /* Wow */
1968 }
1969 if (!type->tp_as_number && base->tp_as_number) {
1970 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1971 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1972 }
1973
1974 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001975 oldsize = base->tp_basicsize;
1976 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1977 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1978 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001979 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1980 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001981 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001982 if (type->tp_traverse == NULL)
1983 type->tp_traverse = base->tp_traverse;
1984 if (type->tp_clear == NULL)
1985 type->tp_clear = base->tp_clear;
1986 }
1987 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001988 /* The condition below could use some explanation.
1989 It appears that tp_new is not inherited for static types
1990 whose base class is 'object'; this seems to be a precaution
1991 so that old extension types don't suddenly become
1992 callable (object.__new__ wouldn't insure the invariants
1993 that the extension type's own factory function ensures).
1994 Heap types, of course, are under our control, so they do
1995 inherit tp_new; static extension types that specify some
1996 other built-in type as the default are considered
1997 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001998 if (base != &PyBaseObject_Type ||
1999 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2000 if (type->tp_new == NULL)
2001 type->tp_new = base->tp_new;
2002 }
2003 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002004 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002005
2006 /* Copy other non-function slots */
2007
2008#undef COPYVAL
2009#define COPYVAL(SLOT) \
2010 if (type->SLOT == 0) type->SLOT = base->SLOT
2011
2012 COPYVAL(tp_itemsize);
2013 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2014 COPYVAL(tp_weaklistoffset);
2015 }
2016 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2017 COPYVAL(tp_dictoffset);
2018 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002019}
2020
2021static void
2022inherit_slots(PyTypeObject *type, PyTypeObject *base)
2023{
2024 PyTypeObject *basebase;
2025
2026#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027#undef COPYSLOT
2028#undef COPYNUM
2029#undef COPYSEQ
2030#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002031#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002032
2033#define SLOTDEFINED(SLOT) \
2034 (base->SLOT != 0 && \
2035 (basebase == NULL || base->SLOT != basebase->SLOT))
2036
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002038 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039
2040#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2041#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2042#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002043#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002044
Guido van Rossum13d52f02001-08-10 21:24:08 +00002045 /* This won't inherit indirect slots (from tp_as_number etc.)
2046 if type doesn't provide the space. */
2047
2048 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2049 basebase = base->tp_base;
2050 if (basebase->tp_as_number == NULL)
2051 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052 COPYNUM(nb_add);
2053 COPYNUM(nb_subtract);
2054 COPYNUM(nb_multiply);
2055 COPYNUM(nb_divide);
2056 COPYNUM(nb_remainder);
2057 COPYNUM(nb_divmod);
2058 COPYNUM(nb_power);
2059 COPYNUM(nb_negative);
2060 COPYNUM(nb_positive);
2061 COPYNUM(nb_absolute);
2062 COPYNUM(nb_nonzero);
2063 COPYNUM(nb_invert);
2064 COPYNUM(nb_lshift);
2065 COPYNUM(nb_rshift);
2066 COPYNUM(nb_and);
2067 COPYNUM(nb_xor);
2068 COPYNUM(nb_or);
2069 COPYNUM(nb_coerce);
2070 COPYNUM(nb_int);
2071 COPYNUM(nb_long);
2072 COPYNUM(nb_float);
2073 COPYNUM(nb_oct);
2074 COPYNUM(nb_hex);
2075 COPYNUM(nb_inplace_add);
2076 COPYNUM(nb_inplace_subtract);
2077 COPYNUM(nb_inplace_multiply);
2078 COPYNUM(nb_inplace_divide);
2079 COPYNUM(nb_inplace_remainder);
2080 COPYNUM(nb_inplace_power);
2081 COPYNUM(nb_inplace_lshift);
2082 COPYNUM(nb_inplace_rshift);
2083 COPYNUM(nb_inplace_and);
2084 COPYNUM(nb_inplace_xor);
2085 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002086 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2087 COPYNUM(nb_true_divide);
2088 COPYNUM(nb_floor_divide);
2089 COPYNUM(nb_inplace_true_divide);
2090 COPYNUM(nb_inplace_floor_divide);
2091 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092 }
2093
Guido van Rossum13d52f02001-08-10 21:24:08 +00002094 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2095 basebase = base->tp_base;
2096 if (basebase->tp_as_sequence == NULL)
2097 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098 COPYSEQ(sq_length);
2099 COPYSEQ(sq_concat);
2100 COPYSEQ(sq_repeat);
2101 COPYSEQ(sq_item);
2102 COPYSEQ(sq_slice);
2103 COPYSEQ(sq_ass_item);
2104 COPYSEQ(sq_ass_slice);
2105 COPYSEQ(sq_contains);
2106 COPYSEQ(sq_inplace_concat);
2107 COPYSEQ(sq_inplace_repeat);
2108 }
2109
Guido van Rossum13d52f02001-08-10 21:24:08 +00002110 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2111 basebase = base->tp_base;
2112 if (basebase->tp_as_mapping == NULL)
2113 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114 COPYMAP(mp_length);
2115 COPYMAP(mp_subscript);
2116 COPYMAP(mp_ass_subscript);
2117 }
2118
Tim Petersfc57ccb2001-10-12 02:38:24 +00002119 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2120 basebase = base->tp_base;
2121 if (basebase->tp_as_buffer == NULL)
2122 basebase = NULL;
2123 COPYBUF(bf_getreadbuffer);
2124 COPYBUF(bf_getwritebuffer);
2125 COPYBUF(bf_getsegcount);
2126 COPYBUF(bf_getcharbuffer);
2127 }
2128
Guido van Rossum13d52f02001-08-10 21:24:08 +00002129 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130
Tim Peters6d6c1a32001-08-02 04:15:00 +00002131 COPYSLOT(tp_dealloc);
2132 COPYSLOT(tp_print);
2133 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2134 type->tp_getattr = base->tp_getattr;
2135 type->tp_getattro = base->tp_getattro;
2136 }
2137 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2138 type->tp_setattr = base->tp_setattr;
2139 type->tp_setattro = base->tp_setattro;
2140 }
2141 /* tp_compare see tp_richcompare */
2142 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002143 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144 COPYSLOT(tp_call);
2145 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002147 if (type->tp_compare == NULL &&
2148 type->tp_richcompare == NULL &&
2149 type->tp_hash == NULL)
2150 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151 type->tp_compare = base->tp_compare;
2152 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002153 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154 }
2155 }
2156 else {
2157 COPYSLOT(tp_compare);
2158 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002159 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2160 COPYSLOT(tp_iter);
2161 COPYSLOT(tp_iternext);
2162 }
2163 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2164 COPYSLOT(tp_descr_get);
2165 COPYSLOT(tp_descr_set);
2166 COPYSLOT(tp_dictoffset);
2167 COPYSLOT(tp_init);
2168 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002169 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002170 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002171 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002172}
2173
Guido van Rossum13d52f02001-08-10 21:24:08 +00002174staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002175staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002176
Tim Peters6d6c1a32001-08-02 04:15:00 +00002177int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002178PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002179{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002180 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002181 PyTypeObject *base;
2182 int i, n;
2183
Guido van Rossumcab05802002-06-10 15:29:03 +00002184 if (type->tp_flags & Py_TPFLAGS_READY) {
2185 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002186 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002187 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002188 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002189
2190 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002191
2192 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2193 base = type->tp_base;
2194 if (base == NULL && type != &PyBaseObject_Type)
2195 base = type->tp_base = &PyBaseObject_Type;
2196
Guido van Rossum0986d822002-04-08 01:38:42 +00002197 /* Initialize ob_type if NULL. This means extensions that want to be
2198 compilable separately on Windows can call PyType_Ready() instead of
2199 initializing the ob_type field of their type objects. */
2200 if (type->ob_type == NULL)
2201 type->ob_type = base->ob_type;
2202
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203 /* Initialize tp_bases */
2204 bases = type->tp_bases;
2205 if (bases == NULL) {
2206 if (base == NULL)
2207 bases = PyTuple_New(0);
2208 else
2209 bases = Py_BuildValue("(O)", base);
2210 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002211 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212 type->tp_bases = bases;
2213 }
2214
2215 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002216 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002217 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002218 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219 }
2220
Guido van Rossum687ae002001-10-15 22:03:32 +00002221 /* Initialize tp_dict */
2222 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 if (dict == NULL) {
2224 dict = PyDict_New();
2225 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002226 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002227 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228 }
2229
Guido van Rossum687ae002001-10-15 22:03:32 +00002230 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002232 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002233 if (type->tp_methods != NULL) {
2234 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002235 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002236 }
2237 if (type->tp_members != NULL) {
2238 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002239 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240 }
2241 if (type->tp_getset != NULL) {
2242 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002243 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244 }
2245
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246 /* Calculate method resolution order */
2247 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002248 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002249 }
2250
Guido van Rossum13d52f02001-08-10 21:24:08 +00002251 /* Inherit special flags from dominant base */
2252 if (type->tp_base != NULL)
2253 inherit_special(type, type->tp_base);
2254
Tim Peters6d6c1a32001-08-02 04:15:00 +00002255 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002256 bases = type->tp_mro;
2257 assert(bases != NULL);
2258 assert(PyTuple_Check(bases));
2259 n = PyTuple_GET_SIZE(bases);
2260 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002261 PyObject *b = PyTuple_GET_ITEM(bases, i);
2262 if (PyType_Check(b))
2263 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002264 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002265
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002266 /* if the type dictionary doesn't contain a __doc__, set it from
2267 the tp_doc slot.
2268 */
2269 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2270 if (type->tp_doc != NULL) {
2271 PyObject *doc = PyString_FromString(type->tp_doc);
2272 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2273 Py_DECREF(doc);
2274 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002275 PyDict_SetItemString(type->tp_dict,
2276 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002277 }
2278 }
2279
Guido van Rossum13d52f02001-08-10 21:24:08 +00002280 /* Some more special stuff */
2281 base = type->tp_base;
2282 if (base != NULL) {
2283 if (type->tp_as_number == NULL)
2284 type->tp_as_number = base->tp_as_number;
2285 if (type->tp_as_sequence == NULL)
2286 type->tp_as_sequence = base->tp_as_sequence;
2287 if (type->tp_as_mapping == NULL)
2288 type->tp_as_mapping = base->tp_as_mapping;
2289 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290
Guido van Rossum1c450732001-10-08 15:18:27 +00002291 /* Link into each base class's list of subclasses */
2292 bases = type->tp_bases;
2293 n = PyTuple_GET_SIZE(bases);
2294 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002295 PyObject *b = PyTuple_GET_ITEM(bases, i);
2296 if (PyType_Check(b) &&
2297 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002298 goto error;
2299 }
2300
Guido van Rossum13d52f02001-08-10 21:24:08 +00002301 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002302 assert(type->tp_dict != NULL);
2303 type->tp_flags =
2304 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002306
2307 error:
2308 type->tp_flags &= ~Py_TPFLAGS_READYING;
2309 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002310}
2311
Guido van Rossum1c450732001-10-08 15:18:27 +00002312static int
2313add_subclass(PyTypeObject *base, PyTypeObject *type)
2314{
2315 int i;
2316 PyObject *list, *ref, *new;
2317
2318 list = base->tp_subclasses;
2319 if (list == NULL) {
2320 base->tp_subclasses = list = PyList_New(0);
2321 if (list == NULL)
2322 return -1;
2323 }
2324 assert(PyList_Check(list));
2325 new = PyWeakref_NewRef((PyObject *)type, NULL);
2326 i = PyList_GET_SIZE(list);
2327 while (--i >= 0) {
2328 ref = PyList_GET_ITEM(list, i);
2329 assert(PyWeakref_CheckRef(ref));
2330 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2331 return PyList_SetItem(list, i, new);
2332 }
2333 i = PyList_Append(list, new);
2334 Py_DECREF(new);
2335 return i;
2336}
2337
Tim Peters6d6c1a32001-08-02 04:15:00 +00002338
2339/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2340
2341/* There's a wrapper *function* for each distinct function typedef used
2342 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2343 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2344 Most tables have only one entry; the tables for binary operators have two
2345 entries, one regular and one with reversed arguments. */
2346
2347static PyObject *
2348wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2349{
2350 inquiry func = (inquiry)wrapped;
2351 int res;
2352
2353 if (!PyArg_ParseTuple(args, ""))
2354 return NULL;
2355 res = (*func)(self);
2356 if (res == -1 && PyErr_Occurred())
2357 return NULL;
2358 return PyInt_FromLong((long)res);
2359}
2360
Tim Peters6d6c1a32001-08-02 04:15:00 +00002361static PyObject *
2362wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2363{
2364 binaryfunc func = (binaryfunc)wrapped;
2365 PyObject *other;
2366
2367 if (!PyArg_ParseTuple(args, "O", &other))
2368 return NULL;
2369 return (*func)(self, other);
2370}
2371
2372static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002373wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2374{
2375 binaryfunc func = (binaryfunc)wrapped;
2376 PyObject *other;
2377
2378 if (!PyArg_ParseTuple(args, "O", &other))
2379 return NULL;
2380 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002381 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002382 Py_INCREF(Py_NotImplemented);
2383 return Py_NotImplemented;
2384 }
2385 return (*func)(self, other);
2386}
2387
2388static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2390{
2391 binaryfunc func = (binaryfunc)wrapped;
2392 PyObject *other;
2393
2394 if (!PyArg_ParseTuple(args, "O", &other))
2395 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002396 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002397 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002398 Py_INCREF(Py_NotImplemented);
2399 return Py_NotImplemented;
2400 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401 return (*func)(other, self);
2402}
2403
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002404static PyObject *
2405wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2406{
2407 coercion func = (coercion)wrapped;
2408 PyObject *other, *res;
2409 int ok;
2410
2411 if (!PyArg_ParseTuple(args, "O", &other))
2412 return NULL;
2413 ok = func(&self, &other);
2414 if (ok < 0)
2415 return NULL;
2416 if (ok > 0) {
2417 Py_INCREF(Py_NotImplemented);
2418 return Py_NotImplemented;
2419 }
2420 res = PyTuple_New(2);
2421 if (res == NULL) {
2422 Py_DECREF(self);
2423 Py_DECREF(other);
2424 return NULL;
2425 }
2426 PyTuple_SET_ITEM(res, 0, self);
2427 PyTuple_SET_ITEM(res, 1, other);
2428 return res;
2429}
2430
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431static PyObject *
2432wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2433{
2434 ternaryfunc func = (ternaryfunc)wrapped;
2435 PyObject *other;
2436 PyObject *third = Py_None;
2437
2438 /* Note: This wrapper only works for __pow__() */
2439
2440 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2441 return NULL;
2442 return (*func)(self, other, third);
2443}
2444
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002445static PyObject *
2446wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2447{
2448 ternaryfunc func = (ternaryfunc)wrapped;
2449 PyObject *other;
2450 PyObject *third = Py_None;
2451
2452 /* Note: This wrapper only works for __pow__() */
2453
2454 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2455 return NULL;
2456 return (*func)(other, self, third);
2457}
2458
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459static PyObject *
2460wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2461{
2462 unaryfunc func = (unaryfunc)wrapped;
2463
2464 if (!PyArg_ParseTuple(args, ""))
2465 return NULL;
2466 return (*func)(self);
2467}
2468
Tim Peters6d6c1a32001-08-02 04:15:00 +00002469static PyObject *
2470wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2471{
2472 intargfunc func = (intargfunc)wrapped;
2473 int i;
2474
2475 if (!PyArg_ParseTuple(args, "i", &i))
2476 return NULL;
2477 return (*func)(self, i);
2478}
2479
Guido van Rossum5d815f32001-08-17 21:57:47 +00002480static int
2481getindex(PyObject *self, PyObject *arg)
2482{
2483 int i;
2484
2485 i = PyInt_AsLong(arg);
2486 if (i == -1 && PyErr_Occurred())
2487 return -1;
2488 if (i < 0) {
2489 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2490 if (sq && sq->sq_length) {
2491 int n = (*sq->sq_length)(self);
2492 if (n < 0)
2493 return -1;
2494 i += n;
2495 }
2496 }
2497 return i;
2498}
2499
2500static PyObject *
2501wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2502{
2503 intargfunc func = (intargfunc)wrapped;
2504 PyObject *arg;
2505 int i;
2506
Guido van Rossumf4593e02001-10-03 12:09:30 +00002507 if (PyTuple_GET_SIZE(args) == 1) {
2508 arg = PyTuple_GET_ITEM(args, 0);
2509 i = getindex(self, arg);
2510 if (i == -1 && PyErr_Occurred())
2511 return NULL;
2512 return (*func)(self, i);
2513 }
2514 PyArg_ParseTuple(args, "O", &arg);
2515 assert(PyErr_Occurred());
2516 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002517}
2518
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519static PyObject *
2520wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2521{
2522 intintargfunc func = (intintargfunc)wrapped;
2523 int i, j;
2524
2525 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2526 return NULL;
2527 return (*func)(self, i, j);
2528}
2529
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002531wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532{
2533 intobjargproc func = (intobjargproc)wrapped;
2534 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002535 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002536
Guido van Rossum5d815f32001-08-17 21:57:47 +00002537 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2538 return NULL;
2539 i = getindex(self, arg);
2540 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541 return NULL;
2542 res = (*func)(self, i, value);
2543 if (res == -1 && PyErr_Occurred())
2544 return NULL;
2545 Py_INCREF(Py_None);
2546 return Py_None;
2547}
2548
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002549static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002550wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002551{
2552 intobjargproc func = (intobjargproc)wrapped;
2553 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002554 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002555
Guido van Rossum5d815f32001-08-17 21:57:47 +00002556 if (!PyArg_ParseTuple(args, "O", &arg))
2557 return NULL;
2558 i = getindex(self, arg);
2559 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002560 return NULL;
2561 res = (*func)(self, i, NULL);
2562 if (res == -1 && PyErr_Occurred())
2563 return NULL;
2564 Py_INCREF(Py_None);
2565 return Py_None;
2566}
2567
Tim Peters6d6c1a32001-08-02 04:15:00 +00002568static PyObject *
2569wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2570{
2571 intintobjargproc func = (intintobjargproc)wrapped;
2572 int i, j, res;
2573 PyObject *value;
2574
2575 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2576 return NULL;
2577 res = (*func)(self, i, j, value);
2578 if (res == -1 && PyErr_Occurred())
2579 return NULL;
2580 Py_INCREF(Py_None);
2581 return Py_None;
2582}
2583
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002584static PyObject *
2585wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2586{
2587 intintobjargproc func = (intintobjargproc)wrapped;
2588 int i, j, res;
2589
2590 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2591 return NULL;
2592 res = (*func)(self, i, j, NULL);
2593 if (res == -1 && PyErr_Occurred())
2594 return NULL;
2595 Py_INCREF(Py_None);
2596 return Py_None;
2597}
2598
Tim Peters6d6c1a32001-08-02 04:15:00 +00002599/* XXX objobjproc is a misnomer; should be objargpred */
2600static PyObject *
2601wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2602{
2603 objobjproc func = (objobjproc)wrapped;
2604 int res;
2605 PyObject *value;
2606
2607 if (!PyArg_ParseTuple(args, "O", &value))
2608 return NULL;
2609 res = (*func)(self, value);
2610 if (res == -1 && PyErr_Occurred())
2611 return NULL;
2612 return PyInt_FromLong((long)res);
2613}
2614
Tim Peters6d6c1a32001-08-02 04:15:00 +00002615static PyObject *
2616wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2617{
2618 objobjargproc func = (objobjargproc)wrapped;
2619 int res;
2620 PyObject *key, *value;
2621
2622 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2623 return NULL;
2624 res = (*func)(self, key, value);
2625 if (res == -1 && PyErr_Occurred())
2626 return NULL;
2627 Py_INCREF(Py_None);
2628 return Py_None;
2629}
2630
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002631static PyObject *
2632wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2633{
2634 objobjargproc func = (objobjargproc)wrapped;
2635 int res;
2636 PyObject *key;
2637
2638 if (!PyArg_ParseTuple(args, "O", &key))
2639 return NULL;
2640 res = (*func)(self, key, NULL);
2641 if (res == -1 && PyErr_Occurred())
2642 return NULL;
2643 Py_INCREF(Py_None);
2644 return Py_None;
2645}
2646
Tim Peters6d6c1a32001-08-02 04:15:00 +00002647static PyObject *
2648wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2649{
2650 cmpfunc func = (cmpfunc)wrapped;
2651 int res;
2652 PyObject *other;
2653
2654 if (!PyArg_ParseTuple(args, "O", &other))
2655 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002656 if (other->ob_type->tp_compare != func &&
2657 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002658 PyErr_Format(
2659 PyExc_TypeError,
2660 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2661 self->ob_type->tp_name,
2662 self->ob_type->tp_name,
2663 other->ob_type->tp_name);
2664 return NULL;
2665 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666 res = (*func)(self, other);
2667 if (PyErr_Occurred())
2668 return NULL;
2669 return PyInt_FromLong((long)res);
2670}
2671
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672static PyObject *
2673wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2674{
2675 setattrofunc func = (setattrofunc)wrapped;
2676 int res;
2677 PyObject *name, *value;
2678
2679 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2680 return NULL;
2681 res = (*func)(self, name, value);
2682 if (res < 0)
2683 return NULL;
2684 Py_INCREF(Py_None);
2685 return Py_None;
2686}
2687
2688static PyObject *
2689wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2690{
2691 setattrofunc func = (setattrofunc)wrapped;
2692 int res;
2693 PyObject *name;
2694
2695 if (!PyArg_ParseTuple(args, "O", &name))
2696 return NULL;
2697 res = (*func)(self, name, NULL);
2698 if (res < 0)
2699 return NULL;
2700 Py_INCREF(Py_None);
2701 return Py_None;
2702}
2703
Tim Peters6d6c1a32001-08-02 04:15:00 +00002704static PyObject *
2705wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2706{
2707 hashfunc func = (hashfunc)wrapped;
2708 long res;
2709
2710 if (!PyArg_ParseTuple(args, ""))
2711 return NULL;
2712 res = (*func)(self);
2713 if (res == -1 && PyErr_Occurred())
2714 return NULL;
2715 return PyInt_FromLong(res);
2716}
2717
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002719wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720{
2721 ternaryfunc func = (ternaryfunc)wrapped;
2722
Guido van Rossumc8e56452001-10-22 00:43:43 +00002723 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724}
2725
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726static PyObject *
2727wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2728{
2729 richcmpfunc func = (richcmpfunc)wrapped;
2730 PyObject *other;
2731
2732 if (!PyArg_ParseTuple(args, "O", &other))
2733 return NULL;
2734 return (*func)(self, other, op);
2735}
2736
2737#undef RICHCMP_WRAPPER
2738#define RICHCMP_WRAPPER(NAME, OP) \
2739static PyObject * \
2740richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2741{ \
2742 return wrap_richcmpfunc(self, args, wrapped, OP); \
2743}
2744
Jack Jansen8e938b42001-08-08 15:29:49 +00002745RICHCMP_WRAPPER(lt, Py_LT)
2746RICHCMP_WRAPPER(le, Py_LE)
2747RICHCMP_WRAPPER(eq, Py_EQ)
2748RICHCMP_WRAPPER(ne, Py_NE)
2749RICHCMP_WRAPPER(gt, Py_GT)
2750RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751
Tim Peters6d6c1a32001-08-02 04:15:00 +00002752static PyObject *
2753wrap_next(PyObject *self, PyObject *args, void *wrapped)
2754{
2755 unaryfunc func = (unaryfunc)wrapped;
2756 PyObject *res;
2757
2758 if (!PyArg_ParseTuple(args, ""))
2759 return NULL;
2760 res = (*func)(self);
2761 if (res == NULL && !PyErr_Occurred())
2762 PyErr_SetNone(PyExc_StopIteration);
2763 return res;
2764}
2765
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766static PyObject *
2767wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2768{
2769 descrgetfunc func = (descrgetfunc)wrapped;
2770 PyObject *obj;
2771 PyObject *type = NULL;
2772
2773 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2774 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775 return (*func)(self, obj, type);
2776}
2777
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002779wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780{
2781 descrsetfunc func = (descrsetfunc)wrapped;
2782 PyObject *obj, *value;
2783 int ret;
2784
2785 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2786 return NULL;
2787 ret = (*func)(self, obj, value);
2788 if (ret < 0)
2789 return NULL;
2790 Py_INCREF(Py_None);
2791 return Py_None;
2792}
2793
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002795wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796{
2797 initproc func = (initproc)wrapped;
2798
Guido van Rossumc8e56452001-10-22 00:43:43 +00002799 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002800 return NULL;
2801 Py_INCREF(Py_None);
2802 return Py_None;
2803}
2804
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002806tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002807{
Barry Warsaw60f01882001-08-22 19:24:42 +00002808 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002809 PyObject *arg0, *res;
2810
2811 if (self == NULL || !PyType_Check(self))
2812 Py_FatalError("__new__() called with non-type 'self'");
2813 type = (PyTypeObject *)self;
2814 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002815 PyErr_Format(PyExc_TypeError,
2816 "%s.__new__(): not enough arguments",
2817 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002818 return NULL;
2819 }
2820 arg0 = PyTuple_GET_ITEM(args, 0);
2821 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002822 PyErr_Format(PyExc_TypeError,
2823 "%s.__new__(X): X is not a type object (%s)",
2824 type->tp_name,
2825 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002826 return NULL;
2827 }
2828 subtype = (PyTypeObject *)arg0;
2829 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002830 PyErr_Format(PyExc_TypeError,
2831 "%s.__new__(%s): %s is not a subtype of %s",
2832 type->tp_name,
2833 subtype->tp_name,
2834 subtype->tp_name,
2835 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002836 return NULL;
2837 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002838
2839 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002840 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002841 most derived base that's not a heap type is this type. */
2842 staticbase = subtype;
2843 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2844 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002845 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002846 PyErr_Format(PyExc_TypeError,
2847 "%s.__new__(%s) is not safe, use %s.__new__()",
2848 type->tp_name,
2849 subtype->tp_name,
2850 staticbase == NULL ? "?" : staticbase->tp_name);
2851 return NULL;
2852 }
2853
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002854 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2855 if (args == NULL)
2856 return NULL;
2857 res = type->tp_new(subtype, args, kwds);
2858 Py_DECREF(args);
2859 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002860}
2861
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002862static struct PyMethodDef tp_new_methoddef[] = {
2863 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2864 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865 {0}
2866};
2867
2868static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002869add_tp_new_wrapper(PyTypeObject *type)
2870{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002871 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002872
Guido van Rossum687ae002001-10-15 22:03:32 +00002873 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002874 return 0;
2875 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002876 if (func == NULL)
2877 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002878 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002879}
2880
Guido van Rossumf040ede2001-08-07 16:40:56 +00002881/* Slot wrappers that call the corresponding __foo__ slot. See comments
2882 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883
Guido van Rossumdc91b992001-08-08 22:26:22 +00002884#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002885static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002886FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002888 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002889 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890}
2891
Guido van Rossumdc91b992001-08-08 22:26:22 +00002892#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002893static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002894FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002895{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002896 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002897 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898}
2899
Guido van Rossumdc91b992001-08-08 22:26:22 +00002900
2901#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002903FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002904{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002905 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002906 int do_other = self->ob_type != other->ob_type && \
2907 other->ob_type->tp_as_number != NULL && \
2908 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002909 if (self->ob_type->tp_as_number != NULL && \
2910 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2911 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002912 if (do_other && \
2913 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2914 r = call_maybe( \
2915 other, ROPSTR, &rcache_str, "(O)", self); \
2916 if (r != Py_NotImplemented) \
2917 return r; \
2918 Py_DECREF(r); \
2919 do_other = 0; \
2920 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002921 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002922 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002923 if (r != Py_NotImplemented || \
2924 other->ob_type == self->ob_type) \
2925 return r; \
2926 Py_DECREF(r); \
2927 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002928 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002929 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002930 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002931 } \
2932 Py_INCREF(Py_NotImplemented); \
2933 return Py_NotImplemented; \
2934}
2935
2936#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2937 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2938
2939#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2940static PyObject * \
2941FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2942{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002943 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002944 return call_method(self, OPSTR, &cache_str, \
2945 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946}
2947
2948static int
2949slot_sq_length(PyObject *self)
2950{
Guido van Rossum2730b132001-08-28 18:22:14 +00002951 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002952 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002953 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002954
2955 if (res == NULL)
2956 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002957 len = (int)PyInt_AsLong(res);
2958 Py_DECREF(res);
2959 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960}
2961
Guido van Rossumdc91b992001-08-08 22:26:22 +00002962SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2963SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002964
2965/* Super-optimized version of slot_sq_item.
2966 Other slots could do the same... */
2967static PyObject *
2968slot_sq_item(PyObject *self, int i)
2969{
2970 static PyObject *getitem_str;
2971 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2972 descrgetfunc f;
2973
2974 if (getitem_str == NULL) {
2975 getitem_str = PyString_InternFromString("__getitem__");
2976 if (getitem_str == NULL)
2977 return NULL;
2978 }
2979 func = _PyType_Lookup(self->ob_type, getitem_str);
2980 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002981 if ((f = func->ob_type->tp_descr_get) == NULL)
2982 Py_INCREF(func);
2983 else
2984 func = f(func, self, (PyObject *)(self->ob_type));
2985 ival = PyInt_FromLong(i);
2986 if (ival != NULL) {
2987 args = PyTuple_New(1);
2988 if (args != NULL) {
2989 PyTuple_SET_ITEM(args, 0, ival);
2990 retval = PyObject_Call(func, args, NULL);
2991 Py_XDECREF(args);
2992 Py_XDECREF(func);
2993 return retval;
2994 }
2995 }
2996 }
2997 else {
2998 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2999 }
3000 Py_XDECREF(args);
3001 Py_XDECREF(ival);
3002 Py_XDECREF(func);
3003 return NULL;
3004}
3005
Guido van Rossumdc91b992001-08-08 22:26:22 +00003006SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007
3008static int
3009slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3010{
3011 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003012 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013
3014 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003015 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003016 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003018 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003019 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020 if (res == NULL)
3021 return -1;
3022 Py_DECREF(res);
3023 return 0;
3024}
3025
3026static int
3027slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3028{
3029 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003030 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031
3032 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003033 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003034 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003036 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003037 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003038 if (res == NULL)
3039 return -1;
3040 Py_DECREF(res);
3041 return 0;
3042}
3043
3044static int
3045slot_sq_contains(PyObject *self, PyObject *value)
3046{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003047 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003048 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003049
Guido van Rossum55f20992001-10-01 17:18:22 +00003050 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003051
3052 if (func != NULL) {
3053 args = Py_BuildValue("(O)", value);
3054 if (args == NULL)
3055 res = NULL;
3056 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003057 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003058 Py_DECREF(args);
3059 }
3060 Py_DECREF(func);
3061 if (res == NULL)
3062 return -1;
3063 return PyObject_IsTrue(res);
3064 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003065 else if (PyErr_Occurred())
3066 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003067 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003068 return _PySequence_IterSearch(self, value,
3069 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003070 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003071}
3072
Guido van Rossumdc91b992001-08-08 22:26:22 +00003073SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3074SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003075
3076#define slot_mp_length slot_sq_length
3077
Guido van Rossumdc91b992001-08-08 22:26:22 +00003078SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079
3080static int
3081slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3082{
3083 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003084 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085
3086 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003087 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003088 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003089 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003090 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003091 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003092 if (res == NULL)
3093 return -1;
3094 Py_DECREF(res);
3095 return 0;
3096}
3097
Guido van Rossumdc91b992001-08-08 22:26:22 +00003098SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3099SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3100SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3101SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3102SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3103SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3104
3105staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3106
3107SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3108 nb_power, "__pow__", "__rpow__")
3109
3110static PyObject *
3111slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3112{
Guido van Rossum2730b132001-08-28 18:22:14 +00003113 static PyObject *pow_str;
3114
Guido van Rossumdc91b992001-08-08 22:26:22 +00003115 if (modulus == Py_None)
3116 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003117 /* Three-arg power doesn't use __rpow__. But ternary_op
3118 can call this when the second argument's type uses
3119 slot_nb_power, so check before calling self.__pow__. */
3120 if (self->ob_type->tp_as_number != NULL &&
3121 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3122 return call_method(self, "__pow__", &pow_str,
3123 "(OO)", other, modulus);
3124 }
3125 Py_INCREF(Py_NotImplemented);
3126 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003127}
3128
3129SLOT0(slot_nb_negative, "__neg__")
3130SLOT0(slot_nb_positive, "__pos__")
3131SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132
3133static int
3134slot_nb_nonzero(PyObject *self)
3135{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003136 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003137 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003138
Guido van Rossum55f20992001-10-01 17:18:22 +00003139 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003140 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003141 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003142 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003143 func = lookup_maybe(self, "__len__", &len_str);
3144 if (func == NULL) {
3145 if (PyErr_Occurred())
3146 return -1;
3147 else
3148 return 1;
3149 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003150 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003151 res = PyObject_CallObject(func, NULL);
3152 Py_DECREF(func);
3153 if (res == NULL)
3154 return -1;
3155 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003156}
3157
Guido van Rossumdc91b992001-08-08 22:26:22 +00003158SLOT0(slot_nb_invert, "__invert__")
3159SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3160SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3161SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3162SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3163SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003164
3165static int
3166slot_nb_coerce(PyObject **a, PyObject **b)
3167{
3168 static PyObject *coerce_str;
3169 PyObject *self = *a, *other = *b;
3170
3171 if (self->ob_type->tp_as_number != NULL &&
3172 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3173 PyObject *r;
3174 r = call_maybe(
3175 self, "__coerce__", &coerce_str, "(O)", other);
3176 if (r == NULL)
3177 return -1;
3178 if (r == Py_NotImplemented) {
3179 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003180 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003181 else {
3182 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3183 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003184 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003185 Py_DECREF(r);
3186 return -1;
3187 }
3188 *a = PyTuple_GET_ITEM(r, 0);
3189 Py_INCREF(*a);
3190 *b = PyTuple_GET_ITEM(r, 1);
3191 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003192 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003193 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003194 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003195 }
3196 if (other->ob_type->tp_as_number != NULL &&
3197 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3198 PyObject *r;
3199 r = call_maybe(
3200 other, "__coerce__", &coerce_str, "(O)", self);
3201 if (r == NULL)
3202 return -1;
3203 if (r == Py_NotImplemented) {
3204 Py_DECREF(r);
3205 return 1;
3206 }
3207 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3208 PyErr_SetString(PyExc_TypeError,
3209 "__coerce__ didn't return a 2-tuple");
3210 Py_DECREF(r);
3211 return -1;
3212 }
3213 *a = PyTuple_GET_ITEM(r, 1);
3214 Py_INCREF(*a);
3215 *b = PyTuple_GET_ITEM(r, 0);
3216 Py_INCREF(*b);
3217 Py_DECREF(r);
3218 return 0;
3219 }
3220 return 1;
3221}
3222
Guido van Rossumdc91b992001-08-08 22:26:22 +00003223SLOT0(slot_nb_int, "__int__")
3224SLOT0(slot_nb_long, "__long__")
3225SLOT0(slot_nb_float, "__float__")
3226SLOT0(slot_nb_oct, "__oct__")
3227SLOT0(slot_nb_hex, "__hex__")
3228SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3229SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3230SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3231SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3232SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3233SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3234SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3235SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3236SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3237SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3238SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3239SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3240 "__floordiv__", "__rfloordiv__")
3241SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3242SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3243SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244
3245static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003246half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003247{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003248 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003249 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003250 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003251
Guido van Rossum60718732001-08-28 17:47:51 +00003252 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003253 if (func == NULL) {
3254 PyErr_Clear();
3255 }
3256 else {
3257 args = Py_BuildValue("(O)", other);
3258 if (args == NULL)
3259 res = NULL;
3260 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003261 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003262 Py_DECREF(args);
3263 }
3264 if (res != Py_NotImplemented) {
3265 if (res == NULL)
3266 return -2;
3267 c = PyInt_AsLong(res);
3268 Py_DECREF(res);
3269 if (c == -1 && PyErr_Occurred())
3270 return -2;
3271 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3272 }
3273 Py_DECREF(res);
3274 }
3275 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003276}
3277
Guido van Rossumab3b0342001-09-18 20:38:53 +00003278/* This slot is published for the benefit of try_3way_compare in object.c */
3279int
3280_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003281{
3282 int c;
3283
Guido van Rossumab3b0342001-09-18 20:38:53 +00003284 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003285 c = half_compare(self, other);
3286 if (c <= 1)
3287 return c;
3288 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003289 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003290 c = half_compare(other, self);
3291 if (c < -1)
3292 return -2;
3293 if (c <= 1)
3294 return -c;
3295 }
3296 return (void *)self < (void *)other ? -1 :
3297 (void *)self > (void *)other ? 1 : 0;
3298}
3299
3300static PyObject *
3301slot_tp_repr(PyObject *self)
3302{
3303 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003304 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003305
Guido van Rossum60718732001-08-28 17:47:51 +00003306 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003307 if (func != NULL) {
3308 res = PyEval_CallObject(func, NULL);
3309 Py_DECREF(func);
3310 return res;
3311 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003312 PyErr_Clear();
3313 return PyString_FromFormat("<%s object at %p>",
3314 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003315}
3316
3317static PyObject *
3318slot_tp_str(PyObject *self)
3319{
3320 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003321 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003322
Guido van Rossum60718732001-08-28 17:47:51 +00003323 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003324 if (func != NULL) {
3325 res = PyEval_CallObject(func, NULL);
3326 Py_DECREF(func);
3327 return res;
3328 }
3329 else {
3330 PyErr_Clear();
3331 return slot_tp_repr(self);
3332 }
3333}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003334
3335static long
3336slot_tp_hash(PyObject *self)
3337{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003338 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003339 static PyObject *hash_str, *eq_str, *cmp_str;
3340
Tim Peters6d6c1a32001-08-02 04:15:00 +00003341 long h;
3342
Guido van Rossum60718732001-08-28 17:47:51 +00003343 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003344
3345 if (func != NULL) {
3346 res = PyEval_CallObject(func, NULL);
3347 Py_DECREF(func);
3348 if (res == NULL)
3349 return -1;
3350 h = PyInt_AsLong(res);
3351 }
3352 else {
3353 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003354 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003355 if (func == NULL) {
3356 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003357 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003358 }
3359 if (func != NULL) {
3360 Py_DECREF(func);
3361 PyErr_SetString(PyExc_TypeError, "unhashable type");
3362 return -1;
3363 }
3364 PyErr_Clear();
3365 h = _Py_HashPointer((void *)self);
3366 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367 if (h == -1 && !PyErr_Occurred())
3368 h = -2;
3369 return h;
3370}
3371
3372static PyObject *
3373slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3374{
Guido van Rossum60718732001-08-28 17:47:51 +00003375 static PyObject *call_str;
3376 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377 PyObject *res;
3378
3379 if (meth == NULL)
3380 return NULL;
3381 res = PyObject_Call(meth, args, kwds);
3382 Py_DECREF(meth);
3383 return res;
3384}
3385
Guido van Rossum14a6f832001-10-17 13:59:09 +00003386/* There are two slot dispatch functions for tp_getattro.
3387
3388 - slot_tp_getattro() is used when __getattribute__ is overridden
3389 but no __getattr__ hook is present;
3390
3391 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3392
Guido van Rossumc334df52002-04-04 23:44:47 +00003393 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3394 detects the absence of __getattr__ and then installs the simpler slot if
3395 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003396
Tim Peters6d6c1a32001-08-02 04:15:00 +00003397static PyObject *
3398slot_tp_getattro(PyObject *self, PyObject *name)
3399{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003400 static PyObject *getattribute_str = NULL;
3401 return call_method(self, "__getattribute__", &getattribute_str,
3402 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403}
3404
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003405static PyObject *
3406slot_tp_getattr_hook(PyObject *self, PyObject *name)
3407{
3408 PyTypeObject *tp = self->ob_type;
3409 PyObject *getattr, *getattribute, *res;
3410 static PyObject *getattribute_str = NULL;
3411 static PyObject *getattr_str = NULL;
3412
3413 if (getattr_str == NULL) {
3414 getattr_str = PyString_InternFromString("__getattr__");
3415 if (getattr_str == NULL)
3416 return NULL;
3417 }
3418 if (getattribute_str == NULL) {
3419 getattribute_str =
3420 PyString_InternFromString("__getattribute__");
3421 if (getattribute_str == NULL)
3422 return NULL;
3423 }
3424 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003425 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003426 /* No __getattr__ hook: use a simpler dispatcher */
3427 tp->tp_getattro = slot_tp_getattro;
3428 return slot_tp_getattro(self, name);
3429 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003430 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003431 if (getattribute == NULL ||
3432 (getattribute->ob_type == &PyWrapperDescr_Type &&
3433 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3434 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003435 res = PyObject_GenericGetAttr(self, name);
3436 else
3437 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003438 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003439 PyErr_Clear();
3440 res = PyObject_CallFunction(getattr, "OO", self, name);
3441 }
3442 return res;
3443}
3444
Tim Peters6d6c1a32001-08-02 04:15:00 +00003445static int
3446slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3447{
3448 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003449 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450
3451 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003452 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003453 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003455 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003456 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003457 if (res == NULL)
3458 return -1;
3459 Py_DECREF(res);
3460 return 0;
3461}
3462
3463/* Map rich comparison operators to their __xx__ namesakes */
3464static char *name_op[] = {
3465 "__lt__",
3466 "__le__",
3467 "__eq__",
3468 "__ne__",
3469 "__gt__",
3470 "__ge__",
3471};
3472
3473static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003474half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003476 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003477 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478
Guido van Rossum60718732001-08-28 17:47:51 +00003479 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003480 if (func == NULL) {
3481 PyErr_Clear();
3482 Py_INCREF(Py_NotImplemented);
3483 return Py_NotImplemented;
3484 }
3485 args = Py_BuildValue("(O)", other);
3486 if (args == NULL)
3487 res = NULL;
3488 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003489 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003490 Py_DECREF(args);
3491 }
3492 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003493 return res;
3494}
3495
Guido van Rossumb8f63662001-08-15 23:57:02 +00003496/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3497static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3498
3499static PyObject *
3500slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3501{
3502 PyObject *res;
3503
3504 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3505 res = half_richcompare(self, other, op);
3506 if (res != Py_NotImplemented)
3507 return res;
3508 Py_DECREF(res);
3509 }
3510 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3511 res = half_richcompare(other, self, swapped_op[op]);
3512 if (res != Py_NotImplemented) {
3513 return res;
3514 }
3515 Py_DECREF(res);
3516 }
3517 Py_INCREF(Py_NotImplemented);
3518 return Py_NotImplemented;
3519}
3520
3521static PyObject *
3522slot_tp_iter(PyObject *self)
3523{
3524 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003525 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003526
Guido van Rossum60718732001-08-28 17:47:51 +00003527 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003528 if (func != NULL) {
3529 res = PyObject_CallObject(func, NULL);
3530 Py_DECREF(func);
3531 return res;
3532 }
3533 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003534 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003535 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003536 PyErr_SetString(PyExc_TypeError,
3537 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003538 return NULL;
3539 }
3540 Py_DECREF(func);
3541 return PySeqIter_New(self);
3542}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543
3544static PyObject *
3545slot_tp_iternext(PyObject *self)
3546{
Guido van Rossum2730b132001-08-28 18:22:14 +00003547 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003548 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003549}
3550
Guido van Rossum1a493502001-08-17 16:47:50 +00003551static PyObject *
3552slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3553{
3554 PyTypeObject *tp = self->ob_type;
3555 PyObject *get;
3556 static PyObject *get_str = NULL;
3557
3558 if (get_str == NULL) {
3559 get_str = PyString_InternFromString("__get__");
3560 if (get_str == NULL)
3561 return NULL;
3562 }
3563 get = _PyType_Lookup(tp, get_str);
3564 if (get == NULL) {
3565 /* Avoid further slowdowns */
3566 if (tp->tp_descr_get == slot_tp_descr_get)
3567 tp->tp_descr_get = NULL;
3568 Py_INCREF(self);
3569 return self;
3570 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003571 if (obj == NULL)
3572 obj = Py_None;
3573 if (type == NULL)
3574 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003575 return PyObject_CallFunction(get, "OOO", self, obj, type);
3576}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577
3578static int
3579slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3580{
Guido van Rossum2c252392001-08-24 10:13:31 +00003581 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003582 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003583
3584 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003585 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003586 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003587 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003588 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003589 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003590 if (res == NULL)
3591 return -1;
3592 Py_DECREF(res);
3593 return 0;
3594}
3595
3596static int
3597slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3598{
Guido van Rossum60718732001-08-28 17:47:51 +00003599 static PyObject *init_str;
3600 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003601 PyObject *res;
3602
3603 if (meth == NULL)
3604 return -1;
3605 res = PyObject_Call(meth, args, kwds);
3606 Py_DECREF(meth);
3607 if (res == NULL)
3608 return -1;
3609 Py_DECREF(res);
3610 return 0;
3611}
3612
3613static PyObject *
3614slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3615{
3616 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3617 PyObject *newargs, *x;
3618 int i, n;
3619
3620 if (func == NULL)
3621 return NULL;
3622 assert(PyTuple_Check(args));
3623 n = PyTuple_GET_SIZE(args);
3624 newargs = PyTuple_New(n+1);
3625 if (newargs == NULL)
3626 return NULL;
3627 Py_INCREF(type);
3628 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3629 for (i = 0; i < n; i++) {
3630 x = PyTuple_GET_ITEM(args, i);
3631 Py_INCREF(x);
3632 PyTuple_SET_ITEM(newargs, i+1, x);
3633 }
3634 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003635 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636 Py_DECREF(func);
3637 return x;
3638}
3639
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003640
3641/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3642 functions. The offsets here are relative to the 'etype' structure, which
3643 incorporates the additional structures used for numbers, sequences and
3644 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3645 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003646 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3647 terminated with an all-zero entry. (This table is further initialized and
3648 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003649
Guido van Rossum6d204072001-10-21 00:44:31 +00003650typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003651
3652#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003653#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003654#undef ETSLOT
3655#undef SQSLOT
3656#undef MPSLOT
3657#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003658#undef UNSLOT
3659#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003660#undef BINSLOT
3661#undef RBINSLOT
3662
Guido van Rossum6d204072001-10-21 00:44:31 +00003663#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3664 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003665#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3666 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3667 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003668#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3669 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3670#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3671 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3672#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3673 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3674#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3675 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3676#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3677 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3678 "x." NAME "() <==> " DOC)
3679#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3680 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3681 "x." NAME "(y) <==> x" DOC "y")
3682#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3683 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3684 "x." NAME "(y) <==> x" DOC "y")
3685#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3686 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3687 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003688
3689static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003690 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3691 "x.__len__() <==> len(x)"),
3692 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3693 "x.__add__(y) <==> x+y"),
3694 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3695 "x.__mul__(n) <==> x*n"),
3696 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3697 "x.__rmul__(n) <==> n*x"),
3698 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3699 "x.__getitem__(y) <==> x[y]"),
3700 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3701 "x.__getslice__(i, j) <==> x[i:j]"),
3702 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3703 "x.__setitem__(i, y) <==> x[i]=y"),
3704 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3705 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003706 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003707 wrap_intintobjargproc,
3708 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3709 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3710 "x.__delslice__(i, j) <==> del x[i:j]"),
3711 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3712 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003713 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003714 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003715 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003716 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003717
Guido van Rossum6d204072001-10-21 00:44:31 +00003718 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3719 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003720 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003721 wrap_binaryfunc,
3722 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003723 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003724 wrap_objobjargproc,
3725 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003726 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003727 wrap_delitem,
3728 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003729
Guido van Rossum6d204072001-10-21 00:44:31 +00003730 BINSLOT("__add__", nb_add, slot_nb_add,
3731 "+"),
3732 RBINSLOT("__radd__", nb_add, slot_nb_add,
3733 "+"),
3734 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3735 "-"),
3736 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3737 "-"),
3738 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3739 "*"),
3740 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3741 "*"),
3742 BINSLOT("__div__", nb_divide, slot_nb_divide,
3743 "/"),
3744 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3745 "/"),
3746 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3747 "%"),
3748 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3749 "%"),
3750 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3751 "divmod(x, y)"),
3752 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3753 "divmod(y, x)"),
3754 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3755 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3756 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3757 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3758 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3759 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3760 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3761 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003762 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003763 "x != 0"),
3764 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3765 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3766 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3767 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3768 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3769 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3770 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3771 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3772 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3773 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3774 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3775 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3776 "x.__coerce__(y) <==> coerce(x, y)"),
3777 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3778 "int(x)"),
3779 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3780 "long(x)"),
3781 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3782 "float(x)"),
3783 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3784 "oct(x)"),
3785 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3786 "hex(x)"),
3787 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3788 wrap_binaryfunc, "+"),
3789 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3790 wrap_binaryfunc, "-"),
3791 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3792 wrap_binaryfunc, "*"),
3793 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3794 wrap_binaryfunc, "/"),
3795 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3796 wrap_binaryfunc, "%"),
3797 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3798 wrap_ternaryfunc, "**"),
3799 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3800 wrap_binaryfunc, "<<"),
3801 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3802 wrap_binaryfunc, ">>"),
3803 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3804 wrap_binaryfunc, "&"),
3805 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3806 wrap_binaryfunc, "^"),
3807 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3808 wrap_binaryfunc, "|"),
3809 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3810 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3811 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3812 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3813 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3814 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3815 IBSLOT("__itruediv__", nb_inplace_true_divide,
3816 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003817
Guido van Rossum6d204072001-10-21 00:44:31 +00003818 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3819 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003820 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003821 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3822 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003823 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003824 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3825 "x.__cmp__(y) <==> cmp(x,y)"),
3826 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3827 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003828 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3829 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003830 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003831 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3832 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3833 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3834 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3835 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3836 "x.__setattr__('name', value) <==> x.name = value"),
3837 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3838 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3839 "x.__delattr__('name') <==> del x.name"),
3840 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3841 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3842 "x.__lt__(y) <==> x<y"),
3843 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3844 "x.__le__(y) <==> x<=y"),
3845 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3846 "x.__eq__(y) <==> x==y"),
3847 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3848 "x.__ne__(y) <==> x!=y"),
3849 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3850 "x.__gt__(y) <==> x>y"),
3851 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3852 "x.__ge__(y) <==> x>=y"),
3853 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3854 "x.__iter__() <==> iter(x)"),
3855 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3856 "x.next() -> the next value, or raise StopIteration"),
3857 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3858 "descr.__get__(obj[, type]) -> value"),
3859 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3860 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003861 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003862 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003863 "see x.__class__.__doc__ for signature",
3864 PyWrapperFlag_KEYWORDS),
3865 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003866 {NULL}
3867};
3868
Guido van Rossumc334df52002-04-04 23:44:47 +00003869/* Given a type pointer and an offset gotten from a slotdef entry, return a
3870 pointer to the actual slot. This is not quite the same as simply adding
3871 the offset to the type pointer, since it takes care to indirect through the
3872 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3873 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003874static void **
3875slotptr(PyTypeObject *type, int offset)
3876{
3877 char *ptr;
3878
Guido van Rossum09638c12002-06-13 19:17:46 +00003879 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003880 assert(offset >= 0);
3881 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003882 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003883 ptr = (void *)type->tp_as_sequence;
3884 offset -= offsetof(etype, as_sequence);
3885 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003886 else if (offset >= offsetof(etype, as_mapping)) {
3887 ptr = (void *)type->tp_as_mapping;
3888 offset -= offsetof(etype, as_mapping);
3889 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003890 else if (offset >= offsetof(etype, as_number)) {
3891 ptr = (void *)type->tp_as_number;
3892 offset -= offsetof(etype, as_number);
3893 }
3894 else {
3895 ptr = (void *)type;
3896 }
3897 if (ptr != NULL)
3898 ptr += offset;
3899 return (void **)ptr;
3900}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003901
Guido van Rossumc334df52002-04-04 23:44:47 +00003902/* Length of array of slotdef pointers used to store slots with the
3903 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3904 the same __name__, for any __name__. Since that's a static property, it is
3905 appropriate to declare fixed-size arrays for this. */
3906#define MAX_EQUIV 10
3907
3908/* Return a slot pointer for a given name, but ONLY if the attribute has
3909 exactly one slot function. The name must be an interned string. */
3910static void **
3911resolve_slotdups(PyTypeObject *type, PyObject *name)
3912{
3913 /* XXX Maybe this could be optimized more -- but is it worth it? */
3914
3915 /* pname and ptrs act as a little cache */
3916 static PyObject *pname;
3917 static slotdef *ptrs[MAX_EQUIV];
3918 slotdef *p, **pp;
3919 void **res, **ptr;
3920
3921 if (pname != name) {
3922 /* Collect all slotdefs that match name into ptrs. */
3923 pname = name;
3924 pp = ptrs;
3925 for (p = slotdefs; p->name_strobj; p++) {
3926 if (p->name_strobj == name)
3927 *pp++ = p;
3928 }
3929 *pp = NULL;
3930 }
3931
3932 /* Look in all matching slots of the type; if exactly one of these has
3933 a filled-in slot, return its value. Otherwise return NULL. */
3934 res = NULL;
3935 for (pp = ptrs; *pp; pp++) {
3936 ptr = slotptr(type, (*pp)->offset);
3937 if (ptr == NULL || *ptr == NULL)
3938 continue;
3939 if (res != NULL)
3940 return NULL;
3941 res = ptr;
3942 }
3943 return res;
3944}
3945
3946/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3947 does some incredibly complex thinking and then sticks something into the
3948 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3949 interests, and then stores a generic wrapper or a specific function into
3950 the slot.) Return a pointer to the next slotdef with a different offset,
3951 because that's convenient for fixup_slot_dispatchers(). */
3952static slotdef *
3953update_one_slot(PyTypeObject *type, slotdef *p)
3954{
3955 PyObject *descr;
3956 PyWrapperDescrObject *d;
3957 void *generic = NULL, *specific = NULL;
3958 int use_generic = 0;
3959 int offset = p->offset;
3960 void **ptr = slotptr(type, offset);
3961
3962 if (ptr == NULL) {
3963 do {
3964 ++p;
3965 } while (p->offset == offset);
3966 return p;
3967 }
3968 do {
3969 descr = _PyType_Lookup(type, p->name_strobj);
3970 if (descr == NULL)
3971 continue;
3972 if (descr->ob_type == &PyWrapperDescr_Type) {
3973 void **tptr = resolve_slotdups(type, p->name_strobj);
3974 if (tptr == NULL || tptr == ptr)
3975 generic = p->function;
3976 d = (PyWrapperDescrObject *)descr;
3977 if (d->d_base->wrapper == p->wrapper &&
3978 PyType_IsSubtype(type, d->d_type))
3979 {
3980 if (specific == NULL ||
3981 specific == d->d_wrapped)
3982 specific = d->d_wrapped;
3983 else
3984 use_generic = 1;
3985 }
3986 }
3987 else {
3988 use_generic = 1;
3989 generic = p->function;
3990 }
3991 } while ((++p)->offset == offset);
3992 if (specific && !use_generic)
3993 *ptr = specific;
3994 else
3995 *ptr = generic;
3996 return p;
3997}
3998
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003999staticforward int recurse_down_subclasses(PyTypeObject *type,
4000 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004001
Guido van Rossumc334df52002-04-04 23:44:47 +00004002/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4003 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004004static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004005update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004006{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004007 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004008
Guido van Rossumc334df52002-04-04 23:44:47 +00004009 for (pp = pp0; *pp; pp++)
4010 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004011 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004012}
4013
Guido van Rossumc334df52002-04-04 23:44:47 +00004014/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4015 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004016static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004017recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004018{
4019 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004020 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004021 int i, n;
4022
4023 subclasses = type->tp_subclasses;
4024 if (subclasses == NULL)
4025 return 0;
4026 assert(PyList_Check(subclasses));
4027 n = PyList_GET_SIZE(subclasses);
4028 for (i = 0; i < n; i++) {
4029 ref = PyList_GET_ITEM(subclasses, i);
4030 assert(PyWeakref_CheckRef(ref));
4031 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
4032 if (subclass == NULL)
4033 continue;
4034 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004035 /* Avoid recursing down into unaffected classes */
4036 dict = subclass->tp_dict;
4037 if (dict != NULL && PyDict_Check(dict) &&
4038 PyDict_GetItem(dict, name) != NULL)
4039 continue;
4040 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004041 return -1;
4042 }
4043 return 0;
4044}
4045
Guido van Rossumc334df52002-04-04 23:44:47 +00004046/* Comparison function for qsort() to compare slotdefs by their offset, and
4047 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004048static int
4049slotdef_cmp(const void *aa, const void *bb)
4050{
4051 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4052 int c = a->offset - b->offset;
4053 if (c != 0)
4054 return c;
4055 else
4056 return a - b;
4057}
4058
Guido van Rossumc334df52002-04-04 23:44:47 +00004059/* Initialize the slotdefs table by adding interned string objects for the
4060 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004061static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004062init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004063{
4064 slotdef *p;
4065 static int initialized = 0;
4066
4067 if (initialized)
4068 return;
4069 for (p = slotdefs; p->name; p++) {
4070 p->name_strobj = PyString_InternFromString(p->name);
4071 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004072 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004073 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004074 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4075 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004076 initialized = 1;
4077}
4078
Guido van Rossumc334df52002-04-04 23:44:47 +00004079/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004080static int
4081update_slot(PyTypeObject *type, PyObject *name)
4082{
Guido van Rossumc334df52002-04-04 23:44:47 +00004083 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004084 slotdef *p;
4085 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004086 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004087
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004088 init_slotdefs();
4089 pp = ptrs;
4090 for (p = slotdefs; p->name; p++) {
4091 /* XXX assume name is interned! */
4092 if (p->name_strobj == name)
4093 *pp++ = p;
4094 }
4095 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004096 for (pp = ptrs; *pp; pp++) {
4097 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004098 offset = p->offset;
4099 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004100 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004101 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004102 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004103 if (ptrs[0] == NULL)
4104 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004105 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004106}
4107
Guido van Rossumc334df52002-04-04 23:44:47 +00004108/* Store the proper functions in the slot dispatches at class (type)
4109 definition time, based upon which operations the class overrides in its
4110 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004112fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004114 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004116 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004117 for (p = slotdefs; p->name; )
4118 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004119}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004120
Guido van Rossum6d204072001-10-21 00:44:31 +00004121/* This function is called by PyType_Ready() to populate the type's
4122 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004123 function slot (like tp_repr) that's defined in the type, one or more
4124 corresponding descriptors are added in the type's tp_dict dictionary
4125 under the appropriate name (like __repr__). Some function slots
4126 cause more than one descriptor to be added (for example, the nb_add
4127 slot adds both __add__ and __radd__ descriptors) and some function
4128 slots compete for the same descriptor (for example both sq_item and
4129 mp_subscript generate a __getitem__ descriptor).
4130
4131 In the latter case, the first slotdef entry encoutered wins. Since
4132 slotdef entries are sorted by the offset of the slot in the etype
4133 struct, this gives us some control over disambiguating between
4134 competing slots: the members of struct etype are listed from most
4135 general to least general, so the most general slot is preferred. In
4136 particular, because as_mapping comes before as_sequence, for a type
4137 that defines both mp_subscript and sq_item, mp_subscript wins.
4138
4139 This only adds new descriptors and doesn't overwrite entries in
4140 tp_dict that were previously defined. The descriptors contain a
4141 reference to the C function they must call, so that it's safe if they
4142 are copied into a subtype's __dict__ and the subtype has a different
4143 C function in its slot -- calling the method defined by the
4144 descriptor will call the C function that was used to create it,
4145 rather than the C function present in the slot when it is called.
4146 (This is important because a subtype may have a C function in the
4147 slot that calls the method from the dictionary, and we want to avoid
4148 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004149
4150static int
4151add_operators(PyTypeObject *type)
4152{
4153 PyObject *dict = type->tp_dict;
4154 slotdef *p;
4155 PyObject *descr;
4156 void **ptr;
4157
4158 init_slotdefs();
4159 for (p = slotdefs; p->name; p++) {
4160 if (p->wrapper == NULL)
4161 continue;
4162 ptr = slotptr(type, p->offset);
4163 if (!ptr || !*ptr)
4164 continue;
4165 if (PyDict_GetItem(dict, p->name_strobj))
4166 continue;
4167 descr = PyDescr_NewWrapper(type, p, *ptr);
4168 if (descr == NULL)
4169 return -1;
4170 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4171 return -1;
4172 Py_DECREF(descr);
4173 }
4174 if (type->tp_new != NULL) {
4175 if (add_tp_new_wrapper(type) < 0)
4176 return -1;
4177 }
4178 return 0;
4179}
4180
Guido van Rossum705f0f52001-08-24 16:47:00 +00004181
4182/* Cooperative 'super' */
4183
4184typedef struct {
4185 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004186 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004187 PyObject *obj;
4188} superobject;
4189
Guido van Rossum6f799372001-09-20 20:46:19 +00004190static PyMemberDef super_members[] = {
4191 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4192 "the class invoking super()"},
4193 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4194 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004195 {0}
4196};
4197
Guido van Rossum705f0f52001-08-24 16:47:00 +00004198static void
4199super_dealloc(PyObject *self)
4200{
4201 superobject *su = (superobject *)self;
4202
Guido van Rossum048eb752001-10-02 21:24:57 +00004203 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004204 Py_XDECREF(su->obj);
4205 Py_XDECREF(su->type);
4206 self->ob_type->tp_free(self);
4207}
4208
4209static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004210super_repr(PyObject *self)
4211{
4212 superobject *su = (superobject *)self;
4213
4214 if (su->obj)
4215 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004216 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004217 su->type ? su->type->tp_name : "NULL",
4218 su->obj->ob_type->tp_name);
4219 else
4220 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004221 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004222 su->type ? su->type->tp_name : "NULL");
4223}
4224
4225static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004226super_getattro(PyObject *self, PyObject *name)
4227{
4228 superobject *su = (superobject *)self;
4229
4230 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004231 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004232 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004233 descrgetfunc f;
4234 int i, n;
4235
Guido van Rossum155db9a2002-04-02 17:53:47 +00004236 starttype = su->obj->ob_type;
4237 mro = starttype->tp_mro;
4238
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004239 if (mro == NULL)
4240 n = 0;
4241 else {
4242 assert(PyTuple_Check(mro));
4243 n = PyTuple_GET_SIZE(mro);
4244 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004245 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004246 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004247 break;
4248 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004249 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004250 starttype = (PyTypeObject *)(su->obj);
4251 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004252 if (mro == NULL)
4253 n = 0;
4254 else {
4255 assert(PyTuple_Check(mro));
4256 n = PyTuple_GET_SIZE(mro);
4257 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004258 for (i = 0; i < n; i++) {
4259 if ((PyObject *)(su->type) ==
4260 PyTuple_GET_ITEM(mro, i))
4261 break;
4262 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004263 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004264 i++;
4265 res = NULL;
4266 for (; i < n; i++) {
4267 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004268 if (PyType_Check(tmp))
4269 dict = ((PyTypeObject *)tmp)->tp_dict;
4270 else if (PyClass_Check(tmp))
4271 dict = ((PyClassObject *)tmp)->cl_dict;
4272 else
4273 continue;
4274 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004275 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004276 Py_INCREF(res);
4277 f = res->ob_type->tp_descr_get;
4278 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004279 tmp = f(res, su->obj,
4280 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004281 Py_DECREF(res);
4282 res = tmp;
4283 }
4284 return res;
4285 }
4286 }
4287 }
4288 return PyObject_GenericGetAttr(self, name);
4289}
4290
Guido van Rossum5b443c62001-12-03 15:38:28 +00004291static int
4292supercheck(PyTypeObject *type, PyObject *obj)
4293{
4294 if (!PyType_IsSubtype(obj->ob_type, type) &&
4295 !(PyType_Check(obj) &&
4296 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4297 PyErr_SetString(PyExc_TypeError,
4298 "super(type, obj): "
4299 "obj must be an instance or subtype of type");
4300 return -1;
4301 }
4302 else
4303 return 0;
4304}
4305
Guido van Rossum705f0f52001-08-24 16:47:00 +00004306static PyObject *
4307super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4308{
4309 superobject *su = (superobject *)self;
4310 superobject *new;
4311
4312 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4313 /* Not binding to an object, or already bound */
4314 Py_INCREF(self);
4315 return self;
4316 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004317 if (su->ob_type != &PySuper_Type)
4318 /* If su is an instance of a subclass of super,
4319 call its type */
4320 return PyObject_CallFunction((PyObject *)su->ob_type,
4321 "OO", su->type, obj);
4322 else {
4323 /* Inline the common case */
4324 if (supercheck(su->type, obj) < 0)
4325 return NULL;
4326 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4327 NULL, NULL);
4328 if (new == NULL)
4329 return NULL;
4330 Py_INCREF(su->type);
4331 Py_INCREF(obj);
4332 new->type = su->type;
4333 new->obj = obj;
4334 return (PyObject *)new;
4335 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004336}
4337
4338static int
4339super_init(PyObject *self, PyObject *args, PyObject *kwds)
4340{
4341 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004342 PyTypeObject *type;
4343 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004344
4345 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4346 return -1;
4347 if (obj == Py_None)
4348 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004349 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004350 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004351 Py_INCREF(type);
4352 Py_XINCREF(obj);
4353 su->type = type;
4354 su->obj = obj;
4355 return 0;
4356}
4357
4358static char super_doc[] =
4359"super(type) -> unbound super object\n"
4360"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004361"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004362"Typical use to call a cooperative superclass method:\n"
4363"class C(B):\n"
4364" def meth(self, arg):\n"
4365" super(C, self).meth(arg)";
4366
Guido van Rossum048eb752001-10-02 21:24:57 +00004367static int
4368super_traverse(PyObject *self, visitproc visit, void *arg)
4369{
4370 superobject *su = (superobject *)self;
4371 int err;
4372
4373#define VISIT(SLOT) \
4374 if (SLOT) { \
4375 err = visit((PyObject *)(SLOT), arg); \
4376 if (err) \
4377 return err; \
4378 }
4379
4380 VISIT(su->obj);
4381 VISIT(su->type);
4382
4383#undef VISIT
4384
4385 return 0;
4386}
4387
Guido van Rossum705f0f52001-08-24 16:47:00 +00004388PyTypeObject PySuper_Type = {
4389 PyObject_HEAD_INIT(&PyType_Type)
4390 0, /* ob_size */
4391 "super", /* tp_name */
4392 sizeof(superobject), /* tp_basicsize */
4393 0, /* tp_itemsize */
4394 /* methods */
4395 super_dealloc, /* tp_dealloc */
4396 0, /* tp_print */
4397 0, /* tp_getattr */
4398 0, /* tp_setattr */
4399 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004400 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004401 0, /* tp_as_number */
4402 0, /* tp_as_sequence */
4403 0, /* tp_as_mapping */
4404 0, /* tp_hash */
4405 0, /* tp_call */
4406 0, /* tp_str */
4407 super_getattro, /* tp_getattro */
4408 0, /* tp_setattro */
4409 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004410 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4411 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004412 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004413 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004414 0, /* tp_clear */
4415 0, /* tp_richcompare */
4416 0, /* tp_weaklistoffset */
4417 0, /* tp_iter */
4418 0, /* tp_iternext */
4419 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004420 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004421 0, /* tp_getset */
4422 0, /* tp_base */
4423 0, /* tp_dict */
4424 super_descr_get, /* tp_descr_get */
4425 0, /* tp_descr_set */
4426 0, /* tp_dictoffset */
4427 super_init, /* tp_init */
4428 PyType_GenericAlloc, /* tp_alloc */
4429 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004430 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004431};