blob: 7918af09dbc145871680b38fe312ac97ff14d6d8 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
35 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
36 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
37 {0}
38};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000039
Guido van Rossumc0b618a1997-05-02 03:12:38 +000040static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000041type_name(PyTypeObject *type, void *context)
42{
43 char *s;
44
45 s = strrchr(type->tp_name, '.');
46 if (s == NULL)
47 s = type->tp_name;
48 else
49 s++;
50 return PyString_FromString(s);
51}
52
53static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000054type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000055{
Guido van Rossumc3542212001-08-16 09:18:56 +000056 PyObject *mod;
57 char *s;
58
59 s = strrchr(type->tp_name, '.');
60 if (s != NULL)
61 return PyString_FromStringAndSize(type->tp_name,
62 (int)(s - type->tp_name));
63 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
64 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000065 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000066 if (mod != NULL && PyString_Check(mod)) {
67 Py_INCREF(mod);
68 return mod;
69 }
70 PyErr_SetString(PyExc_AttributeError, "__module__");
71 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000072}
73
Guido van Rossum3926a632001-09-25 16:25:58 +000074static int
75type_set_module(PyTypeObject *type, PyObject *value, void *context)
76{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000077 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000078 strrchr(type->tp_name, '.')) {
79 PyErr_Format(PyExc_TypeError,
80 "can't set %s.__module__", type->tp_name);
81 return -1;
82 }
83 if (!value) {
84 PyErr_Format(PyExc_TypeError,
85 "can't delete %s.__module__", type->tp_name);
86 return -1;
87 }
88 return PyDict_SetItemString(type->tp_dict, "__module__", value);
89}
90
Tim Peters6d6c1a32001-08-02 04:15:00 +000091static PyObject *
92type_dict(PyTypeObject *type, void *context)
93{
94 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095 Py_INCREF(Py_None);
96 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000098 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000099}
100
Tim Peters24008312002-03-17 18:56:20 +0000101static PyObject *
102type_get_doc(PyTypeObject *type, void *context)
103{
104 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000106 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000107 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000108 if (result == NULL) {
109 result = Py_None;
110 Py_INCREF(result);
111 }
112 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000113 result = result->ob_type->tp_descr_get(result, NULL,
114 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000115 }
116 else {
117 Py_INCREF(result);
118 }
Tim Peters24008312002-03-17 18:56:20 +0000119 return result;
120}
121
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000122static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000123 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000125 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000126 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000127 {0}
128};
129
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000130static int
131type_compare(PyObject *v, PyObject *w)
132{
133 /* This is called with type objects only. So we
134 can just compare the addresses. */
135 Py_uintptr_t vv = (Py_uintptr_t)v;
136 Py_uintptr_t ww = (Py_uintptr_t)w;
137 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
138}
139
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000140static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000141type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000143 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000144 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000145
146 mod = type_module(type, NULL);
147 if (mod == NULL)
148 PyErr_Clear();
149 else if (!PyString_Check(mod)) {
150 Py_DECREF(mod);
151 mod = NULL;
152 }
153 name = type_name(type, NULL);
154 if (name == NULL)
155 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000156
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000157 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
158 kind = "class";
159 else
160 kind = "type";
161
Barry Warsaw7ce36942001-08-24 18:34:26 +0000162 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000163 rtn = PyString_FromFormat("<%s '%s.%s'>",
164 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000165 PyString_AS_STRING(mod),
166 PyString_AS_STRING(name));
167 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000168 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000169 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000170
Guido van Rossumc3542212001-08-16 09:18:56 +0000171 Py_XDECREF(mod);
172 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000173 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Tim Peters6d6c1a32001-08-02 04:15:00 +0000176static PyObject *
177type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
178{
179 PyObject *obj;
180
181 if (type->tp_new == NULL) {
182 PyErr_Format(PyExc_TypeError,
183 "cannot create '%.100s' instances",
184 type->tp_name);
185 return NULL;
186 }
187
Tim Peters3f996e72001-09-13 19:18:27 +0000188 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000189 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000190 /* Ugly exception: when the call was type(something),
191 don't call tp_init on the result. */
192 if (type == &PyType_Type &&
193 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
194 (kwds == NULL ||
195 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
196 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000197 /* If the returned object is not an instance of type,
198 it won't be initialized. */
199 if (!PyType_IsSubtype(obj->ob_type, type))
200 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201 type = obj->ob_type;
202 if (type->tp_init != NULL &&
203 type->tp_init(obj, args, kwds) < 0) {
204 Py_DECREF(obj);
205 obj = NULL;
206 }
207 }
208 return obj;
209}
210
211PyObject *
212PyType_GenericAlloc(PyTypeObject *type, int nitems)
213{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000214 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000215 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000216
217 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000218 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000219 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000220 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000221
Neil Schemenauerc806c882001-08-29 23:54:54 +0000222 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000223 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000224
Neil Schemenauerc806c882001-08-29 23:54:54 +0000225 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000226
Tim Peters6d6c1a32001-08-02 04:15:00 +0000227 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
228 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000229
Tim Peters6d6c1a32001-08-02 04:15:00 +0000230 if (type->tp_itemsize == 0)
231 PyObject_INIT(obj, type);
232 else
233 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000234
Tim Peters6d6c1a32001-08-02 04:15:00 +0000235 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000236 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000237 return obj;
238}
239
240PyObject *
241PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
242{
243 return type->tp_alloc(type, 0);
244}
245
Guido van Rossum9475a232001-10-05 20:51:39 +0000246/* Helpers for subtyping */
247
248static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000249traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
250{
251 int i, n;
252 PyMemberDef *mp;
253
254 n = type->ob_size;
255 mp = ((etype *)type)->members;
256 for (i = 0; i < n; i++, mp++) {
257 if (mp->type == T_OBJECT_EX) {
258 char *addr = (char *)self + mp->offset;
259 PyObject *obj = *(PyObject **)addr;
260 if (obj != NULL) {
261 int err = visit(obj, arg);
262 if (err)
263 return err;
264 }
265 }
266 }
267 return 0;
268}
269
270static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000271subtype_traverse(PyObject *self, visitproc visit, void *arg)
272{
273 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000274 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000275
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000276 /* Find the nearest base with a different tp_traverse,
277 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000278 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000279 base = type;
280 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
281 if (base->ob_size) {
282 int err = traverse_slots(base, self, visit, arg);
283 if (err)
284 return err;
285 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000286 base = base->tp_base;
287 assert(base);
288 }
289
290 if (type->tp_dictoffset != base->tp_dictoffset) {
291 PyObject **dictptr = _PyObject_GetDictPtr(self);
292 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000293 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000294 if (err)
295 return err;
296 }
297 }
298
Guido van Rossuma3862092002-06-10 15:24:42 +0000299 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
300 /* For a heaptype, the instances count as references
301 to the type. Traverse the type so the collector
302 can find cycles involving this link. */
303 int err = visit((PyObject *)type, arg);
304 if (err)
305 return err;
306 }
307
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000308 if (basetraverse)
309 return basetraverse(self, visit, arg);
310 return 0;
311}
312
313static void
314clear_slots(PyTypeObject *type, PyObject *self)
315{
316 int i, n;
317 PyMemberDef *mp;
318
319 n = type->ob_size;
320 mp = ((etype *)type)->members;
321 for (i = 0; i < n; i++, mp++) {
322 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
323 char *addr = (char *)self + mp->offset;
324 PyObject *obj = *(PyObject **)addr;
325 if (obj != NULL) {
326 Py_DECREF(obj);
327 *(PyObject **)addr = NULL;
328 }
329 }
330 }
331}
332
333static int
334subtype_clear(PyObject *self)
335{
336 PyTypeObject *type, *base;
337 inquiry baseclear;
338
339 /* Find the nearest base with a different tp_clear
340 and clear slots while we're at it */
341 type = self->ob_type;
342 base = type;
343 while ((baseclear = base->tp_clear) == subtype_clear) {
344 if (base->ob_size)
345 clear_slots(base, self);
346 base = base->tp_base;
347 assert(base);
348 }
349
Guido van Rossuma3862092002-06-10 15:24:42 +0000350 /* There's no need to clear the instance dict (if any);
351 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000352
353 if (baseclear)
354 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000355 return 0;
356}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000357
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000358staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
359
360static int
361call_finalizer(PyObject *self)
362{
363 static PyObject *del_str = NULL;
364 PyObject *del, *res;
365 PyObject *error_type, *error_value, *error_traceback;
366
367 /* Temporarily resurrect the object. */
368#ifdef Py_TRACE_REFS
369#ifndef Py_REF_DEBUG
370# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
371#endif
372 /* much too complicated if Py_TRACE_REFS defined */
373 _Py_NewReference((PyObject *)self);
374#ifdef COUNT_ALLOCS
375 /* compensate for boost in _Py_NewReference; note that
376 * _Py_RefTotal was also boosted; we'll knock that down later.
377 */
378 self->ob_type->tp_allocs--;
379#endif
380#else /* !Py_TRACE_REFS */
381 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
382 Py_INCREF(self);
383#endif /* !Py_TRACE_REFS */
384
385 /* Save the current exception, if any. */
386 PyErr_Fetch(&error_type, &error_value, &error_traceback);
387
388 /* Execute __del__ method, if any. */
389 del = lookup_maybe(self, "__del__", &del_str);
390 if (del != NULL) {
391 res = PyEval_CallObject(del, NULL);
392 if (res == NULL)
393 PyErr_WriteUnraisable(del);
394 else
395 Py_DECREF(res);
396 Py_DECREF(del);
397 }
398
399 /* Restore the saved exception. */
400 PyErr_Restore(error_type, error_value, error_traceback);
401
402 /* Undo the temporary resurrection; can't use DECREF here, it would
403 * cause a recursive call.
404 */
405#ifdef Py_REF_DEBUG
406 /* _Py_RefTotal was boosted either by _Py_NewReference or
407 * Py_INCREF above.
408 */
409 _Py_RefTotal--;
410#endif
411 if (--self->ob_refcnt > 0) {
412#ifdef COUNT_ALLOCS
413 self->ob_type->tp_frees--;
414#endif
415 _PyObject_GC_TRACK(self);
416 return -1; /* __del__ added a reference; don't delete now */
417 }
418#ifdef Py_TRACE_REFS
419 _Py_ForgetReference((PyObject *)self);
420#ifdef COUNT_ALLOCS
421 /* compensate for increment in _Py_ForgetReference */
422 self->ob_type->tp_frees--;
423#endif
424#endif
425
426 return 0;
427}
428
Tim Peters6d6c1a32001-08-02 04:15:00 +0000429static void
430subtype_dealloc(PyObject *self)
431{
Guido van Rossum14227b42001-12-06 02:35:58 +0000432 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000433 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000434
435 /* This exists so we can DECREF self->ob_type */
436
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000437 if (call_finalizer(self) < 0)
438 return;
439
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000440 /* Find the nearest base with a different tp_dealloc
441 and clear slots while we're at it */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000442 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000443 base = type;
444 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
445 if (base->ob_size)
446 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447 base = base->tp_base;
448 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000449 }
450
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000452 if (type->tp_dictoffset && !base->tp_dictoffset) {
453 PyObject **dictptr = _PyObject_GetDictPtr(self);
454 if (dictptr != NULL) {
455 PyObject *dict = *dictptr;
456 if (dict != NULL) {
457 Py_DECREF(dict);
458 *dictptr = NULL;
459 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 }
461 }
462
Guido van Rossum9676b222001-08-17 20:32:36 +0000463 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000464 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000465 PyObject_ClearWeakRefs(self);
466
Tim Peters6d6c1a32001-08-02 04:15:00 +0000467 /* Finalize GC if the base doesn't do GC and we do */
468 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000469 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000470
471 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000472 assert(basedealloc);
473 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474
475 /* Can't reference self beyond this point */
476 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
477 Py_DECREF(type);
478 }
479}
480
Tim Peters6d6c1a32001-08-02 04:15:00 +0000481staticforward PyTypeObject *solid_base(PyTypeObject *type);
482
Tim Peters6d6c1a32001-08-02 04:15:00 +0000483/* type test with subclassing support */
484
485int
486PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
487{
488 PyObject *mro;
489
Guido van Rossum9478d072001-09-07 18:52:13 +0000490 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
491 return b == a || b == &PyBaseObject_Type;
492
Tim Peters6d6c1a32001-08-02 04:15:00 +0000493 mro = a->tp_mro;
494 if (mro != NULL) {
495 /* Deal with multiple inheritance without recursion
496 by walking the MRO tuple */
497 int i, n;
498 assert(PyTuple_Check(mro));
499 n = PyTuple_GET_SIZE(mro);
500 for (i = 0; i < n; i++) {
501 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
502 return 1;
503 }
504 return 0;
505 }
506 else {
507 /* a is not completely initilized yet; follow tp_base */
508 do {
509 if (a == b)
510 return 1;
511 a = a->tp_base;
512 } while (a != NULL);
513 return b == &PyBaseObject_Type;
514 }
515}
516
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000517/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000518 without looking in the instance dictionary
519 (so we can't use PyObject_GetAttr) but still binding
520 it to the instance. The arguments are the object,
521 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000522 static variable used to cache the interned Python string.
523
524 Two variants:
525
526 - lookup_maybe() returns NULL without raising an exception
527 when the _PyType_Lookup() call fails;
528
529 - lookup_method() always raises an exception upon errors.
530*/
Guido van Rossum60718732001-08-28 17:47:51 +0000531
532static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000533lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000534{
535 PyObject *res;
536
537 if (*attrobj == NULL) {
538 *attrobj = PyString_InternFromString(attrstr);
539 if (*attrobj == NULL)
540 return NULL;
541 }
542 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000543 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000544 descrgetfunc f;
545 if ((f = res->ob_type->tp_descr_get) == NULL)
546 Py_INCREF(res);
547 else
548 res = f(res, self, (PyObject *)(self->ob_type));
549 }
550 return res;
551}
552
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000553static PyObject *
554lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
555{
556 PyObject *res = lookup_maybe(self, attrstr, attrobj);
557 if (res == NULL && !PyErr_Occurred())
558 PyErr_SetObject(PyExc_AttributeError, *attrobj);
559 return res;
560}
561
Guido van Rossum2730b132001-08-28 18:22:14 +0000562/* A variation of PyObject_CallMethod that uses lookup_method()
563 instead of PyObject_GetAttrString(). This uses the same convention
564 as lookup_method to cache the interned name string object. */
565
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000566static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000567call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
568{
569 va_list va;
570 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000571 va_start(va, format);
572
Guido van Rossumda21c012001-10-03 00:50:18 +0000573 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000574 if (func == NULL) {
575 va_end(va);
576 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000577 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000578 return NULL;
579 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000580
581 if (format && *format)
582 args = Py_VaBuildValue(format, va);
583 else
584 args = PyTuple_New(0);
585
586 va_end(va);
587
588 if (args == NULL)
589 return NULL;
590
591 assert(PyTuple_Check(args));
592 retval = PyObject_Call(func, args, NULL);
593
594 Py_DECREF(args);
595 Py_DECREF(func);
596
597 return retval;
598}
599
600/* Clone of call_method() that returns NotImplemented when the lookup fails. */
601
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000602static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000603call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
604{
605 va_list va;
606 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000607 va_start(va, format);
608
Guido van Rossumda21c012001-10-03 00:50:18 +0000609 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000610 if (func == NULL) {
611 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000612 if (!PyErr_Occurred()) {
613 Py_INCREF(Py_NotImplemented);
614 return Py_NotImplemented;
615 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000616 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000617 }
618
619 if (format && *format)
620 args = Py_VaBuildValue(format, va);
621 else
622 args = PyTuple_New(0);
623
624 va_end(va);
625
Guido van Rossum717ce002001-09-14 16:58:08 +0000626 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000627 return NULL;
628
Guido van Rossum717ce002001-09-14 16:58:08 +0000629 assert(PyTuple_Check(args));
630 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000631
632 Py_DECREF(args);
633 Py_DECREF(func);
634
635 return retval;
636}
637
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638/* Method resolution order algorithm from "Putting Metaclasses to Work"
639 by Forman and Danforth (Addison-Wesley 1999). */
640
641static int
642conservative_merge(PyObject *left, PyObject *right)
643{
644 int left_size;
645 int right_size;
646 int i, j, r, ok;
647 PyObject *temp, *rr;
648
649 assert(PyList_Check(left));
650 assert(PyList_Check(right));
651
652 again:
653 left_size = PyList_GET_SIZE(left);
654 right_size = PyList_GET_SIZE(right);
655 for (i = 0; i < left_size; i++) {
656 for (j = 0; j < right_size; j++) {
657 if (PyList_GET_ITEM(left, i) ==
658 PyList_GET_ITEM(right, j)) {
659 /* found a merge point */
660 temp = PyList_New(0);
661 if (temp == NULL)
662 return -1;
663 for (r = 0; r < j; r++) {
664 rr = PyList_GET_ITEM(right, r);
665 ok = PySequence_Contains(left, rr);
666 if (ok < 0) {
667 Py_DECREF(temp);
668 return -1;
669 }
670 if (!ok) {
671 ok = PyList_Append(temp, rr);
672 if (ok < 0) {
673 Py_DECREF(temp);
674 return -1;
675 }
676 }
677 }
678 ok = PyList_SetSlice(left, i, i, temp);
679 Py_DECREF(temp);
680 if (ok < 0)
681 return -1;
682 ok = PyList_SetSlice(right, 0, j+1, NULL);
683 if (ok < 0)
684 return -1;
685 goto again;
686 }
687 }
688 }
689 return PyList_SetSlice(left, left_size, left_size, right);
690}
691
692static int
693serious_order_disagreements(PyObject *left, PyObject *right)
694{
695 return 0; /* XXX later -- for now, we cheat: "don't do that" */
696}
697
Tim Petersa91e9642001-11-14 23:32:33 +0000698static int
699fill_classic_mro(PyObject *mro, PyObject *cls)
700{
701 PyObject *bases, *base;
702 int i, n;
703
704 assert(PyList_Check(mro));
705 assert(PyClass_Check(cls));
706 i = PySequence_Contains(mro, cls);
707 if (i < 0)
708 return -1;
709 if (!i) {
710 if (PyList_Append(mro, cls) < 0)
711 return -1;
712 }
713 bases = ((PyClassObject *)cls)->cl_bases;
714 assert(bases && PyTuple_Check(bases));
715 n = PyTuple_GET_SIZE(bases);
716 for (i = 0; i < n; i++) {
717 base = PyTuple_GET_ITEM(bases, i);
718 if (fill_classic_mro(mro, base) < 0)
719 return -1;
720 }
721 return 0;
722}
723
724static PyObject *
725classic_mro(PyObject *cls)
726{
727 PyObject *mro;
728
729 assert(PyClass_Check(cls));
730 mro = PyList_New(0);
731 if (mro != NULL) {
732 if (fill_classic_mro(mro, cls) == 0)
733 return mro;
734 Py_DECREF(mro);
735 }
736 return NULL;
737}
738
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739static PyObject *
740mro_implementation(PyTypeObject *type)
741{
742 int i, n, ok;
743 PyObject *bases, *result;
744
Guido van Rossum63517572002-06-18 16:44:57 +0000745 if(type->tp_dict == NULL) {
746 if(PyType_Ready(type) < 0)
747 return NULL;
748 }
749
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750 bases = type->tp_bases;
751 n = PyTuple_GET_SIZE(bases);
752 result = Py_BuildValue("[O]", (PyObject *)type);
753 if (result == NULL)
754 return NULL;
755 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000756 PyObject *base = PyTuple_GET_ITEM(bases, i);
757 PyObject *parentMRO;
758 if (PyType_Check(base))
759 parentMRO = PySequence_List(
760 ((PyTypeObject*)base)->tp_mro);
761 else
762 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000763 if (parentMRO == NULL) {
764 Py_DECREF(result);
765 return NULL;
766 }
767 if (serious_order_disagreements(result, parentMRO)) {
768 Py_DECREF(result);
769 return NULL;
770 }
771 ok = conservative_merge(result, parentMRO);
772 Py_DECREF(parentMRO);
773 if (ok < 0) {
774 Py_DECREF(result);
775 return NULL;
776 }
777 }
778 return result;
779}
780
781static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000782mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783{
784 PyTypeObject *type = (PyTypeObject *)self;
785
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786 return mro_implementation(type);
787}
788
789static int
790mro_internal(PyTypeObject *type)
791{
792 PyObject *mro, *result, *tuple;
793
794 if (type->ob_type == &PyType_Type) {
795 result = mro_implementation(type);
796 }
797 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000798 static PyObject *mro_str;
799 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800 if (mro == NULL)
801 return -1;
802 result = PyObject_CallObject(mro, NULL);
803 Py_DECREF(mro);
804 }
805 if (result == NULL)
806 return -1;
807 tuple = PySequence_Tuple(result);
808 Py_DECREF(result);
809 type->tp_mro = tuple;
810 return 0;
811}
812
813
814/* Calculate the best base amongst multiple base classes.
815 This is the first one that's on the path to the "solid base". */
816
817static PyTypeObject *
818best_base(PyObject *bases)
819{
820 int i, n;
821 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000822 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823
824 assert(PyTuple_Check(bases));
825 n = PyTuple_GET_SIZE(bases);
826 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000827 base = NULL;
828 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000829 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000830 base_proto = PyTuple_GET_ITEM(bases, i);
831 if (PyClass_Check(base_proto))
832 continue;
833 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 PyErr_SetString(
835 PyExc_TypeError,
836 "bases must be types");
837 return NULL;
838 }
Tim Petersa91e9642001-11-14 23:32:33 +0000839 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000841 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 return NULL;
843 }
844 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000845 if (winner == NULL) {
846 winner = candidate;
847 base = base_i;
848 }
849 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850 ;
851 else if (PyType_IsSubtype(candidate, winner)) {
852 winner = candidate;
853 base = base_i;
854 }
855 else {
856 PyErr_SetString(
857 PyExc_TypeError,
858 "multiple bases have "
859 "instance lay-out conflict");
860 return NULL;
861 }
862 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000863 if (base == NULL)
864 PyErr_SetString(PyExc_TypeError,
865 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866 return base;
867}
868
869static int
870extra_ivars(PyTypeObject *type, PyTypeObject *base)
871{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000872 size_t t_size = type->tp_basicsize;
873 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874
Guido van Rossum9676b222001-08-17 20:32:36 +0000875 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000876 if (type->tp_itemsize || base->tp_itemsize) {
877 /* If itemsize is involved, stricter rules */
878 return t_size != b_size ||
879 type->tp_itemsize != base->tp_itemsize;
880 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000881 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
882 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
883 t_size -= sizeof(PyObject *);
884 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
885 type->tp_dictoffset + sizeof(PyObject *) == t_size)
886 t_size -= sizeof(PyObject *);
887
888 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889}
890
891static PyTypeObject *
892solid_base(PyTypeObject *type)
893{
894 PyTypeObject *base;
895
896 if (type->tp_base)
897 base = solid_base(type->tp_base);
898 else
899 base = &PyBaseObject_Type;
900 if (extra_ivars(type, base))
901 return type;
902 else
903 return base;
904}
905
906staticforward void object_dealloc(PyObject *);
907staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000908staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000909staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910
911static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000912subtype_dict(PyObject *obj, void *context)
913{
914 PyObject **dictptr = _PyObject_GetDictPtr(obj);
915 PyObject *dict;
916
917 if (dictptr == NULL) {
918 PyErr_SetString(PyExc_AttributeError,
919 "This object has no __dict__");
920 return NULL;
921 }
922 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000923 if (dict == NULL)
924 *dictptr = dict = PyDict_New();
925 Py_XINCREF(dict);
926 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000927}
928
Guido van Rossum6661be32001-10-26 04:26:12 +0000929static int
930subtype_setdict(PyObject *obj, PyObject *value, void *context)
931{
932 PyObject **dictptr = _PyObject_GetDictPtr(obj);
933 PyObject *dict;
934
935 if (dictptr == NULL) {
936 PyErr_SetString(PyExc_AttributeError,
937 "This object has no __dict__");
938 return -1;
939 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000940 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000941 PyErr_SetString(PyExc_TypeError,
942 "__dict__ must be set to a dictionary");
943 return -1;
944 }
945 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000946 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000947 *dictptr = value;
948 Py_XDECREF(dict);
949 return 0;
950}
951
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000952static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000953 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000954 {0},
955};
956
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000957/* bozo: __getstate__ that raises TypeError */
958
959static PyObject *
960bozo_func(PyObject *self, PyObject *args)
961{
962 PyErr_SetString(PyExc_TypeError,
963 "a class that defines __slots__ without "
964 "defining __getstate__ cannot be pickled");
965 return NULL;
966}
967
Neal Norwitz93c1e232002-03-31 16:06:11 +0000968static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000969
970static PyObject *bozo_obj = NULL;
971
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000972static int
973valid_identifier(PyObject *s)
974{
975 char *p;
976 int i, n;
977
978 if (!PyString_Check(s)) {
979 PyErr_SetString(PyExc_TypeError,
980 "__slots__ must be strings");
981 return 0;
982 }
983 p = PyString_AS_STRING(s);
984 n = PyString_GET_SIZE(s);
985 /* We must reject an empty name. As a hack, we bump the
986 length to 1 so that the loop will balk on the trailing \0. */
987 if (n == 0)
988 n = 1;
989 for (i = 0; i < n; i++, p++) {
990 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
991 PyErr_SetString(PyExc_TypeError,
992 "__slots__ must be identifiers");
993 return 0;
994 }
995 }
996 return 1;
997}
998
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000999static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1001{
1002 PyObject *name, *bases, *dict;
1003 static char *kwlist[] = {"name", "bases", "dict", 0};
1004 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001005 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001007 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001008 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009
Tim Peters3abca122001-10-27 19:37:48 +00001010 assert(args != NULL && PyTuple_Check(args));
1011 assert(kwds == NULL || PyDict_Check(kwds));
1012
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001013 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001014 {
1015 const int nargs = PyTuple_GET_SIZE(args);
1016 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1017
1018 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1019 PyObject *x = PyTuple_GET_ITEM(args, 0);
1020 Py_INCREF(x->ob_type);
1021 return (PyObject *) x->ob_type;
1022 }
1023
1024 /* SF bug 475327 -- if that didn't trigger, we need 3
1025 arguments. but PyArg_ParseTupleAndKeywords below may give
1026 a msg saying type() needs exactly 3. */
1027 if (nargs + nkwds != 3) {
1028 PyErr_SetString(PyExc_TypeError,
1029 "type() takes 1 or 3 arguments");
1030 return NULL;
1031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032 }
1033
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001034 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1036 &name,
1037 &PyTuple_Type, &bases,
1038 &PyDict_Type, &dict))
1039 return NULL;
1040
1041 /* Determine the proper metatype to deal with this,
1042 and check for metatype conflicts while we're at it.
1043 Note that if some other metatype wins to contract,
1044 it's possible that its instances are not types. */
1045 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001046 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047 for (i = 0; i < nbases; i++) {
1048 tmp = PyTuple_GET_ITEM(bases, i);
1049 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001050 if (tmptype == &PyClass_Type)
1051 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001052 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001054 if (PyType_IsSubtype(tmptype, winner)) {
1055 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056 continue;
1057 }
1058 PyErr_SetString(PyExc_TypeError,
1059 "metatype conflict among bases");
1060 return NULL;
1061 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001062 if (winner != metatype) {
1063 if (winner->tp_new != type_new) /* Pass it to the winner */
1064 return winner->tp_new(winner, args, kwds);
1065 metatype = winner;
1066 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001067
1068 /* Adjust for empty tuple bases */
1069 if (nbases == 0) {
1070 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1071 if (bases == NULL)
1072 return NULL;
1073 nbases = 1;
1074 }
1075 else
1076 Py_INCREF(bases);
1077
1078 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1079
1080 /* Calculate best base, and check that all bases are type objects */
1081 base = best_base(bases);
1082 if (base == NULL)
1083 return NULL;
1084 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1085 PyErr_Format(PyExc_TypeError,
1086 "type '%.100s' is not an acceptable base type",
1087 base->tp_name);
1088 return NULL;
1089 }
1090
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 /* Check for a __slots__ sequence variable in dict, and count it */
1092 slots = PyDict_GetItemString(dict, "__slots__");
1093 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001094 add_dict = 0;
1095 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096 if (slots != NULL) {
1097 /* Make it into a tuple */
1098 if (PyString_Check(slots))
1099 slots = Py_BuildValue("(O)", slots);
1100 else
1101 slots = PySequence_Tuple(slots);
1102 if (slots == NULL)
1103 return NULL;
1104 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001105 if (nslots > 0 && base->tp_itemsize != 0) {
1106 PyErr_Format(PyExc_TypeError,
1107 "nonempty __slots__ "
1108 "not supported for subtype of '%s'",
1109 base->tp_name);
1110 return NULL;
1111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 for (i = 0; i < nslots; i++) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001113 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114 Py_DECREF(slots);
1115 return NULL;
1116 }
1117 }
1118 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001119 if (slots != NULL) {
1120 /* See if *this* class defines __getstate__ */
1121 PyObject *getstate = PyDict_GetItemString(dict,
1122 "__getstate__");
1123 if (getstate == NULL) {
1124 /* If not, provide a bozo that raises TypeError */
1125 if (bozo_obj == NULL) {
1126 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1127 if (bozo_obj == NULL) {
1128 /* XXX decref various things */
1129 return NULL;
1130 }
1131 }
1132 if (PyDict_SetItemString(dict,
1133 "__getstate__",
1134 bozo_obj) < 0) {
1135 /* XXX decref various things */
1136 return NULL;
1137 }
1138 }
1139 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 if (slots == NULL && base->tp_dictoffset == 0 &&
1141 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001142 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001143 add_dict++;
1144 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001145 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1146 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001147 nslots++;
1148 add_weak++;
1149 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150
1151 /* XXX From here until type is safely allocated,
1152 "return NULL" may leak slots! */
1153
1154 /* Allocate the type object */
1155 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1156 if (type == NULL)
1157 return NULL;
1158
1159 /* Keep name and slots alive in the extended type object */
1160 et = (etype *)type;
1161 Py_INCREF(name);
1162 et->name = name;
1163 et->slots = slots;
1164
Guido van Rossumdc91b992001-08-08 22:26:22 +00001165 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1167 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001168 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1169 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001170
1171 /* It's a new-style number unless it specifically inherits any
1172 old-style numeric behavior */
1173 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1174 (base->tp_as_number == NULL))
1175 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1176
1177 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 type->tp_as_number = &et->as_number;
1179 type->tp_as_sequence = &et->as_sequence;
1180 type->tp_as_mapping = &et->as_mapping;
1181 type->tp_as_buffer = &et->as_buffer;
1182 type->tp_name = PyString_AS_STRING(name);
1183
1184 /* Set tp_base and tp_bases */
1185 type->tp_bases = bases;
1186 Py_INCREF(base);
1187 type->tp_base = base;
1188
Guido van Rossum687ae002001-10-15 22:03:32 +00001189 /* Initialize tp_dict from passed-in dict */
1190 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191 if (dict == NULL) {
1192 Py_DECREF(type);
1193 return NULL;
1194 }
1195
Guido van Rossumc3542212001-08-16 09:18:56 +00001196 /* Set __module__ in the dict */
1197 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1198 tmp = PyEval_GetGlobals();
1199 if (tmp != NULL) {
1200 tmp = PyDict_GetItemString(tmp, "__name__");
1201 if (tmp != NULL) {
1202 if (PyDict_SetItemString(dict, "__module__",
1203 tmp) < 0)
1204 return NULL;
1205 }
1206 }
1207 }
1208
Tim Peters2f93e282001-10-04 05:27:00 +00001209 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001210 and is a string. The __doc__ accessor will first look for tp_doc;
1211 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001212 */
1213 {
1214 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1215 if (doc != NULL && PyString_Check(doc)) {
1216 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001217 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001218 if (type->tp_doc == NULL) {
1219 Py_DECREF(type);
1220 return NULL;
1221 }
1222 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1223 }
1224 }
1225
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226 /* Special-case __new__: if it's a plain function,
1227 make it a static function */
1228 tmp = PyDict_GetItemString(dict, "__new__");
1229 if (tmp != NULL && PyFunction_Check(tmp)) {
1230 tmp = PyStaticMethod_New(tmp);
1231 if (tmp == NULL) {
1232 Py_DECREF(type);
1233 return NULL;
1234 }
1235 PyDict_SetItemString(dict, "__new__", tmp);
1236 Py_DECREF(tmp);
1237 }
1238
1239 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1240 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001241 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 if (slots != NULL) {
1243 for (i = 0; i < nslots; i++, mp++) {
1244 mp->name = PyString_AS_STRING(
1245 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001246 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001247 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001248 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001249 strcmp(mp->name, "__weakref__") == 0) {
1250 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001251 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001252 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001253 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 slotoffset += sizeof(PyObject *);
1255 }
1256 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001257 else {
1258 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001259 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001260 type->tp_dictoffset =
1261 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001262 else
1263 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001264 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001265 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001266 }
1267 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001268 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001269 type->tp_weaklistoffset = slotoffset;
1270 mp->name = "__weakref__";
1271 mp->type = T_OBJECT;
1272 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001273 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001274 mp++;
1275 slotoffset += sizeof(PyObject *);
1276 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277 }
1278 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001279 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001280 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281
1282 /* Special case some slots */
1283 if (type->tp_dictoffset != 0 || nslots > 0) {
1284 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1285 type->tp_getattro = PyObject_GenericGetAttr;
1286 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1287 type->tp_setattro = PyObject_GenericSetAttr;
1288 }
1289 type->tp_dealloc = subtype_dealloc;
1290
Guido van Rossum9475a232001-10-05 20:51:39 +00001291 /* Enable GC unless there are really no instance variables possible */
1292 if (!(type->tp_basicsize == sizeof(PyObject) &&
1293 type->tp_itemsize == 0))
1294 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1295
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296 /* Always override allocation strategy to use regular heap */
1297 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001298 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001299 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001300 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001301 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001302 }
1303 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001304 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305
1306 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001307 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308 Py_DECREF(type);
1309 return NULL;
1310 }
1311
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001312 /* Put the proper slots in place */
1313 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001314
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 return (PyObject *)type;
1316}
1317
1318/* Internal API to look for a name through the MRO.
1319 This returns a borrowed reference, and doesn't set an exception! */
1320PyObject *
1321_PyType_Lookup(PyTypeObject *type, PyObject *name)
1322{
1323 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001324 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325
Guido van Rossum687ae002001-10-15 22:03:32 +00001326 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001328
1329 /* If mro is NULL, the type is either not yet initialized
1330 by PyType_Ready(), or already cleared by type_clear().
1331 Either way the safest thing to do is to return NULL. */
1332 if (mro == NULL)
1333 return NULL;
1334
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 assert(PyTuple_Check(mro));
1336 n = PyTuple_GET_SIZE(mro);
1337 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001338 base = PyTuple_GET_ITEM(mro, i);
1339 if (PyClass_Check(base))
1340 dict = ((PyClassObject *)base)->cl_dict;
1341 else {
1342 assert(PyType_Check(base));
1343 dict = ((PyTypeObject *)base)->tp_dict;
1344 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345 assert(dict && PyDict_Check(dict));
1346 res = PyDict_GetItem(dict, name);
1347 if (res != NULL)
1348 return res;
1349 }
1350 return NULL;
1351}
1352
1353/* This is similar to PyObject_GenericGetAttr(),
1354 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1355static PyObject *
1356type_getattro(PyTypeObject *type, PyObject *name)
1357{
1358 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001359 PyObject *meta_attribute, *attribute;
1360 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001361
1362 /* Initialize this type (we'll assume the metatype is initialized) */
1363 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001364 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001365 return NULL;
1366 }
1367
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001368 /* No readable descriptor found yet */
1369 meta_get = NULL;
1370
1371 /* Look for the attribute in the metatype */
1372 meta_attribute = _PyType_Lookup(metatype, name);
1373
1374 if (meta_attribute != NULL) {
1375 meta_get = meta_attribute->ob_type->tp_descr_get;
1376
1377 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1378 /* Data descriptors implement tp_descr_set to intercept
1379 * writes. Assume the attribute is not overridden in
1380 * type's tp_dict (and bases): call the descriptor now.
1381 */
1382 return meta_get(meta_attribute, (PyObject *)type,
1383 (PyObject *)metatype);
1384 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 }
1386
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001387 /* No data descriptor found on metatype. Look in tp_dict of this
1388 * type and its bases */
1389 attribute = _PyType_Lookup(type, name);
1390 if (attribute != NULL) {
1391 /* Implement descriptor functionality, if any */
1392 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1393 if (local_get != NULL) {
1394 /* NULL 2nd argument indicates the descriptor was
1395 * found on the target object itself (or a base) */
1396 return local_get(attribute, (PyObject *)NULL,
1397 (PyObject *)type);
1398 }
1399
1400 Py_INCREF(attribute);
1401 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 }
1403
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001404 /* No attribute found in local __dict__ (or bases): use the
1405 * descriptor from the metatype, if any */
1406 if (meta_get != NULL)
1407 return meta_get(meta_attribute, (PyObject *)type,
1408 (PyObject *)metatype);
1409
1410 /* If an ordinary attribute was found on the metatype, return it now */
1411 if (meta_attribute != NULL) {
1412 Py_INCREF(meta_attribute);
1413 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 }
1415
1416 /* Give up */
1417 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001418 "type object '%.50s' has no attribute '%.400s'",
1419 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420 return NULL;
1421}
1422
1423static int
1424type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1425{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001426 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1427 PyErr_Format(
1428 PyExc_TypeError,
1429 "can't set attributes of built-in/extension type '%s'",
1430 type->tp_name);
1431 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001432 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001433 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1434 return -1;
1435 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436}
1437
1438static void
1439type_dealloc(PyTypeObject *type)
1440{
1441 etype *et;
1442
1443 /* Assert this is a heap-allocated type object */
1444 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001445 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001446 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447 et = (etype *)type;
1448 Py_XDECREF(type->tp_base);
1449 Py_XDECREF(type->tp_dict);
1450 Py_XDECREF(type->tp_bases);
1451 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001452 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001453 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454 Py_XDECREF(et->name);
1455 Py_XDECREF(et->slots);
1456 type->ob_type->tp_free((PyObject *)type);
1457}
1458
Guido van Rossum1c450732001-10-08 15:18:27 +00001459static PyObject *
1460type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1461{
1462 PyObject *list, *raw, *ref;
1463 int i, n;
1464
1465 list = PyList_New(0);
1466 if (list == NULL)
1467 return NULL;
1468 raw = type->tp_subclasses;
1469 if (raw == NULL)
1470 return list;
1471 assert(PyList_Check(raw));
1472 n = PyList_GET_SIZE(raw);
1473 for (i = 0; i < n; i++) {
1474 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001475 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001476 ref = PyWeakref_GET_OBJECT(ref);
1477 if (ref != Py_None) {
1478 if (PyList_Append(list, ref) < 0) {
1479 Py_DECREF(list);
1480 return NULL;
1481 }
1482 }
1483 }
1484 return list;
1485}
1486
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001488 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001490 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1491 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492 {0}
1493};
1494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001495PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001497"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001498
Guido van Rossum048eb752001-10-02 21:24:57 +00001499static int
1500type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1501{
Guido van Rossum048eb752001-10-02 21:24:57 +00001502 int err;
1503
Guido van Rossuma3862092002-06-10 15:24:42 +00001504 /* Because of type_is_gc(), the collector only calls this
1505 for heaptypes. */
1506 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001507
1508#define VISIT(SLOT) \
1509 if (SLOT) { \
1510 err = visit((PyObject *)(SLOT), arg); \
1511 if (err) \
1512 return err; \
1513 }
1514
1515 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001516 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001517 VISIT(type->tp_mro);
1518 VISIT(type->tp_bases);
1519 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00001520
1521 /* There's no need to visit type->tp_subclasses or
1522 ((etype *)type)->slots, because they can't be involved
1523 in cycles; tp_subclasses is a list of weak references,
1524 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00001525
1526#undef VISIT
1527
1528 return 0;
1529}
1530
1531static int
1532type_clear(PyTypeObject *type)
1533{
Guido van Rossum048eb752001-10-02 21:24:57 +00001534 PyObject *tmp;
1535
Guido van Rossuma3862092002-06-10 15:24:42 +00001536 /* Because of type_is_gc(), the collector only calls this
1537 for heaptypes. */
1538 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001539
1540#define CLEAR(SLOT) \
1541 if (SLOT) { \
1542 tmp = (PyObject *)(SLOT); \
1543 SLOT = NULL; \
1544 Py_DECREF(tmp); \
1545 }
1546
Guido van Rossuma3862092002-06-10 15:24:42 +00001547 /* The only field we need to clear is tp_mro, which is part of a
1548 hard cycle (its first element is the class itself) that won't
1549 be broken otherwise (it's a tuple and tuples don't have a
1550 tp_clear handler). None of the other fields need to be
1551 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00001552
Guido van Rossuma3862092002-06-10 15:24:42 +00001553 tp_dict:
1554 It is a dict, so the collector will call its tp_clear.
1555
1556 tp_cache:
1557 Not used; if it were, it would be a dict.
1558
1559 tp_bases, tp_base:
1560 If these are involved in a cycle, there must be at least
1561 one other, mutable object in the cycle, e.g. a base
1562 class's dict; the cycle will be broken that way.
1563
1564 tp_subclasses:
1565 A list of weak references can't be part of a cycle; and
1566 lists have their own tp_clear.
1567
1568 slots (in etype):
1569 A tuple of strings can't be part of a cycle.
1570 */
1571
1572 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00001573
Guido van Rossum048eb752001-10-02 21:24:57 +00001574#undef CLEAR
1575
1576 return 0;
1577}
1578
1579static int
1580type_is_gc(PyTypeObject *type)
1581{
1582 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1583}
1584
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001585PyTypeObject PyType_Type = {
1586 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587 0, /* ob_size */
1588 "type", /* tp_name */
1589 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001590 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591 (destructor)type_dealloc, /* tp_dealloc */
1592 0, /* tp_print */
1593 0, /* tp_getattr */
1594 0, /* tp_setattr */
1595 type_compare, /* tp_compare */
1596 (reprfunc)type_repr, /* tp_repr */
1597 0, /* tp_as_number */
1598 0, /* tp_as_sequence */
1599 0, /* tp_as_mapping */
1600 (hashfunc)_Py_HashPointer, /* tp_hash */
1601 (ternaryfunc)type_call, /* tp_call */
1602 0, /* tp_str */
1603 (getattrofunc)type_getattro, /* tp_getattro */
1604 (setattrofunc)type_setattro, /* tp_setattro */
1605 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001606 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1607 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001608 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001609 (traverseproc)type_traverse, /* tp_traverse */
1610 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001612 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 0, /* tp_iter */
1614 0, /* tp_iternext */
1615 type_methods, /* tp_methods */
1616 type_members, /* tp_members */
1617 type_getsets, /* tp_getset */
1618 0, /* tp_base */
1619 0, /* tp_dict */
1620 0, /* tp_descr_get */
1621 0, /* tp_descr_set */
1622 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1623 0, /* tp_init */
1624 0, /* tp_alloc */
1625 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001626 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001627 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001628};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001629
1630
1631/* The base type of all types (eventually)... except itself. */
1632
1633static int
1634object_init(PyObject *self, PyObject *args, PyObject *kwds)
1635{
1636 return 0;
1637}
1638
1639static void
1640object_dealloc(PyObject *self)
1641{
1642 self->ob_type->tp_free(self);
1643}
1644
Guido van Rossum8e248182001-08-12 05:17:56 +00001645static PyObject *
1646object_repr(PyObject *self)
1647{
Guido van Rossum76e69632001-08-16 18:52:43 +00001648 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001649 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001650
Guido van Rossum76e69632001-08-16 18:52:43 +00001651 type = self->ob_type;
1652 mod = type_module(type, NULL);
1653 if (mod == NULL)
1654 PyErr_Clear();
1655 else if (!PyString_Check(mod)) {
1656 Py_DECREF(mod);
1657 mod = NULL;
1658 }
1659 name = type_name(type, NULL);
1660 if (name == NULL)
1661 return NULL;
1662 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001663 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001664 PyString_AS_STRING(mod),
1665 PyString_AS_STRING(name),
1666 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001667 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001668 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001669 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001670 Py_XDECREF(mod);
1671 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001672 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001673}
1674
Guido van Rossumb8f63662001-08-15 23:57:02 +00001675static PyObject *
1676object_str(PyObject *self)
1677{
1678 unaryfunc f;
1679
1680 f = self->ob_type->tp_repr;
1681 if (f == NULL)
1682 f = object_repr;
1683 return f(self);
1684}
1685
Guido van Rossum8e248182001-08-12 05:17:56 +00001686static long
1687object_hash(PyObject *self)
1688{
1689 return _Py_HashPointer(self);
1690}
Guido van Rossum8e248182001-08-12 05:17:56 +00001691
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001692static PyObject *
1693object_get_class(PyObject *self, void *closure)
1694{
1695 Py_INCREF(self->ob_type);
1696 return (PyObject *)(self->ob_type);
1697}
1698
1699static int
1700equiv_structs(PyTypeObject *a, PyTypeObject *b)
1701{
1702 return a == b ||
1703 (a != NULL &&
1704 b != NULL &&
1705 a->tp_basicsize == b->tp_basicsize &&
1706 a->tp_itemsize == b->tp_itemsize &&
1707 a->tp_dictoffset == b->tp_dictoffset &&
1708 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1709 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1710 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1711}
1712
1713static int
1714same_slots_added(PyTypeObject *a, PyTypeObject *b)
1715{
1716 PyTypeObject *base = a->tp_base;
1717 int size;
1718
1719 if (base != b->tp_base)
1720 return 0;
1721 if (equiv_structs(a, base) && equiv_structs(b, base))
1722 return 1;
1723 size = base->tp_basicsize;
1724 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1725 size += sizeof(PyObject *);
1726 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1727 size += sizeof(PyObject *);
1728 return size == a->tp_basicsize && size == b->tp_basicsize;
1729}
1730
1731static int
1732object_set_class(PyObject *self, PyObject *value, void *closure)
1733{
1734 PyTypeObject *old = self->ob_type;
1735 PyTypeObject *new, *newbase, *oldbase;
1736
Guido van Rossumb6b89422002-04-15 01:03:30 +00001737 if (value == NULL) {
1738 PyErr_SetString(PyExc_TypeError,
1739 "can't delete __class__ attribute");
1740 return -1;
1741 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001742 if (!PyType_Check(value)) {
1743 PyErr_Format(PyExc_TypeError,
1744 "__class__ must be set to new-style class, not '%s' object",
1745 value->ob_type->tp_name);
1746 return -1;
1747 }
1748 new = (PyTypeObject *)value;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001749 if (new->tp_dealloc != old->tp_dealloc ||
1750 new->tp_free != old->tp_free)
1751 {
1752 PyErr_Format(PyExc_TypeError,
1753 "__class__ assignment: "
1754 "'%s' deallocator differs from '%s'",
1755 new->tp_name,
1756 old->tp_name);
1757 return -1;
1758 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001759 newbase = new;
1760 oldbase = old;
1761 while (equiv_structs(newbase, newbase->tp_base))
1762 newbase = newbase->tp_base;
1763 while (equiv_structs(oldbase, oldbase->tp_base))
1764 oldbase = oldbase->tp_base;
1765 if (newbase != oldbase &&
1766 (newbase->tp_base != oldbase->tp_base ||
1767 !same_slots_added(newbase, oldbase))) {
1768 PyErr_Format(PyExc_TypeError,
1769 "__class__ assignment: "
1770 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001771 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001772 old->tp_name);
1773 return -1;
1774 }
1775 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1776 Py_INCREF(new);
1777 }
1778 self->ob_type = new;
1779 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1780 Py_DECREF(old);
1781 }
1782 return 0;
1783}
1784
1785static PyGetSetDef object_getsets[] = {
1786 {"__class__", object_get_class, object_set_class,
1787 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 {0}
1789};
1790
Guido van Rossum3926a632001-09-25 16:25:58 +00001791static PyObject *
1792object_reduce(PyObject *self, PyObject *args)
1793{
1794 /* Call copy_reg._reduce(self) */
1795 static PyObject *copy_reg_str;
1796 PyObject *copy_reg, *res;
1797
1798 if (!copy_reg_str) {
1799 copy_reg_str = PyString_InternFromString("copy_reg");
1800 if (copy_reg_str == NULL)
1801 return NULL;
1802 }
1803 copy_reg = PyImport_Import(copy_reg_str);
1804 if (!copy_reg)
1805 return NULL;
1806 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1807 Py_DECREF(copy_reg);
1808 return res;
1809}
1810
1811static PyMethodDef object_methods[] = {
1812 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1813 {0}
1814};
1815
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816PyTypeObject PyBaseObject_Type = {
1817 PyObject_HEAD_INIT(&PyType_Type)
1818 0, /* ob_size */
1819 "object", /* tp_name */
1820 sizeof(PyObject), /* tp_basicsize */
1821 0, /* tp_itemsize */
1822 (destructor)object_dealloc, /* tp_dealloc */
1823 0, /* tp_print */
1824 0, /* tp_getattr */
1825 0, /* tp_setattr */
1826 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001827 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001828 0, /* tp_as_number */
1829 0, /* tp_as_sequence */
1830 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001831 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001832 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001833 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001835 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 0, /* tp_as_buffer */
1837 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1838 "The most base type", /* tp_doc */
1839 0, /* tp_traverse */
1840 0, /* tp_clear */
1841 0, /* tp_richcompare */
1842 0, /* tp_weaklistoffset */
1843 0, /* tp_iter */
1844 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001845 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001846 0, /* tp_members */
1847 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 0, /* tp_base */
1849 0, /* tp_dict */
1850 0, /* tp_descr_get */
1851 0, /* tp_descr_set */
1852 0, /* tp_dictoffset */
1853 object_init, /* tp_init */
1854 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001855 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001856 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857};
1858
1859
1860/* Initialize the __dict__ in a type object */
1861
Fred Drake7bf97152002-03-28 05:33:33 +00001862static PyObject *
1863create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1864{
1865 PyObject *cfunc;
1866 PyObject *result;
1867
1868 cfunc = PyCFunction_New(meth, NULL);
1869 if (cfunc == NULL)
1870 return NULL;
1871 result = func(cfunc);
1872 Py_DECREF(cfunc);
1873 return result;
1874}
1875
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876static int
1877add_methods(PyTypeObject *type, PyMethodDef *meth)
1878{
Guido van Rossum687ae002001-10-15 22:03:32 +00001879 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880
1881 for (; meth->ml_name != NULL; meth++) {
1882 PyObject *descr;
1883 if (PyDict_GetItemString(dict, meth->ml_name))
1884 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001885 if (meth->ml_flags & METH_CLASS) {
1886 if (meth->ml_flags & METH_STATIC) {
1887 PyErr_SetString(PyExc_ValueError,
1888 "method cannot be both class and static");
1889 return -1;
1890 }
1891 descr = create_specialmethod(meth, PyClassMethod_New);
1892 }
1893 else if (meth->ml_flags & METH_STATIC) {
1894 descr = create_specialmethod(meth, PyStaticMethod_New);
1895 }
1896 else {
1897 descr = PyDescr_NewMethod(type, meth);
1898 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899 if (descr == NULL)
1900 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001901 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001902 return -1;
1903 Py_DECREF(descr);
1904 }
1905 return 0;
1906}
1907
1908static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001909add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910{
Guido van Rossum687ae002001-10-15 22:03:32 +00001911 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912
1913 for (; memb->name != NULL; memb++) {
1914 PyObject *descr;
1915 if (PyDict_GetItemString(dict, memb->name))
1916 continue;
1917 descr = PyDescr_NewMember(type, memb);
1918 if (descr == NULL)
1919 return -1;
1920 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1921 return -1;
1922 Py_DECREF(descr);
1923 }
1924 return 0;
1925}
1926
1927static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001928add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001929{
Guido van Rossum687ae002001-10-15 22:03:32 +00001930 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931
1932 for (; gsp->name != NULL; gsp++) {
1933 PyObject *descr;
1934 if (PyDict_GetItemString(dict, gsp->name))
1935 continue;
1936 descr = PyDescr_NewGetSet(type, gsp);
1937
1938 if (descr == NULL)
1939 return -1;
1940 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1941 return -1;
1942 Py_DECREF(descr);
1943 }
1944 return 0;
1945}
1946
Guido van Rossum13d52f02001-08-10 21:24:08 +00001947static void
1948inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949{
1950 int oldsize, newsize;
1951
Guido van Rossum13d52f02001-08-10 21:24:08 +00001952 /* Special flag magic */
1953 if (!type->tp_as_buffer && base->tp_as_buffer) {
1954 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1955 type->tp_flags |=
1956 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1957 }
1958 if (!type->tp_as_sequence && base->tp_as_sequence) {
1959 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1960 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1961 }
1962 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1963 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1964 if ((!type->tp_as_number && base->tp_as_number) ||
1965 (!type->tp_as_sequence && base->tp_as_sequence)) {
1966 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1967 if (!type->tp_as_number && !type->tp_as_sequence) {
1968 type->tp_flags |= base->tp_flags &
1969 Py_TPFLAGS_HAVE_INPLACEOPS;
1970 }
1971 }
1972 /* Wow */
1973 }
1974 if (!type->tp_as_number && base->tp_as_number) {
1975 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1976 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1977 }
1978
1979 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001980 oldsize = base->tp_basicsize;
1981 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1982 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1983 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001984 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1985 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001986 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001987 if (type->tp_traverse == NULL)
1988 type->tp_traverse = base->tp_traverse;
1989 if (type->tp_clear == NULL)
1990 type->tp_clear = base->tp_clear;
1991 }
1992 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001993 /* The condition below could use some explanation.
1994 It appears that tp_new is not inherited for static types
1995 whose base class is 'object'; this seems to be a precaution
1996 so that old extension types don't suddenly become
1997 callable (object.__new__ wouldn't insure the invariants
1998 that the extension type's own factory function ensures).
1999 Heap types, of course, are under our control, so they do
2000 inherit tp_new; static extension types that specify some
2001 other built-in type as the default are considered
2002 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002003 if (base != &PyBaseObject_Type ||
2004 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2005 if (type->tp_new == NULL)
2006 type->tp_new = base->tp_new;
2007 }
2008 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002009 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002010
2011 /* Copy other non-function slots */
2012
2013#undef COPYVAL
2014#define COPYVAL(SLOT) \
2015 if (type->SLOT == 0) type->SLOT = base->SLOT
2016
2017 COPYVAL(tp_itemsize);
2018 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2019 COPYVAL(tp_weaklistoffset);
2020 }
2021 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2022 COPYVAL(tp_dictoffset);
2023 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002024}
2025
2026static void
2027inherit_slots(PyTypeObject *type, PyTypeObject *base)
2028{
2029 PyTypeObject *basebase;
2030
2031#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032#undef COPYSLOT
2033#undef COPYNUM
2034#undef COPYSEQ
2035#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002036#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002037
2038#define SLOTDEFINED(SLOT) \
2039 (base->SLOT != 0 && \
2040 (basebase == NULL || base->SLOT != basebase->SLOT))
2041
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002043 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002044
2045#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2046#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2047#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002048#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049
Guido van Rossum13d52f02001-08-10 21:24:08 +00002050 /* This won't inherit indirect slots (from tp_as_number etc.)
2051 if type doesn't provide the space. */
2052
2053 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2054 basebase = base->tp_base;
2055 if (basebase->tp_as_number == NULL)
2056 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057 COPYNUM(nb_add);
2058 COPYNUM(nb_subtract);
2059 COPYNUM(nb_multiply);
2060 COPYNUM(nb_divide);
2061 COPYNUM(nb_remainder);
2062 COPYNUM(nb_divmod);
2063 COPYNUM(nb_power);
2064 COPYNUM(nb_negative);
2065 COPYNUM(nb_positive);
2066 COPYNUM(nb_absolute);
2067 COPYNUM(nb_nonzero);
2068 COPYNUM(nb_invert);
2069 COPYNUM(nb_lshift);
2070 COPYNUM(nb_rshift);
2071 COPYNUM(nb_and);
2072 COPYNUM(nb_xor);
2073 COPYNUM(nb_or);
2074 COPYNUM(nb_coerce);
2075 COPYNUM(nb_int);
2076 COPYNUM(nb_long);
2077 COPYNUM(nb_float);
2078 COPYNUM(nb_oct);
2079 COPYNUM(nb_hex);
2080 COPYNUM(nb_inplace_add);
2081 COPYNUM(nb_inplace_subtract);
2082 COPYNUM(nb_inplace_multiply);
2083 COPYNUM(nb_inplace_divide);
2084 COPYNUM(nb_inplace_remainder);
2085 COPYNUM(nb_inplace_power);
2086 COPYNUM(nb_inplace_lshift);
2087 COPYNUM(nb_inplace_rshift);
2088 COPYNUM(nb_inplace_and);
2089 COPYNUM(nb_inplace_xor);
2090 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002091 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2092 COPYNUM(nb_true_divide);
2093 COPYNUM(nb_floor_divide);
2094 COPYNUM(nb_inplace_true_divide);
2095 COPYNUM(nb_inplace_floor_divide);
2096 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 }
2098
Guido van Rossum13d52f02001-08-10 21:24:08 +00002099 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2100 basebase = base->tp_base;
2101 if (basebase->tp_as_sequence == NULL)
2102 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103 COPYSEQ(sq_length);
2104 COPYSEQ(sq_concat);
2105 COPYSEQ(sq_repeat);
2106 COPYSEQ(sq_item);
2107 COPYSEQ(sq_slice);
2108 COPYSEQ(sq_ass_item);
2109 COPYSEQ(sq_ass_slice);
2110 COPYSEQ(sq_contains);
2111 COPYSEQ(sq_inplace_concat);
2112 COPYSEQ(sq_inplace_repeat);
2113 }
2114
Guido van Rossum13d52f02001-08-10 21:24:08 +00002115 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2116 basebase = base->tp_base;
2117 if (basebase->tp_as_mapping == NULL)
2118 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002119 COPYMAP(mp_length);
2120 COPYMAP(mp_subscript);
2121 COPYMAP(mp_ass_subscript);
2122 }
2123
Tim Petersfc57ccb2001-10-12 02:38:24 +00002124 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2125 basebase = base->tp_base;
2126 if (basebase->tp_as_buffer == NULL)
2127 basebase = NULL;
2128 COPYBUF(bf_getreadbuffer);
2129 COPYBUF(bf_getwritebuffer);
2130 COPYBUF(bf_getsegcount);
2131 COPYBUF(bf_getcharbuffer);
2132 }
2133
Guido van Rossum13d52f02001-08-10 21:24:08 +00002134 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135
Tim Peters6d6c1a32001-08-02 04:15:00 +00002136 COPYSLOT(tp_dealloc);
2137 COPYSLOT(tp_print);
2138 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2139 type->tp_getattr = base->tp_getattr;
2140 type->tp_getattro = base->tp_getattro;
2141 }
2142 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2143 type->tp_setattr = base->tp_setattr;
2144 type->tp_setattro = base->tp_setattro;
2145 }
2146 /* tp_compare see tp_richcompare */
2147 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002148 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149 COPYSLOT(tp_call);
2150 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002152 if (type->tp_compare == NULL &&
2153 type->tp_richcompare == NULL &&
2154 type->tp_hash == NULL)
2155 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156 type->tp_compare = base->tp_compare;
2157 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002158 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002159 }
2160 }
2161 else {
2162 COPYSLOT(tp_compare);
2163 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002164 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2165 COPYSLOT(tp_iter);
2166 COPYSLOT(tp_iternext);
2167 }
2168 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2169 COPYSLOT(tp_descr_get);
2170 COPYSLOT(tp_descr_set);
2171 COPYSLOT(tp_dictoffset);
2172 COPYSLOT(tp_init);
2173 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002174 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002175 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002177}
2178
Guido van Rossum13d52f02001-08-10 21:24:08 +00002179staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002180staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002181
Tim Peters6d6c1a32001-08-02 04:15:00 +00002182int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002183PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002185 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186 PyTypeObject *base;
2187 int i, n;
2188
Guido van Rossumcab05802002-06-10 15:29:03 +00002189 if (type->tp_flags & Py_TPFLAGS_READY) {
2190 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002191 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002192 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002193 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002194
2195 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196
2197 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2198 base = type->tp_base;
2199 if (base == NULL && type != &PyBaseObject_Type)
2200 base = type->tp_base = &PyBaseObject_Type;
2201
Guido van Rossum0986d822002-04-08 01:38:42 +00002202 /* Initialize ob_type if NULL. This means extensions that want to be
2203 compilable separately on Windows can call PyType_Ready() instead of
2204 initializing the ob_type field of their type objects. */
2205 if (type->ob_type == NULL)
2206 type->ob_type = base->ob_type;
2207
Tim Peters6d6c1a32001-08-02 04:15:00 +00002208 /* Initialize tp_bases */
2209 bases = type->tp_bases;
2210 if (bases == NULL) {
2211 if (base == NULL)
2212 bases = PyTuple_New(0);
2213 else
2214 bases = Py_BuildValue("(O)", base);
2215 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002216 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217 type->tp_bases = bases;
2218 }
2219
2220 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002221 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002222 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002223 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224 }
2225
Guido van Rossum687ae002001-10-15 22:03:32 +00002226 /* Initialize tp_dict */
2227 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228 if (dict == NULL) {
2229 dict = PyDict_New();
2230 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002231 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002232 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002233 }
2234
Guido van Rossum687ae002001-10-15 22:03:32 +00002235 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002236 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002237 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238 if (type->tp_methods != NULL) {
2239 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002240 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241 }
2242 if (type->tp_members != NULL) {
2243 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002244 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245 }
2246 if (type->tp_getset != NULL) {
2247 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002248 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002249 }
2250
Tim Peters6d6c1a32001-08-02 04:15:00 +00002251 /* Calculate method resolution order */
2252 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002253 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002254 }
2255
Guido van Rossum13d52f02001-08-10 21:24:08 +00002256 /* Inherit special flags from dominant base */
2257 if (type->tp_base != NULL)
2258 inherit_special(type, type->tp_base);
2259
Tim Peters6d6c1a32001-08-02 04:15:00 +00002260 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002261 bases = type->tp_mro;
2262 assert(bases != NULL);
2263 assert(PyTuple_Check(bases));
2264 n = PyTuple_GET_SIZE(bases);
2265 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002266 PyObject *b = PyTuple_GET_ITEM(bases, i);
2267 if (PyType_Check(b))
2268 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002269 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002271 /* if the type dictionary doesn't contain a __doc__, set it from
2272 the tp_doc slot.
2273 */
2274 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2275 if (type->tp_doc != NULL) {
2276 PyObject *doc = PyString_FromString(type->tp_doc);
2277 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2278 Py_DECREF(doc);
2279 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002280 PyDict_SetItemString(type->tp_dict,
2281 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002282 }
2283 }
2284
Guido van Rossum13d52f02001-08-10 21:24:08 +00002285 /* Some more special stuff */
2286 base = type->tp_base;
2287 if (base != NULL) {
2288 if (type->tp_as_number == NULL)
2289 type->tp_as_number = base->tp_as_number;
2290 if (type->tp_as_sequence == NULL)
2291 type->tp_as_sequence = base->tp_as_sequence;
2292 if (type->tp_as_mapping == NULL)
2293 type->tp_as_mapping = base->tp_as_mapping;
2294 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295
Guido van Rossum1c450732001-10-08 15:18:27 +00002296 /* Link into each base class's list of subclasses */
2297 bases = type->tp_bases;
2298 n = PyTuple_GET_SIZE(bases);
2299 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002300 PyObject *b = PyTuple_GET_ITEM(bases, i);
2301 if (PyType_Check(b) &&
2302 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002303 goto error;
2304 }
2305
Guido van Rossum13d52f02001-08-10 21:24:08 +00002306 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002307 assert(type->tp_dict != NULL);
2308 type->tp_flags =
2309 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002310 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002311
2312 error:
2313 type->tp_flags &= ~Py_TPFLAGS_READYING;
2314 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315}
2316
Guido van Rossum1c450732001-10-08 15:18:27 +00002317static int
2318add_subclass(PyTypeObject *base, PyTypeObject *type)
2319{
2320 int i;
2321 PyObject *list, *ref, *new;
2322
2323 list = base->tp_subclasses;
2324 if (list == NULL) {
2325 base->tp_subclasses = list = PyList_New(0);
2326 if (list == NULL)
2327 return -1;
2328 }
2329 assert(PyList_Check(list));
2330 new = PyWeakref_NewRef((PyObject *)type, NULL);
2331 i = PyList_GET_SIZE(list);
2332 while (--i >= 0) {
2333 ref = PyList_GET_ITEM(list, i);
2334 assert(PyWeakref_CheckRef(ref));
2335 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2336 return PyList_SetItem(list, i, new);
2337 }
2338 i = PyList_Append(list, new);
2339 Py_DECREF(new);
2340 return i;
2341}
2342
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343
2344/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2345
2346/* There's a wrapper *function* for each distinct function typedef used
2347 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2348 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2349 Most tables have only one entry; the tables for binary operators have two
2350 entries, one regular and one with reversed arguments. */
2351
2352static PyObject *
2353wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2354{
2355 inquiry func = (inquiry)wrapped;
2356 int res;
2357
2358 if (!PyArg_ParseTuple(args, ""))
2359 return NULL;
2360 res = (*func)(self);
2361 if (res == -1 && PyErr_Occurred())
2362 return NULL;
2363 return PyInt_FromLong((long)res);
2364}
2365
Tim Peters6d6c1a32001-08-02 04:15:00 +00002366static PyObject *
2367wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2368{
2369 binaryfunc func = (binaryfunc)wrapped;
2370 PyObject *other;
2371
2372 if (!PyArg_ParseTuple(args, "O", &other))
2373 return NULL;
2374 return (*func)(self, other);
2375}
2376
2377static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002378wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2379{
2380 binaryfunc func = (binaryfunc)wrapped;
2381 PyObject *other;
2382
2383 if (!PyArg_ParseTuple(args, "O", &other))
2384 return NULL;
2385 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002386 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002387 Py_INCREF(Py_NotImplemented);
2388 return Py_NotImplemented;
2389 }
2390 return (*func)(self, other);
2391}
2392
2393static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002394wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2395{
2396 binaryfunc func = (binaryfunc)wrapped;
2397 PyObject *other;
2398
2399 if (!PyArg_ParseTuple(args, "O", &other))
2400 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002401 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002402 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002403 Py_INCREF(Py_NotImplemented);
2404 return Py_NotImplemented;
2405 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002406 return (*func)(other, self);
2407}
2408
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002409static PyObject *
2410wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2411{
2412 coercion func = (coercion)wrapped;
2413 PyObject *other, *res;
2414 int ok;
2415
2416 if (!PyArg_ParseTuple(args, "O", &other))
2417 return NULL;
2418 ok = func(&self, &other);
2419 if (ok < 0)
2420 return NULL;
2421 if (ok > 0) {
2422 Py_INCREF(Py_NotImplemented);
2423 return Py_NotImplemented;
2424 }
2425 res = PyTuple_New(2);
2426 if (res == NULL) {
2427 Py_DECREF(self);
2428 Py_DECREF(other);
2429 return NULL;
2430 }
2431 PyTuple_SET_ITEM(res, 0, self);
2432 PyTuple_SET_ITEM(res, 1, other);
2433 return res;
2434}
2435
Tim Peters6d6c1a32001-08-02 04:15:00 +00002436static PyObject *
2437wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2438{
2439 ternaryfunc func = (ternaryfunc)wrapped;
2440 PyObject *other;
2441 PyObject *third = Py_None;
2442
2443 /* Note: This wrapper only works for __pow__() */
2444
2445 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2446 return NULL;
2447 return (*func)(self, other, third);
2448}
2449
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002450static PyObject *
2451wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2452{
2453 ternaryfunc func = (ternaryfunc)wrapped;
2454 PyObject *other;
2455 PyObject *third = Py_None;
2456
2457 /* Note: This wrapper only works for __pow__() */
2458
2459 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2460 return NULL;
2461 return (*func)(other, self, third);
2462}
2463
Tim Peters6d6c1a32001-08-02 04:15:00 +00002464static PyObject *
2465wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2466{
2467 unaryfunc func = (unaryfunc)wrapped;
2468
2469 if (!PyArg_ParseTuple(args, ""))
2470 return NULL;
2471 return (*func)(self);
2472}
2473
Tim Peters6d6c1a32001-08-02 04:15:00 +00002474static PyObject *
2475wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2476{
2477 intargfunc func = (intargfunc)wrapped;
2478 int i;
2479
2480 if (!PyArg_ParseTuple(args, "i", &i))
2481 return NULL;
2482 return (*func)(self, i);
2483}
2484
Guido van Rossum5d815f32001-08-17 21:57:47 +00002485static int
2486getindex(PyObject *self, PyObject *arg)
2487{
2488 int i;
2489
2490 i = PyInt_AsLong(arg);
2491 if (i == -1 && PyErr_Occurred())
2492 return -1;
2493 if (i < 0) {
2494 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2495 if (sq && sq->sq_length) {
2496 int n = (*sq->sq_length)(self);
2497 if (n < 0)
2498 return -1;
2499 i += n;
2500 }
2501 }
2502 return i;
2503}
2504
2505static PyObject *
2506wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2507{
2508 intargfunc func = (intargfunc)wrapped;
2509 PyObject *arg;
2510 int i;
2511
Guido van Rossumf4593e02001-10-03 12:09:30 +00002512 if (PyTuple_GET_SIZE(args) == 1) {
2513 arg = PyTuple_GET_ITEM(args, 0);
2514 i = getindex(self, arg);
2515 if (i == -1 && PyErr_Occurred())
2516 return NULL;
2517 return (*func)(self, i);
2518 }
2519 PyArg_ParseTuple(args, "O", &arg);
2520 assert(PyErr_Occurred());
2521 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002522}
2523
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524static PyObject *
2525wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2526{
2527 intintargfunc func = (intintargfunc)wrapped;
2528 int i, j;
2529
2530 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2531 return NULL;
2532 return (*func)(self, i, j);
2533}
2534
Tim Peters6d6c1a32001-08-02 04:15:00 +00002535static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002536wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537{
2538 intobjargproc func = (intobjargproc)wrapped;
2539 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002540 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541
Guido van Rossum5d815f32001-08-17 21:57:47 +00002542 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2543 return NULL;
2544 i = getindex(self, arg);
2545 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002546 return NULL;
2547 res = (*func)(self, i, value);
2548 if (res == -1 && PyErr_Occurred())
2549 return NULL;
2550 Py_INCREF(Py_None);
2551 return Py_None;
2552}
2553
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002554static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002555wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002556{
2557 intobjargproc func = (intobjargproc)wrapped;
2558 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002559 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002560
Guido van Rossum5d815f32001-08-17 21:57:47 +00002561 if (!PyArg_ParseTuple(args, "O", &arg))
2562 return NULL;
2563 i = getindex(self, arg);
2564 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002565 return NULL;
2566 res = (*func)(self, i, NULL);
2567 if (res == -1 && PyErr_Occurred())
2568 return NULL;
2569 Py_INCREF(Py_None);
2570 return Py_None;
2571}
2572
Tim Peters6d6c1a32001-08-02 04:15:00 +00002573static PyObject *
2574wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2575{
2576 intintobjargproc func = (intintobjargproc)wrapped;
2577 int i, j, res;
2578 PyObject *value;
2579
2580 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2581 return NULL;
2582 res = (*func)(self, i, j, value);
2583 if (res == -1 && PyErr_Occurred())
2584 return NULL;
2585 Py_INCREF(Py_None);
2586 return Py_None;
2587}
2588
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002589static PyObject *
2590wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2591{
2592 intintobjargproc func = (intintobjargproc)wrapped;
2593 int i, j, res;
2594
2595 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2596 return NULL;
2597 res = (*func)(self, i, j, NULL);
2598 if (res == -1 && PyErr_Occurred())
2599 return NULL;
2600 Py_INCREF(Py_None);
2601 return Py_None;
2602}
2603
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604/* XXX objobjproc is a misnomer; should be objargpred */
2605static PyObject *
2606wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2607{
2608 objobjproc func = (objobjproc)wrapped;
2609 int res;
2610 PyObject *value;
2611
2612 if (!PyArg_ParseTuple(args, "O", &value))
2613 return NULL;
2614 res = (*func)(self, value);
2615 if (res == -1 && PyErr_Occurred())
2616 return NULL;
2617 return PyInt_FromLong((long)res);
2618}
2619
Tim Peters6d6c1a32001-08-02 04:15:00 +00002620static PyObject *
2621wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2622{
2623 objobjargproc func = (objobjargproc)wrapped;
2624 int res;
2625 PyObject *key, *value;
2626
2627 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2628 return NULL;
2629 res = (*func)(self, key, value);
2630 if (res == -1 && PyErr_Occurred())
2631 return NULL;
2632 Py_INCREF(Py_None);
2633 return Py_None;
2634}
2635
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002636static PyObject *
2637wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2638{
2639 objobjargproc func = (objobjargproc)wrapped;
2640 int res;
2641 PyObject *key;
2642
2643 if (!PyArg_ParseTuple(args, "O", &key))
2644 return NULL;
2645 res = (*func)(self, key, NULL);
2646 if (res == -1 && PyErr_Occurred())
2647 return NULL;
2648 Py_INCREF(Py_None);
2649 return Py_None;
2650}
2651
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652static PyObject *
2653wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2654{
2655 cmpfunc func = (cmpfunc)wrapped;
2656 int res;
2657 PyObject *other;
2658
2659 if (!PyArg_ParseTuple(args, "O", &other))
2660 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002661 if (other->ob_type->tp_compare != func &&
2662 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002663 PyErr_Format(
2664 PyExc_TypeError,
2665 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2666 self->ob_type->tp_name,
2667 self->ob_type->tp_name,
2668 other->ob_type->tp_name);
2669 return NULL;
2670 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671 res = (*func)(self, other);
2672 if (PyErr_Occurred())
2673 return NULL;
2674 return PyInt_FromLong((long)res);
2675}
2676
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677static PyObject *
2678wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2679{
2680 setattrofunc func = (setattrofunc)wrapped;
2681 int res;
2682 PyObject *name, *value;
2683
2684 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2685 return NULL;
2686 res = (*func)(self, name, value);
2687 if (res < 0)
2688 return NULL;
2689 Py_INCREF(Py_None);
2690 return Py_None;
2691}
2692
2693static PyObject *
2694wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2695{
2696 setattrofunc func = (setattrofunc)wrapped;
2697 int res;
2698 PyObject *name;
2699
2700 if (!PyArg_ParseTuple(args, "O", &name))
2701 return NULL;
2702 res = (*func)(self, name, NULL);
2703 if (res < 0)
2704 return NULL;
2705 Py_INCREF(Py_None);
2706 return Py_None;
2707}
2708
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709static PyObject *
2710wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2711{
2712 hashfunc func = (hashfunc)wrapped;
2713 long res;
2714
2715 if (!PyArg_ParseTuple(args, ""))
2716 return NULL;
2717 res = (*func)(self);
2718 if (res == -1 && PyErr_Occurred())
2719 return NULL;
2720 return PyInt_FromLong(res);
2721}
2722
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002724wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725{
2726 ternaryfunc func = (ternaryfunc)wrapped;
2727
Guido van Rossumc8e56452001-10-22 00:43:43 +00002728 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002729}
2730
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731static PyObject *
2732wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2733{
2734 richcmpfunc func = (richcmpfunc)wrapped;
2735 PyObject *other;
2736
2737 if (!PyArg_ParseTuple(args, "O", &other))
2738 return NULL;
2739 return (*func)(self, other, op);
2740}
2741
2742#undef RICHCMP_WRAPPER
2743#define RICHCMP_WRAPPER(NAME, OP) \
2744static PyObject * \
2745richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2746{ \
2747 return wrap_richcmpfunc(self, args, wrapped, OP); \
2748}
2749
Jack Jansen8e938b42001-08-08 15:29:49 +00002750RICHCMP_WRAPPER(lt, Py_LT)
2751RICHCMP_WRAPPER(le, Py_LE)
2752RICHCMP_WRAPPER(eq, Py_EQ)
2753RICHCMP_WRAPPER(ne, Py_NE)
2754RICHCMP_WRAPPER(gt, Py_GT)
2755RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757static PyObject *
2758wrap_next(PyObject *self, PyObject *args, void *wrapped)
2759{
2760 unaryfunc func = (unaryfunc)wrapped;
2761 PyObject *res;
2762
2763 if (!PyArg_ParseTuple(args, ""))
2764 return NULL;
2765 res = (*func)(self);
2766 if (res == NULL && !PyErr_Occurred())
2767 PyErr_SetNone(PyExc_StopIteration);
2768 return res;
2769}
2770
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771static PyObject *
2772wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2773{
2774 descrgetfunc func = (descrgetfunc)wrapped;
2775 PyObject *obj;
2776 PyObject *type = NULL;
2777
2778 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2779 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780 return (*func)(self, obj, type);
2781}
2782
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002784wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785{
2786 descrsetfunc func = (descrsetfunc)wrapped;
2787 PyObject *obj, *value;
2788 int ret;
2789
2790 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2791 return NULL;
2792 ret = (*func)(self, obj, value);
2793 if (ret < 0)
2794 return NULL;
2795 Py_INCREF(Py_None);
2796 return Py_None;
2797}
2798
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002800wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801{
2802 initproc func = (initproc)wrapped;
2803
Guido van Rossumc8e56452001-10-22 00:43:43 +00002804 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805 return NULL;
2806 Py_INCREF(Py_None);
2807 return Py_None;
2808}
2809
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002811tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812{
Barry Warsaw60f01882001-08-22 19:24:42 +00002813 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002814 PyObject *arg0, *res;
2815
2816 if (self == NULL || !PyType_Check(self))
2817 Py_FatalError("__new__() called with non-type 'self'");
2818 type = (PyTypeObject *)self;
2819 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002820 PyErr_Format(PyExc_TypeError,
2821 "%s.__new__(): not enough arguments",
2822 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002823 return NULL;
2824 }
2825 arg0 = PyTuple_GET_ITEM(args, 0);
2826 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002827 PyErr_Format(PyExc_TypeError,
2828 "%s.__new__(X): X is not a type object (%s)",
2829 type->tp_name,
2830 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002831 return NULL;
2832 }
2833 subtype = (PyTypeObject *)arg0;
2834 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002835 PyErr_Format(PyExc_TypeError,
2836 "%s.__new__(%s): %s is not a subtype of %s",
2837 type->tp_name,
2838 subtype->tp_name,
2839 subtype->tp_name,
2840 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002841 return NULL;
2842 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002843
2844 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002845 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002846 most derived base that's not a heap type is this type. */
2847 staticbase = subtype;
2848 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2849 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002850 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002851 PyErr_Format(PyExc_TypeError,
2852 "%s.__new__(%s) is not safe, use %s.__new__()",
2853 type->tp_name,
2854 subtype->tp_name,
2855 staticbase == NULL ? "?" : staticbase->tp_name);
2856 return NULL;
2857 }
2858
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002859 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2860 if (args == NULL)
2861 return NULL;
2862 res = type->tp_new(subtype, args, kwds);
2863 Py_DECREF(args);
2864 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865}
2866
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002867static struct PyMethodDef tp_new_methoddef[] = {
2868 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2869 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002870 {0}
2871};
2872
2873static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002874add_tp_new_wrapper(PyTypeObject *type)
2875{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002876 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002877
Guido van Rossum687ae002001-10-15 22:03:32 +00002878 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002879 return 0;
2880 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002881 if (func == NULL)
2882 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002883 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002884}
2885
Guido van Rossumf040ede2001-08-07 16:40:56 +00002886/* Slot wrappers that call the corresponding __foo__ slot. See comments
2887 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888
Guido van Rossumdc91b992001-08-08 22:26:22 +00002889#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002891FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002892{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002893 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002894 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002895}
2896
Guido van Rossumdc91b992001-08-08 22:26:22 +00002897#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002899FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002901 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002902 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903}
2904
Guido van Rossumdc91b992001-08-08 22:26:22 +00002905
2906#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002908FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002910 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002911 int do_other = self->ob_type != other->ob_type && \
2912 other->ob_type->tp_as_number != NULL && \
2913 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002914 if (self->ob_type->tp_as_number != NULL && \
2915 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2916 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002917 if (do_other && \
2918 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2919 r = call_maybe( \
2920 other, ROPSTR, &rcache_str, "(O)", self); \
2921 if (r != Py_NotImplemented) \
2922 return r; \
2923 Py_DECREF(r); \
2924 do_other = 0; \
2925 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002926 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002927 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002928 if (r != Py_NotImplemented || \
2929 other->ob_type == self->ob_type) \
2930 return r; \
2931 Py_DECREF(r); \
2932 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002933 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002934 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002935 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002936 } \
2937 Py_INCREF(Py_NotImplemented); \
2938 return Py_NotImplemented; \
2939}
2940
2941#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2942 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2943
2944#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2945static PyObject * \
2946FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2947{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002948 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002949 return call_method(self, OPSTR, &cache_str, \
2950 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002951}
2952
2953static int
2954slot_sq_length(PyObject *self)
2955{
Guido van Rossum2730b132001-08-28 18:22:14 +00002956 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002957 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002958 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959
2960 if (res == NULL)
2961 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002962 len = (int)PyInt_AsLong(res);
2963 Py_DECREF(res);
2964 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965}
2966
Guido van Rossumdc91b992001-08-08 22:26:22 +00002967SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2968SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002969
2970/* Super-optimized version of slot_sq_item.
2971 Other slots could do the same... */
2972static PyObject *
2973slot_sq_item(PyObject *self, int i)
2974{
2975 static PyObject *getitem_str;
2976 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2977 descrgetfunc f;
2978
2979 if (getitem_str == NULL) {
2980 getitem_str = PyString_InternFromString("__getitem__");
2981 if (getitem_str == NULL)
2982 return NULL;
2983 }
2984 func = _PyType_Lookup(self->ob_type, getitem_str);
2985 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002986 if ((f = func->ob_type->tp_descr_get) == NULL)
2987 Py_INCREF(func);
2988 else
2989 func = f(func, self, (PyObject *)(self->ob_type));
2990 ival = PyInt_FromLong(i);
2991 if (ival != NULL) {
2992 args = PyTuple_New(1);
2993 if (args != NULL) {
2994 PyTuple_SET_ITEM(args, 0, ival);
2995 retval = PyObject_Call(func, args, NULL);
2996 Py_XDECREF(args);
2997 Py_XDECREF(func);
2998 return retval;
2999 }
3000 }
3001 }
3002 else {
3003 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3004 }
3005 Py_XDECREF(args);
3006 Py_XDECREF(ival);
3007 Py_XDECREF(func);
3008 return NULL;
3009}
3010
Guido van Rossumdc91b992001-08-08 22:26:22 +00003011SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012
3013static int
3014slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3015{
3016 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003017 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018
3019 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003020 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003021 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003022 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003023 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003024 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025 if (res == NULL)
3026 return -1;
3027 Py_DECREF(res);
3028 return 0;
3029}
3030
3031static int
3032slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3033{
3034 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003035 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036
3037 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003038 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003039 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003041 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003042 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043 if (res == NULL)
3044 return -1;
3045 Py_DECREF(res);
3046 return 0;
3047}
3048
3049static int
3050slot_sq_contains(PyObject *self, PyObject *value)
3051{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003052 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003053 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054
Guido van Rossum55f20992001-10-01 17:18:22 +00003055 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003056
3057 if (func != NULL) {
3058 args = Py_BuildValue("(O)", value);
3059 if (args == NULL)
3060 res = NULL;
3061 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003062 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003063 Py_DECREF(args);
3064 }
3065 Py_DECREF(func);
3066 if (res == NULL)
3067 return -1;
3068 return PyObject_IsTrue(res);
3069 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003070 else if (PyErr_Occurred())
3071 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003072 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003073 return _PySequence_IterSearch(self, value,
3074 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003075 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003076}
3077
Guido van Rossumdc91b992001-08-08 22:26:22 +00003078SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3079SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003080
3081#define slot_mp_length slot_sq_length
3082
Guido van Rossumdc91b992001-08-08 22:26:22 +00003083SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084
3085static int
3086slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3087{
3088 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003089 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003090
3091 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003092 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003093 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003095 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003096 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097 if (res == NULL)
3098 return -1;
3099 Py_DECREF(res);
3100 return 0;
3101}
3102
Guido van Rossumdc91b992001-08-08 22:26:22 +00003103SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3104SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3105SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3106SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3107SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3108SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3109
3110staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3111
3112SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3113 nb_power, "__pow__", "__rpow__")
3114
3115static PyObject *
3116slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3117{
Guido van Rossum2730b132001-08-28 18:22:14 +00003118 static PyObject *pow_str;
3119
Guido van Rossumdc91b992001-08-08 22:26:22 +00003120 if (modulus == Py_None)
3121 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003122 /* Three-arg power doesn't use __rpow__. But ternary_op
3123 can call this when the second argument's type uses
3124 slot_nb_power, so check before calling self.__pow__. */
3125 if (self->ob_type->tp_as_number != NULL &&
3126 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3127 return call_method(self, "__pow__", &pow_str,
3128 "(OO)", other, modulus);
3129 }
3130 Py_INCREF(Py_NotImplemented);
3131 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003132}
3133
3134SLOT0(slot_nb_negative, "__neg__")
3135SLOT0(slot_nb_positive, "__pos__")
3136SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003137
3138static int
3139slot_nb_nonzero(PyObject *self)
3140{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003141 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003142 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003143
Guido van Rossum55f20992001-10-01 17:18:22 +00003144 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003145 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003146 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003147 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003148 func = lookup_maybe(self, "__len__", &len_str);
3149 if (func == NULL) {
3150 if (PyErr_Occurred())
3151 return -1;
3152 else
3153 return 1;
3154 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003155 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003156 res = PyObject_CallObject(func, NULL);
3157 Py_DECREF(func);
3158 if (res == NULL)
3159 return -1;
3160 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003161}
3162
Guido van Rossumdc91b992001-08-08 22:26:22 +00003163SLOT0(slot_nb_invert, "__invert__")
3164SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3165SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3166SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3167SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3168SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003169
3170static int
3171slot_nb_coerce(PyObject **a, PyObject **b)
3172{
3173 static PyObject *coerce_str;
3174 PyObject *self = *a, *other = *b;
3175
3176 if (self->ob_type->tp_as_number != NULL &&
3177 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3178 PyObject *r;
3179 r = call_maybe(
3180 self, "__coerce__", &coerce_str, "(O)", other);
3181 if (r == NULL)
3182 return -1;
3183 if (r == Py_NotImplemented) {
3184 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003185 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003186 else {
3187 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3188 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003189 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003190 Py_DECREF(r);
3191 return -1;
3192 }
3193 *a = PyTuple_GET_ITEM(r, 0);
3194 Py_INCREF(*a);
3195 *b = PyTuple_GET_ITEM(r, 1);
3196 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003197 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003198 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003199 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003200 }
3201 if (other->ob_type->tp_as_number != NULL &&
3202 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3203 PyObject *r;
3204 r = call_maybe(
3205 other, "__coerce__", &coerce_str, "(O)", self);
3206 if (r == NULL)
3207 return -1;
3208 if (r == Py_NotImplemented) {
3209 Py_DECREF(r);
3210 return 1;
3211 }
3212 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3213 PyErr_SetString(PyExc_TypeError,
3214 "__coerce__ didn't return a 2-tuple");
3215 Py_DECREF(r);
3216 return -1;
3217 }
3218 *a = PyTuple_GET_ITEM(r, 1);
3219 Py_INCREF(*a);
3220 *b = PyTuple_GET_ITEM(r, 0);
3221 Py_INCREF(*b);
3222 Py_DECREF(r);
3223 return 0;
3224 }
3225 return 1;
3226}
3227
Guido van Rossumdc91b992001-08-08 22:26:22 +00003228SLOT0(slot_nb_int, "__int__")
3229SLOT0(slot_nb_long, "__long__")
3230SLOT0(slot_nb_float, "__float__")
3231SLOT0(slot_nb_oct, "__oct__")
3232SLOT0(slot_nb_hex, "__hex__")
3233SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3234SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3235SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3236SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3237SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3238SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3239SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3240SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3241SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3242SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3243SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3244SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3245 "__floordiv__", "__rfloordiv__")
3246SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3247SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3248SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003249
3250static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003251half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003252{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003253 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003254 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003255 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003256
Guido van Rossum60718732001-08-28 17:47:51 +00003257 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003258 if (func == NULL) {
3259 PyErr_Clear();
3260 }
3261 else {
3262 args = Py_BuildValue("(O)", other);
3263 if (args == NULL)
3264 res = NULL;
3265 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003266 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003267 Py_DECREF(args);
3268 }
3269 if (res != Py_NotImplemented) {
3270 if (res == NULL)
3271 return -2;
3272 c = PyInt_AsLong(res);
3273 Py_DECREF(res);
3274 if (c == -1 && PyErr_Occurred())
3275 return -2;
3276 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3277 }
3278 Py_DECREF(res);
3279 }
3280 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281}
3282
Guido van Rossumab3b0342001-09-18 20:38:53 +00003283/* This slot is published for the benefit of try_3way_compare in object.c */
3284int
3285_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003286{
3287 int c;
3288
Guido van Rossumab3b0342001-09-18 20:38:53 +00003289 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003290 c = half_compare(self, other);
3291 if (c <= 1)
3292 return c;
3293 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003294 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003295 c = half_compare(other, self);
3296 if (c < -1)
3297 return -2;
3298 if (c <= 1)
3299 return -c;
3300 }
3301 return (void *)self < (void *)other ? -1 :
3302 (void *)self > (void *)other ? 1 : 0;
3303}
3304
3305static PyObject *
3306slot_tp_repr(PyObject *self)
3307{
3308 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003309 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003310
Guido van Rossum60718732001-08-28 17:47:51 +00003311 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003312 if (func != NULL) {
3313 res = PyEval_CallObject(func, NULL);
3314 Py_DECREF(func);
3315 return res;
3316 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003317 PyErr_Clear();
3318 return PyString_FromFormat("<%s object at %p>",
3319 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003320}
3321
3322static PyObject *
3323slot_tp_str(PyObject *self)
3324{
3325 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003326 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003327
Guido van Rossum60718732001-08-28 17:47:51 +00003328 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003329 if (func != NULL) {
3330 res = PyEval_CallObject(func, NULL);
3331 Py_DECREF(func);
3332 return res;
3333 }
3334 else {
3335 PyErr_Clear();
3336 return slot_tp_repr(self);
3337 }
3338}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339
3340static long
3341slot_tp_hash(PyObject *self)
3342{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003343 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003344 static PyObject *hash_str, *eq_str, *cmp_str;
3345
Tim Peters6d6c1a32001-08-02 04:15:00 +00003346 long h;
3347
Guido van Rossum60718732001-08-28 17:47:51 +00003348 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003349
3350 if (func != NULL) {
3351 res = PyEval_CallObject(func, NULL);
3352 Py_DECREF(func);
3353 if (res == NULL)
3354 return -1;
3355 h = PyInt_AsLong(res);
3356 }
3357 else {
3358 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003359 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003360 if (func == NULL) {
3361 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003362 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003363 }
3364 if (func != NULL) {
3365 Py_DECREF(func);
3366 PyErr_SetString(PyExc_TypeError, "unhashable type");
3367 return -1;
3368 }
3369 PyErr_Clear();
3370 h = _Py_HashPointer((void *)self);
3371 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372 if (h == -1 && !PyErr_Occurred())
3373 h = -2;
3374 return h;
3375}
3376
3377static PyObject *
3378slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3379{
Guido van Rossum60718732001-08-28 17:47:51 +00003380 static PyObject *call_str;
3381 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382 PyObject *res;
3383
3384 if (meth == NULL)
3385 return NULL;
3386 res = PyObject_Call(meth, args, kwds);
3387 Py_DECREF(meth);
3388 return res;
3389}
3390
Guido van Rossum14a6f832001-10-17 13:59:09 +00003391/* There are two slot dispatch functions for tp_getattro.
3392
3393 - slot_tp_getattro() is used when __getattribute__ is overridden
3394 but no __getattr__ hook is present;
3395
3396 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3397
Guido van Rossumc334df52002-04-04 23:44:47 +00003398 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3399 detects the absence of __getattr__ and then installs the simpler slot if
3400 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003401
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402static PyObject *
3403slot_tp_getattro(PyObject *self, PyObject *name)
3404{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003405 static PyObject *getattribute_str = NULL;
3406 return call_method(self, "__getattribute__", &getattribute_str,
3407 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003408}
3409
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003410static PyObject *
3411slot_tp_getattr_hook(PyObject *self, PyObject *name)
3412{
3413 PyTypeObject *tp = self->ob_type;
3414 PyObject *getattr, *getattribute, *res;
3415 static PyObject *getattribute_str = NULL;
3416 static PyObject *getattr_str = NULL;
3417
3418 if (getattr_str == NULL) {
3419 getattr_str = PyString_InternFromString("__getattr__");
3420 if (getattr_str == NULL)
3421 return NULL;
3422 }
3423 if (getattribute_str == NULL) {
3424 getattribute_str =
3425 PyString_InternFromString("__getattribute__");
3426 if (getattribute_str == NULL)
3427 return NULL;
3428 }
3429 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003430 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003431 /* No __getattr__ hook: use a simpler dispatcher */
3432 tp->tp_getattro = slot_tp_getattro;
3433 return slot_tp_getattro(self, name);
3434 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003435 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003436 if (getattribute == NULL ||
3437 (getattribute->ob_type == &PyWrapperDescr_Type &&
3438 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3439 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003440 res = PyObject_GenericGetAttr(self, name);
3441 else
3442 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003443 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003444 PyErr_Clear();
3445 res = PyObject_CallFunction(getattr, "OO", self, name);
3446 }
3447 return res;
3448}
3449
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450static int
3451slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3452{
3453 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003454 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455
3456 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003457 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003458 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003460 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003461 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003462 if (res == NULL)
3463 return -1;
3464 Py_DECREF(res);
3465 return 0;
3466}
3467
3468/* Map rich comparison operators to their __xx__ namesakes */
3469static char *name_op[] = {
3470 "__lt__",
3471 "__le__",
3472 "__eq__",
3473 "__ne__",
3474 "__gt__",
3475 "__ge__",
3476};
3477
3478static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003479half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003481 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003482 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483
Guido van Rossum60718732001-08-28 17:47:51 +00003484 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003485 if (func == NULL) {
3486 PyErr_Clear();
3487 Py_INCREF(Py_NotImplemented);
3488 return Py_NotImplemented;
3489 }
3490 args = Py_BuildValue("(O)", other);
3491 if (args == NULL)
3492 res = NULL;
3493 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003494 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003495 Py_DECREF(args);
3496 }
3497 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498 return res;
3499}
3500
Guido van Rossumb8f63662001-08-15 23:57:02 +00003501/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3502static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3503
3504static PyObject *
3505slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3506{
3507 PyObject *res;
3508
3509 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3510 res = half_richcompare(self, other, op);
3511 if (res != Py_NotImplemented)
3512 return res;
3513 Py_DECREF(res);
3514 }
3515 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3516 res = half_richcompare(other, self, swapped_op[op]);
3517 if (res != Py_NotImplemented) {
3518 return res;
3519 }
3520 Py_DECREF(res);
3521 }
3522 Py_INCREF(Py_NotImplemented);
3523 return Py_NotImplemented;
3524}
3525
3526static PyObject *
3527slot_tp_iter(PyObject *self)
3528{
3529 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003530 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003531
Guido van Rossum60718732001-08-28 17:47:51 +00003532 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003533 if (func != NULL) {
3534 res = PyObject_CallObject(func, NULL);
3535 Py_DECREF(func);
3536 return res;
3537 }
3538 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003539 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003540 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003541 PyErr_SetString(PyExc_TypeError,
3542 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003543 return NULL;
3544 }
3545 Py_DECREF(func);
3546 return PySeqIter_New(self);
3547}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548
3549static PyObject *
3550slot_tp_iternext(PyObject *self)
3551{
Guido van Rossum2730b132001-08-28 18:22:14 +00003552 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003553 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003554}
3555
Guido van Rossum1a493502001-08-17 16:47:50 +00003556static PyObject *
3557slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3558{
3559 PyTypeObject *tp = self->ob_type;
3560 PyObject *get;
3561 static PyObject *get_str = NULL;
3562
3563 if (get_str == NULL) {
3564 get_str = PyString_InternFromString("__get__");
3565 if (get_str == NULL)
3566 return NULL;
3567 }
3568 get = _PyType_Lookup(tp, get_str);
3569 if (get == NULL) {
3570 /* Avoid further slowdowns */
3571 if (tp->tp_descr_get == slot_tp_descr_get)
3572 tp->tp_descr_get = NULL;
3573 Py_INCREF(self);
3574 return self;
3575 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003576 if (obj == NULL)
3577 obj = Py_None;
3578 if (type == NULL)
3579 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003580 return PyObject_CallFunction(get, "OOO", self, obj, type);
3581}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582
3583static int
3584slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3585{
Guido van Rossum2c252392001-08-24 10:13:31 +00003586 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003587 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003588
3589 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003590 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003591 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003592 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003593 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003594 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003595 if (res == NULL)
3596 return -1;
3597 Py_DECREF(res);
3598 return 0;
3599}
3600
3601static int
3602slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3603{
Guido van Rossum60718732001-08-28 17:47:51 +00003604 static PyObject *init_str;
3605 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606 PyObject *res;
3607
3608 if (meth == NULL)
3609 return -1;
3610 res = PyObject_Call(meth, args, kwds);
3611 Py_DECREF(meth);
3612 if (res == NULL)
3613 return -1;
3614 Py_DECREF(res);
3615 return 0;
3616}
3617
3618static PyObject *
3619slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3620{
3621 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3622 PyObject *newargs, *x;
3623 int i, n;
3624
3625 if (func == NULL)
3626 return NULL;
3627 assert(PyTuple_Check(args));
3628 n = PyTuple_GET_SIZE(args);
3629 newargs = PyTuple_New(n+1);
3630 if (newargs == NULL)
3631 return NULL;
3632 Py_INCREF(type);
3633 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3634 for (i = 0; i < n; i++) {
3635 x = PyTuple_GET_ITEM(args, i);
3636 Py_INCREF(x);
3637 PyTuple_SET_ITEM(newargs, i+1, x);
3638 }
3639 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003640 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641 Py_DECREF(func);
3642 return x;
3643}
3644
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003645
3646/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3647 functions. The offsets here are relative to the 'etype' structure, which
3648 incorporates the additional structures used for numbers, sequences and
3649 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3650 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003651 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3652 terminated with an all-zero entry. (This table is further initialized and
3653 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003654
Guido van Rossum6d204072001-10-21 00:44:31 +00003655typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003656
3657#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003658#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003659#undef ETSLOT
3660#undef SQSLOT
3661#undef MPSLOT
3662#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003663#undef UNSLOT
3664#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003665#undef BINSLOT
3666#undef RBINSLOT
3667
Guido van Rossum6d204072001-10-21 00:44:31 +00003668#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3669 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003670#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3671 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3672 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003673#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3674 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3675#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3676 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3677#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3678 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3679#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3680 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3681#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3682 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3683 "x." NAME "() <==> " DOC)
3684#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3685 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3686 "x." NAME "(y) <==> x" DOC "y")
3687#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3688 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3689 "x." NAME "(y) <==> x" DOC "y")
3690#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3691 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3692 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003693
3694static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003695 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3696 "x.__len__() <==> len(x)"),
3697 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3698 "x.__add__(y) <==> x+y"),
3699 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3700 "x.__mul__(n) <==> x*n"),
3701 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3702 "x.__rmul__(n) <==> n*x"),
3703 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3704 "x.__getitem__(y) <==> x[y]"),
3705 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3706 "x.__getslice__(i, j) <==> x[i:j]"),
3707 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3708 "x.__setitem__(i, y) <==> x[i]=y"),
3709 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3710 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003711 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003712 wrap_intintobjargproc,
3713 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3714 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3715 "x.__delslice__(i, j) <==> del x[i:j]"),
3716 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3717 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003718 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003719 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003720 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003721 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003722
Guido van Rossum6d204072001-10-21 00:44:31 +00003723 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3724 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003725 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003726 wrap_binaryfunc,
3727 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003728 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003729 wrap_objobjargproc,
3730 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003731 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003732 wrap_delitem,
3733 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003734
Guido van Rossum6d204072001-10-21 00:44:31 +00003735 BINSLOT("__add__", nb_add, slot_nb_add,
3736 "+"),
3737 RBINSLOT("__radd__", nb_add, slot_nb_add,
3738 "+"),
3739 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3740 "-"),
3741 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3742 "-"),
3743 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3744 "*"),
3745 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3746 "*"),
3747 BINSLOT("__div__", nb_divide, slot_nb_divide,
3748 "/"),
3749 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3750 "/"),
3751 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3752 "%"),
3753 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3754 "%"),
3755 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3756 "divmod(x, y)"),
3757 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3758 "divmod(y, x)"),
3759 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3760 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3761 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3762 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3763 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3764 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3765 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3766 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003767 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003768 "x != 0"),
3769 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3770 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3771 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3772 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3773 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3774 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3775 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3776 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3777 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3778 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3779 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3780 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3781 "x.__coerce__(y) <==> coerce(x, y)"),
3782 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3783 "int(x)"),
3784 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3785 "long(x)"),
3786 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3787 "float(x)"),
3788 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3789 "oct(x)"),
3790 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3791 "hex(x)"),
3792 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3793 wrap_binaryfunc, "+"),
3794 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3795 wrap_binaryfunc, "-"),
3796 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3797 wrap_binaryfunc, "*"),
3798 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3799 wrap_binaryfunc, "/"),
3800 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3801 wrap_binaryfunc, "%"),
3802 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3803 wrap_ternaryfunc, "**"),
3804 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3805 wrap_binaryfunc, "<<"),
3806 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3807 wrap_binaryfunc, ">>"),
3808 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3809 wrap_binaryfunc, "&"),
3810 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3811 wrap_binaryfunc, "^"),
3812 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3813 wrap_binaryfunc, "|"),
3814 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3815 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3816 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3817 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3818 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3819 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3820 IBSLOT("__itruediv__", nb_inplace_true_divide,
3821 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003822
Guido van Rossum6d204072001-10-21 00:44:31 +00003823 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3824 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003825 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003826 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3827 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003828 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003829 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3830 "x.__cmp__(y) <==> cmp(x,y)"),
3831 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3832 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003833 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3834 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003835 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003836 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3837 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3838 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3839 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3840 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3841 "x.__setattr__('name', value) <==> x.name = value"),
3842 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3843 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3844 "x.__delattr__('name') <==> del x.name"),
3845 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3846 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3847 "x.__lt__(y) <==> x<y"),
3848 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3849 "x.__le__(y) <==> x<=y"),
3850 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3851 "x.__eq__(y) <==> x==y"),
3852 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3853 "x.__ne__(y) <==> x!=y"),
3854 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3855 "x.__gt__(y) <==> x>y"),
3856 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3857 "x.__ge__(y) <==> x>=y"),
3858 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3859 "x.__iter__() <==> iter(x)"),
3860 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3861 "x.next() -> the next value, or raise StopIteration"),
3862 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3863 "descr.__get__(obj[, type]) -> value"),
3864 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3865 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003866 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003867 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003868 "see x.__class__.__doc__ for signature",
3869 PyWrapperFlag_KEYWORDS),
3870 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003871 {NULL}
3872};
3873
Guido van Rossumc334df52002-04-04 23:44:47 +00003874/* Given a type pointer and an offset gotten from a slotdef entry, return a
3875 pointer to the actual slot. This is not quite the same as simply adding
3876 the offset to the type pointer, since it takes care to indirect through the
3877 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3878 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003879static void **
3880slotptr(PyTypeObject *type, int offset)
3881{
3882 char *ptr;
3883
Guido van Rossum09638c12002-06-13 19:17:46 +00003884 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003885 assert(offset >= 0);
3886 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00003887 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003888 ptr = (void *)type->tp_as_sequence;
3889 offset -= offsetof(etype, as_sequence);
3890 }
Guido van Rossum09638c12002-06-13 19:17:46 +00003891 else if (offset >= offsetof(etype, as_mapping)) {
3892 ptr = (void *)type->tp_as_mapping;
3893 offset -= offsetof(etype, as_mapping);
3894 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003895 else if (offset >= offsetof(etype, as_number)) {
3896 ptr = (void *)type->tp_as_number;
3897 offset -= offsetof(etype, as_number);
3898 }
3899 else {
3900 ptr = (void *)type;
3901 }
3902 if (ptr != NULL)
3903 ptr += offset;
3904 return (void **)ptr;
3905}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003906
Guido van Rossumc334df52002-04-04 23:44:47 +00003907/* Length of array of slotdef pointers used to store slots with the
3908 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3909 the same __name__, for any __name__. Since that's a static property, it is
3910 appropriate to declare fixed-size arrays for this. */
3911#define MAX_EQUIV 10
3912
3913/* Return a slot pointer for a given name, but ONLY if the attribute has
3914 exactly one slot function. The name must be an interned string. */
3915static void **
3916resolve_slotdups(PyTypeObject *type, PyObject *name)
3917{
3918 /* XXX Maybe this could be optimized more -- but is it worth it? */
3919
3920 /* pname and ptrs act as a little cache */
3921 static PyObject *pname;
3922 static slotdef *ptrs[MAX_EQUIV];
3923 slotdef *p, **pp;
3924 void **res, **ptr;
3925
3926 if (pname != name) {
3927 /* Collect all slotdefs that match name into ptrs. */
3928 pname = name;
3929 pp = ptrs;
3930 for (p = slotdefs; p->name_strobj; p++) {
3931 if (p->name_strobj == name)
3932 *pp++ = p;
3933 }
3934 *pp = NULL;
3935 }
3936
3937 /* Look in all matching slots of the type; if exactly one of these has
3938 a filled-in slot, return its value. Otherwise return NULL. */
3939 res = NULL;
3940 for (pp = ptrs; *pp; pp++) {
3941 ptr = slotptr(type, (*pp)->offset);
3942 if (ptr == NULL || *ptr == NULL)
3943 continue;
3944 if (res != NULL)
3945 return NULL;
3946 res = ptr;
3947 }
3948 return res;
3949}
3950
3951/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3952 does some incredibly complex thinking and then sticks something into the
3953 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3954 interests, and then stores a generic wrapper or a specific function into
3955 the slot.) Return a pointer to the next slotdef with a different offset,
3956 because that's convenient for fixup_slot_dispatchers(). */
3957static slotdef *
3958update_one_slot(PyTypeObject *type, slotdef *p)
3959{
3960 PyObject *descr;
3961 PyWrapperDescrObject *d;
3962 void *generic = NULL, *specific = NULL;
3963 int use_generic = 0;
3964 int offset = p->offset;
3965 void **ptr = slotptr(type, offset);
3966
3967 if (ptr == NULL) {
3968 do {
3969 ++p;
3970 } while (p->offset == offset);
3971 return p;
3972 }
3973 do {
3974 descr = _PyType_Lookup(type, p->name_strobj);
3975 if (descr == NULL)
3976 continue;
3977 if (descr->ob_type == &PyWrapperDescr_Type) {
3978 void **tptr = resolve_slotdups(type, p->name_strobj);
3979 if (tptr == NULL || tptr == ptr)
3980 generic = p->function;
3981 d = (PyWrapperDescrObject *)descr;
3982 if (d->d_base->wrapper == p->wrapper &&
3983 PyType_IsSubtype(type, d->d_type))
3984 {
3985 if (specific == NULL ||
3986 specific == d->d_wrapped)
3987 specific = d->d_wrapped;
3988 else
3989 use_generic = 1;
3990 }
3991 }
3992 else {
3993 use_generic = 1;
3994 generic = p->function;
3995 }
3996 } while ((++p)->offset == offset);
3997 if (specific && !use_generic)
3998 *ptr = specific;
3999 else
4000 *ptr = generic;
4001 return p;
4002}
4003
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004004staticforward int recurse_down_subclasses(PyTypeObject *type,
4005 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004006
Guido van Rossumc334df52002-04-04 23:44:47 +00004007/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4008 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004009static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004010update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004011{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004012 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004013
Guido van Rossumc334df52002-04-04 23:44:47 +00004014 for (pp = pp0; *pp; pp++)
4015 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004016 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004017}
4018
Guido van Rossumc334df52002-04-04 23:44:47 +00004019/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4020 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004021static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004022recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004023{
4024 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004025 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004026 int i, n;
4027
4028 subclasses = type->tp_subclasses;
4029 if (subclasses == NULL)
4030 return 0;
4031 assert(PyList_Check(subclasses));
4032 n = PyList_GET_SIZE(subclasses);
4033 for (i = 0; i < n; i++) {
4034 ref = PyList_GET_ITEM(subclasses, i);
4035 assert(PyWeakref_CheckRef(ref));
4036 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004037 assert(subclass != NULL);
4038 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004039 continue;
4040 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004041 /* Avoid recursing down into unaffected classes */
4042 dict = subclass->tp_dict;
4043 if (dict != NULL && PyDict_Check(dict) &&
4044 PyDict_GetItem(dict, name) != NULL)
4045 continue;
4046 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004047 return -1;
4048 }
4049 return 0;
4050}
4051
Guido van Rossumc334df52002-04-04 23:44:47 +00004052/* Comparison function for qsort() to compare slotdefs by their offset, and
4053 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004054static int
4055slotdef_cmp(const void *aa, const void *bb)
4056{
4057 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4058 int c = a->offset - b->offset;
4059 if (c != 0)
4060 return c;
4061 else
4062 return a - b;
4063}
4064
Guido van Rossumc334df52002-04-04 23:44:47 +00004065/* Initialize the slotdefs table by adding interned string objects for the
4066 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004067static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004068init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004069{
4070 slotdef *p;
4071 static int initialized = 0;
4072
4073 if (initialized)
4074 return;
4075 for (p = slotdefs; p->name; p++) {
4076 p->name_strobj = PyString_InternFromString(p->name);
4077 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004078 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004079 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004080 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4081 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004082 initialized = 1;
4083}
4084
Guido van Rossumc334df52002-04-04 23:44:47 +00004085/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004086static int
4087update_slot(PyTypeObject *type, PyObject *name)
4088{
Guido van Rossumc334df52002-04-04 23:44:47 +00004089 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004090 slotdef *p;
4091 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004092 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004093
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004094 init_slotdefs();
4095 pp = ptrs;
4096 for (p = slotdefs; p->name; p++) {
4097 /* XXX assume name is interned! */
4098 if (p->name_strobj == name)
4099 *pp++ = p;
4100 }
4101 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004102 for (pp = ptrs; *pp; pp++) {
4103 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004104 offset = p->offset;
4105 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004106 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004107 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004108 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004109 if (ptrs[0] == NULL)
4110 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004111 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004112}
4113
Guido van Rossumc334df52002-04-04 23:44:47 +00004114/* Store the proper functions in the slot dispatches at class (type)
4115 definition time, based upon which operations the class overrides in its
4116 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004118fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004119{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004120 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004122 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004123 for (p = slotdefs; p->name; )
4124 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004125}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004126
Guido van Rossum6d204072001-10-21 00:44:31 +00004127/* This function is called by PyType_Ready() to populate the type's
4128 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004129 function slot (like tp_repr) that's defined in the type, one or more
4130 corresponding descriptors are added in the type's tp_dict dictionary
4131 under the appropriate name (like __repr__). Some function slots
4132 cause more than one descriptor to be added (for example, the nb_add
4133 slot adds both __add__ and __radd__ descriptors) and some function
4134 slots compete for the same descriptor (for example both sq_item and
4135 mp_subscript generate a __getitem__ descriptor).
4136
4137 In the latter case, the first slotdef entry encoutered wins. Since
4138 slotdef entries are sorted by the offset of the slot in the etype
4139 struct, this gives us some control over disambiguating between
4140 competing slots: the members of struct etype are listed from most
4141 general to least general, so the most general slot is preferred. In
4142 particular, because as_mapping comes before as_sequence, for a type
4143 that defines both mp_subscript and sq_item, mp_subscript wins.
4144
4145 This only adds new descriptors and doesn't overwrite entries in
4146 tp_dict that were previously defined. The descriptors contain a
4147 reference to the C function they must call, so that it's safe if they
4148 are copied into a subtype's __dict__ and the subtype has a different
4149 C function in its slot -- calling the method defined by the
4150 descriptor will call the C function that was used to create it,
4151 rather than the C function present in the slot when it is called.
4152 (This is important because a subtype may have a C function in the
4153 slot that calls the method from the dictionary, and we want to avoid
4154 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004155
4156static int
4157add_operators(PyTypeObject *type)
4158{
4159 PyObject *dict = type->tp_dict;
4160 slotdef *p;
4161 PyObject *descr;
4162 void **ptr;
4163
4164 init_slotdefs();
4165 for (p = slotdefs; p->name; p++) {
4166 if (p->wrapper == NULL)
4167 continue;
4168 ptr = slotptr(type, p->offset);
4169 if (!ptr || !*ptr)
4170 continue;
4171 if (PyDict_GetItem(dict, p->name_strobj))
4172 continue;
4173 descr = PyDescr_NewWrapper(type, p, *ptr);
4174 if (descr == NULL)
4175 return -1;
4176 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4177 return -1;
4178 Py_DECREF(descr);
4179 }
4180 if (type->tp_new != NULL) {
4181 if (add_tp_new_wrapper(type) < 0)
4182 return -1;
4183 }
4184 return 0;
4185}
4186
Guido van Rossum705f0f52001-08-24 16:47:00 +00004187
4188/* Cooperative 'super' */
4189
4190typedef struct {
4191 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004192 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004193 PyObject *obj;
4194} superobject;
4195
Guido van Rossum6f799372001-09-20 20:46:19 +00004196static PyMemberDef super_members[] = {
4197 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4198 "the class invoking super()"},
4199 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4200 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004201 {0}
4202};
4203
Guido van Rossum705f0f52001-08-24 16:47:00 +00004204static void
4205super_dealloc(PyObject *self)
4206{
4207 superobject *su = (superobject *)self;
4208
Guido van Rossum048eb752001-10-02 21:24:57 +00004209 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004210 Py_XDECREF(su->obj);
4211 Py_XDECREF(su->type);
4212 self->ob_type->tp_free(self);
4213}
4214
4215static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004216super_repr(PyObject *self)
4217{
4218 superobject *su = (superobject *)self;
4219
4220 if (su->obj)
4221 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004222 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004223 su->type ? su->type->tp_name : "NULL",
4224 su->obj->ob_type->tp_name);
4225 else
4226 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004227 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004228 su->type ? su->type->tp_name : "NULL");
4229}
4230
4231static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004232super_getattro(PyObject *self, PyObject *name)
4233{
4234 superobject *su = (superobject *)self;
4235
4236 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004237 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004238 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004239 descrgetfunc f;
4240 int i, n;
4241
Guido van Rossum155db9a2002-04-02 17:53:47 +00004242 starttype = su->obj->ob_type;
4243 mro = starttype->tp_mro;
4244
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004245 if (mro == NULL)
4246 n = 0;
4247 else {
4248 assert(PyTuple_Check(mro));
4249 n = PyTuple_GET_SIZE(mro);
4250 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004251 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004252 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004253 break;
4254 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004255 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004256 starttype = (PyTypeObject *)(su->obj);
4257 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004258 if (mro == NULL)
4259 n = 0;
4260 else {
4261 assert(PyTuple_Check(mro));
4262 n = PyTuple_GET_SIZE(mro);
4263 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004264 for (i = 0; i < n; i++) {
4265 if ((PyObject *)(su->type) ==
4266 PyTuple_GET_ITEM(mro, i))
4267 break;
4268 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004269 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004270 i++;
4271 res = NULL;
4272 for (; i < n; i++) {
4273 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004274 if (PyType_Check(tmp))
4275 dict = ((PyTypeObject *)tmp)->tp_dict;
4276 else if (PyClass_Check(tmp))
4277 dict = ((PyClassObject *)tmp)->cl_dict;
4278 else
4279 continue;
4280 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004281 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004282 Py_INCREF(res);
4283 f = res->ob_type->tp_descr_get;
4284 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004285 tmp = f(res, su->obj,
4286 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004287 Py_DECREF(res);
4288 res = tmp;
4289 }
4290 return res;
4291 }
4292 }
4293 }
4294 return PyObject_GenericGetAttr(self, name);
4295}
4296
Guido van Rossum5b443c62001-12-03 15:38:28 +00004297static int
4298supercheck(PyTypeObject *type, PyObject *obj)
4299{
4300 if (!PyType_IsSubtype(obj->ob_type, type) &&
4301 !(PyType_Check(obj) &&
4302 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4303 PyErr_SetString(PyExc_TypeError,
4304 "super(type, obj): "
4305 "obj must be an instance or subtype of type");
4306 return -1;
4307 }
4308 else
4309 return 0;
4310}
4311
Guido van Rossum705f0f52001-08-24 16:47:00 +00004312static PyObject *
4313super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4314{
4315 superobject *su = (superobject *)self;
4316 superobject *new;
4317
4318 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4319 /* Not binding to an object, or already bound */
4320 Py_INCREF(self);
4321 return self;
4322 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004323 if (su->ob_type != &PySuper_Type)
4324 /* If su is an instance of a subclass of super,
4325 call its type */
4326 return PyObject_CallFunction((PyObject *)su->ob_type,
4327 "OO", su->type, obj);
4328 else {
4329 /* Inline the common case */
4330 if (supercheck(su->type, obj) < 0)
4331 return NULL;
4332 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4333 NULL, NULL);
4334 if (new == NULL)
4335 return NULL;
4336 Py_INCREF(su->type);
4337 Py_INCREF(obj);
4338 new->type = su->type;
4339 new->obj = obj;
4340 return (PyObject *)new;
4341 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004342}
4343
4344static int
4345super_init(PyObject *self, PyObject *args, PyObject *kwds)
4346{
4347 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004348 PyTypeObject *type;
4349 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004350
4351 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4352 return -1;
4353 if (obj == Py_None)
4354 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004355 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004356 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004357 Py_INCREF(type);
4358 Py_XINCREF(obj);
4359 su->type = type;
4360 su->obj = obj;
4361 return 0;
4362}
4363
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004364PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00004365"super(type) -> unbound super object\n"
4366"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004367"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004368"Typical use to call a cooperative superclass method:\n"
4369"class C(B):\n"
4370" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004371" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004372
Guido van Rossum048eb752001-10-02 21:24:57 +00004373static int
4374super_traverse(PyObject *self, visitproc visit, void *arg)
4375{
4376 superobject *su = (superobject *)self;
4377 int err;
4378
4379#define VISIT(SLOT) \
4380 if (SLOT) { \
4381 err = visit((PyObject *)(SLOT), arg); \
4382 if (err) \
4383 return err; \
4384 }
4385
4386 VISIT(su->obj);
4387 VISIT(su->type);
4388
4389#undef VISIT
4390
4391 return 0;
4392}
4393
Guido van Rossum705f0f52001-08-24 16:47:00 +00004394PyTypeObject PySuper_Type = {
4395 PyObject_HEAD_INIT(&PyType_Type)
4396 0, /* ob_size */
4397 "super", /* tp_name */
4398 sizeof(superobject), /* tp_basicsize */
4399 0, /* tp_itemsize */
4400 /* methods */
4401 super_dealloc, /* tp_dealloc */
4402 0, /* tp_print */
4403 0, /* tp_getattr */
4404 0, /* tp_setattr */
4405 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004406 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004407 0, /* tp_as_number */
4408 0, /* tp_as_sequence */
4409 0, /* tp_as_mapping */
4410 0, /* tp_hash */
4411 0, /* tp_call */
4412 0, /* tp_str */
4413 super_getattro, /* tp_getattro */
4414 0, /* tp_setattro */
4415 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004416 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4417 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004418 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004419 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004420 0, /* tp_clear */
4421 0, /* tp_richcompare */
4422 0, /* tp_weaklistoffset */
4423 0, /* tp_iter */
4424 0, /* tp_iternext */
4425 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004426 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004427 0, /* tp_getset */
4428 0, /* tp_base */
4429 0, /* tp_dict */
4430 super_descr_get, /* tp_descr_get */
4431 0, /* tp_descr_set */
4432 0, /* tp_dictoffset */
4433 super_init, /* tp_init */
4434 PyType_GenericAlloc, /* tp_alloc */
4435 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004436 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004437};