blob: 07032f4e24e35823edf3ae5438ef56b4a20f0df8 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum6f799372001-09-20 20:46:19 +00007static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000047 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000048 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
Guido van Rossum3926a632001-09-25 16:25:58 +000056static int
57type_set_module(PyTypeObject *type, PyObject *value, void *context)
58{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000059 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000060 strrchr(type->tp_name, '.')) {
61 PyErr_Format(PyExc_TypeError,
62 "can't set %s.__module__", type->tp_name);
63 return -1;
64 }
65 if (!value) {
66 PyErr_Format(PyExc_TypeError,
67 "can't delete %s.__module__", type->tp_name);
68 return -1;
69 }
70 return PyDict_SetItemString(type->tp_dict, "__module__", value);
71}
72
Tim Peters6d6c1a32001-08-02 04:15:00 +000073static PyObject *
74type_dict(PyTypeObject *type, void *context)
75{
76 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 Py_INCREF(Py_None);
78 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000080 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000081}
82
Neil Schemenauerf23473f2001-10-21 22:28:58 +000083static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000084 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +000085 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000086 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 {0}
88};
89
Martin v. Löwis0163d6d2001-06-09 07:34:05 +000090static int
91type_compare(PyObject *v, PyObject *w)
92{
93 /* This is called with type objects only. So we
94 can just compare the addresses. */
95 Py_uintptr_t vv = (Py_uintptr_t)v;
96 Py_uintptr_t ww = (Py_uintptr_t)w;
97 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
98}
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000103 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000104 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000105
106 mod = type_module(type, NULL);
107 if (mod == NULL)
108 PyErr_Clear();
109 else if (!PyString_Check(mod)) {
110 Py_DECREF(mod);
111 mod = NULL;
112 }
113 name = type_name(type, NULL);
114 if (name == NULL)
115 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000117 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
118 kind = "class";
119 else
120 kind = "type";
121
Barry Warsaw7ce36942001-08-24 18:34:26 +0000122 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000123 rtn = PyString_FromFormat("<%s '%s.%s'>",
124 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000125 PyString_AS_STRING(mod),
126 PyString_AS_STRING(name));
127 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000128 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000129 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000130
Guido van Rossumc3542212001-08-16 09:18:56 +0000131 Py_XDECREF(mod);
132 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134}
135
Tim Peters6d6c1a32001-08-02 04:15:00 +0000136static PyObject *
137type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
138{
139 PyObject *obj;
140
141 if (type->tp_new == NULL) {
142 PyErr_Format(PyExc_TypeError,
143 "cannot create '%.100s' instances",
144 type->tp_name);
145 return NULL;
146 }
147
Tim Peters3f996e72001-09-13 19:18:27 +0000148 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000149 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000150 /* Ugly exception: when the call was type(something),
151 don't call tp_init on the result. */
152 if (type == &PyType_Type &&
153 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
154 (kwds == NULL ||
155 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
156 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000157 type = obj->ob_type;
158 if (type->tp_init != NULL &&
159 type->tp_init(obj, args, kwds) < 0) {
160 Py_DECREF(obj);
161 obj = NULL;
162 }
163 }
164 return obj;
165}
166
167PyObject *
168PyType_GenericAlloc(PyTypeObject *type, int nitems)
169{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000170 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000171 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000172
173 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000174 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000175 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000176 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000177
Neil Schemenauerc806c882001-08-29 23:54:54 +0000178 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000180
Neil Schemenauerc806c882001-08-29 23:54:54 +0000181 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000182
Tim Peters6d6c1a32001-08-02 04:15:00 +0000183 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
184 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000185
Tim Peters6d6c1a32001-08-02 04:15:00 +0000186 if (type->tp_itemsize == 0)
187 PyObject_INIT(obj, type);
188 else
189 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000190
Tim Peters6d6c1a32001-08-02 04:15:00 +0000191 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000192 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000193 return obj;
194}
195
196PyObject *
197PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
198{
199 return type->tp_alloc(type, 0);
200}
201
Guido van Rossum9475a232001-10-05 20:51:39 +0000202/* Helpers for subtyping */
203
204static int
205subtype_traverse(PyObject *self, visitproc visit, void *arg)
206{
207 PyTypeObject *type, *base;
208 traverseproc f;
209 int err;
210
211 /* Find the nearest base with a different tp_traverse */
212 type = self->ob_type;
213 base = type->tp_base;
214 while ((f = base->tp_traverse) == subtype_traverse) {
215 base = base->tp_base;
216 assert(base);
217 }
218
219 if (type->tp_dictoffset != base->tp_dictoffset) {
220 PyObject **dictptr = _PyObject_GetDictPtr(self);
221 if (dictptr && *dictptr) {
222 err = visit(*dictptr, arg);
223 if (err)
224 return err;
225 }
226 }
227
228 if (f)
229 return f(self, visit, arg);
230 return 0;
231}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000232
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000233staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
234
235static int
236call_finalizer(PyObject *self)
237{
238 static PyObject *del_str = NULL;
239 PyObject *del, *res;
240 PyObject *error_type, *error_value, *error_traceback;
241
242 /* Temporarily resurrect the object. */
243#ifdef Py_TRACE_REFS
244#ifndef Py_REF_DEBUG
245# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
246#endif
247 /* much too complicated if Py_TRACE_REFS defined */
248 _Py_NewReference((PyObject *)self);
249#ifdef COUNT_ALLOCS
250 /* compensate for boost in _Py_NewReference; note that
251 * _Py_RefTotal was also boosted; we'll knock that down later.
252 */
253 self->ob_type->tp_allocs--;
254#endif
255#else /* !Py_TRACE_REFS */
256 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
257 Py_INCREF(self);
258#endif /* !Py_TRACE_REFS */
259
260 /* Save the current exception, if any. */
261 PyErr_Fetch(&error_type, &error_value, &error_traceback);
262
263 /* Execute __del__ method, if any. */
264 del = lookup_maybe(self, "__del__", &del_str);
265 if (del != NULL) {
266 res = PyEval_CallObject(del, NULL);
267 if (res == NULL)
268 PyErr_WriteUnraisable(del);
269 else
270 Py_DECREF(res);
271 Py_DECREF(del);
272 }
273
274 /* Restore the saved exception. */
275 PyErr_Restore(error_type, error_value, error_traceback);
276
277 /* Undo the temporary resurrection; can't use DECREF here, it would
278 * cause a recursive call.
279 */
280#ifdef Py_REF_DEBUG
281 /* _Py_RefTotal was boosted either by _Py_NewReference or
282 * Py_INCREF above.
283 */
284 _Py_RefTotal--;
285#endif
286 if (--self->ob_refcnt > 0) {
287#ifdef COUNT_ALLOCS
288 self->ob_type->tp_frees--;
289#endif
290 _PyObject_GC_TRACK(self);
291 return -1; /* __del__ added a reference; don't delete now */
292 }
293#ifdef Py_TRACE_REFS
294 _Py_ForgetReference((PyObject *)self);
295#ifdef COUNT_ALLOCS
296 /* compensate for increment in _Py_ForgetReference */
297 self->ob_type->tp_frees--;
298#endif
299#endif
300
301 return 0;
302}
303
Tim Peters6d6c1a32001-08-02 04:15:00 +0000304static void
305subtype_dealloc(PyObject *self)
306{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000307 PyTypeObject *type, *base;
308 destructor f;
309
310 /* This exists so we can DECREF self->ob_type */
311
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000312 if (call_finalizer(self) < 0)
313 return;
314
Tim Peters6d6c1a32001-08-02 04:15:00 +0000315 /* Find the nearest base with a different tp_dealloc */
316 type = self->ob_type;
317 base = type->tp_base;
318 while ((f = base->tp_dealloc) == subtype_dealloc) {
319 base = base->tp_base;
320 assert(base);
321 }
322
323 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000324 if (type->tp_dictoffset && !base->tp_dictoffset) {
325 PyObject **dictptr = _PyObject_GetDictPtr(self);
326 if (dictptr != NULL) {
327 PyObject *dict = *dictptr;
328 if (dict != NULL) {
329 Py_DECREF(dict);
330 *dictptr = NULL;
331 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332 }
333 }
334
Guido van Rossum9676b222001-08-17 20:32:36 +0000335 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000336 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000337 PyObject_ClearWeakRefs(self);
338
Tim Peters6d6c1a32001-08-02 04:15:00 +0000339 /* Finalize GC if the base doesn't do GC and we do */
340 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000341 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000342
343 /* Call the base tp_dealloc() */
344 assert(f);
345 f(self);
346
347 /* Can't reference self beyond this point */
348 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
349 Py_DECREF(type);
350 }
351}
352
Tim Peters6d6c1a32001-08-02 04:15:00 +0000353staticforward PyTypeObject *solid_base(PyTypeObject *type);
354
355typedef struct {
356 PyTypeObject type;
357 PyNumberMethods as_number;
358 PySequenceMethods as_sequence;
359 PyMappingMethods as_mapping;
360 PyBufferProcs as_buffer;
361 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000362 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000363} etype;
364
365/* type test with subclassing support */
366
367int
368PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
369{
370 PyObject *mro;
371
Guido van Rossum9478d072001-09-07 18:52:13 +0000372 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
373 return b == a || b == &PyBaseObject_Type;
374
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375 mro = a->tp_mro;
376 if (mro != NULL) {
377 /* Deal with multiple inheritance without recursion
378 by walking the MRO tuple */
379 int i, n;
380 assert(PyTuple_Check(mro));
381 n = PyTuple_GET_SIZE(mro);
382 for (i = 0; i < n; i++) {
383 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
384 return 1;
385 }
386 return 0;
387 }
388 else {
389 /* a is not completely initilized yet; follow tp_base */
390 do {
391 if (a == b)
392 return 1;
393 a = a->tp_base;
394 } while (a != NULL);
395 return b == &PyBaseObject_Type;
396 }
397}
398
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000399/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000400 without looking in the instance dictionary
401 (so we can't use PyObject_GetAttr) but still binding
402 it to the instance. The arguments are the object,
403 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000404 static variable used to cache the interned Python string.
405
406 Two variants:
407
408 - lookup_maybe() returns NULL without raising an exception
409 when the _PyType_Lookup() call fails;
410
411 - lookup_method() always raises an exception upon errors.
412*/
Guido van Rossum60718732001-08-28 17:47:51 +0000413
414static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000415lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000416{
417 PyObject *res;
418
419 if (*attrobj == NULL) {
420 *attrobj = PyString_InternFromString(attrstr);
421 if (*attrobj == NULL)
422 return NULL;
423 }
424 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000425 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000426 descrgetfunc f;
427 if ((f = res->ob_type->tp_descr_get) == NULL)
428 Py_INCREF(res);
429 else
430 res = f(res, self, (PyObject *)(self->ob_type));
431 }
432 return res;
433}
434
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000435static PyObject *
436lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
437{
438 PyObject *res = lookup_maybe(self, attrstr, attrobj);
439 if (res == NULL && !PyErr_Occurred())
440 PyErr_SetObject(PyExc_AttributeError, *attrobj);
441 return res;
442}
443
Guido van Rossum2730b132001-08-28 18:22:14 +0000444/* A variation of PyObject_CallMethod that uses lookup_method()
445 instead of PyObject_GetAttrString(). This uses the same convention
446 as lookup_method to cache the interned name string object. */
447
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000448static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000449call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
450{
451 va_list va;
452 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000453 va_start(va, format);
454
Guido van Rossumda21c012001-10-03 00:50:18 +0000455 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000456 if (func == NULL) {
457 va_end(va);
458 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000459 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000460 return NULL;
461 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000462
463 if (format && *format)
464 args = Py_VaBuildValue(format, va);
465 else
466 args = PyTuple_New(0);
467
468 va_end(va);
469
470 if (args == NULL)
471 return NULL;
472
473 assert(PyTuple_Check(args));
474 retval = PyObject_Call(func, args, NULL);
475
476 Py_DECREF(args);
477 Py_DECREF(func);
478
479 return retval;
480}
481
482/* Clone of call_method() that returns NotImplemented when the lookup fails. */
483
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000484static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000485call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
486{
487 va_list va;
488 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000489 va_start(va, format);
490
Guido van Rossumda21c012001-10-03 00:50:18 +0000491 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000492 if (func == NULL) {
493 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000494 if (!PyErr_Occurred()) {
495 Py_INCREF(Py_NotImplemented);
496 return Py_NotImplemented;
497 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000498 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000499 }
500
501 if (format && *format)
502 args = Py_VaBuildValue(format, va);
503 else
504 args = PyTuple_New(0);
505
506 va_end(va);
507
Guido van Rossum717ce002001-09-14 16:58:08 +0000508 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000509 return NULL;
510
Guido van Rossum717ce002001-09-14 16:58:08 +0000511 assert(PyTuple_Check(args));
512 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000513
514 Py_DECREF(args);
515 Py_DECREF(func);
516
517 return retval;
518}
519
Tim Peters6d6c1a32001-08-02 04:15:00 +0000520/* Method resolution order algorithm from "Putting Metaclasses to Work"
521 by Forman and Danforth (Addison-Wesley 1999). */
522
523static int
524conservative_merge(PyObject *left, PyObject *right)
525{
526 int left_size;
527 int right_size;
528 int i, j, r, ok;
529 PyObject *temp, *rr;
530
531 assert(PyList_Check(left));
532 assert(PyList_Check(right));
533
534 again:
535 left_size = PyList_GET_SIZE(left);
536 right_size = PyList_GET_SIZE(right);
537 for (i = 0; i < left_size; i++) {
538 for (j = 0; j < right_size; j++) {
539 if (PyList_GET_ITEM(left, i) ==
540 PyList_GET_ITEM(right, j)) {
541 /* found a merge point */
542 temp = PyList_New(0);
543 if (temp == NULL)
544 return -1;
545 for (r = 0; r < j; r++) {
546 rr = PyList_GET_ITEM(right, r);
547 ok = PySequence_Contains(left, rr);
548 if (ok < 0) {
549 Py_DECREF(temp);
550 return -1;
551 }
552 if (!ok) {
553 ok = PyList_Append(temp, rr);
554 if (ok < 0) {
555 Py_DECREF(temp);
556 return -1;
557 }
558 }
559 }
560 ok = PyList_SetSlice(left, i, i, temp);
561 Py_DECREF(temp);
562 if (ok < 0)
563 return -1;
564 ok = PyList_SetSlice(right, 0, j+1, NULL);
565 if (ok < 0)
566 return -1;
567 goto again;
568 }
569 }
570 }
571 return PyList_SetSlice(left, left_size, left_size, right);
572}
573
574static int
575serious_order_disagreements(PyObject *left, PyObject *right)
576{
577 return 0; /* XXX later -- for now, we cheat: "don't do that" */
578}
579
Tim Petersa91e9642001-11-14 23:32:33 +0000580static int
581fill_classic_mro(PyObject *mro, PyObject *cls)
582{
583 PyObject *bases, *base;
584 int i, n;
585
586 assert(PyList_Check(mro));
587 assert(PyClass_Check(cls));
588 i = PySequence_Contains(mro, cls);
589 if (i < 0)
590 return -1;
591 if (!i) {
592 if (PyList_Append(mro, cls) < 0)
593 return -1;
594 }
595 bases = ((PyClassObject *)cls)->cl_bases;
596 assert(bases && PyTuple_Check(bases));
597 n = PyTuple_GET_SIZE(bases);
598 for (i = 0; i < n; i++) {
599 base = PyTuple_GET_ITEM(bases, i);
600 if (fill_classic_mro(mro, base) < 0)
601 return -1;
602 }
603 return 0;
604}
605
606static PyObject *
607classic_mro(PyObject *cls)
608{
609 PyObject *mro;
610
611 assert(PyClass_Check(cls));
612 mro = PyList_New(0);
613 if (mro != NULL) {
614 if (fill_classic_mro(mro, cls) == 0)
615 return mro;
616 Py_DECREF(mro);
617 }
618 return NULL;
619}
620
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621static PyObject *
622mro_implementation(PyTypeObject *type)
623{
624 int i, n, ok;
625 PyObject *bases, *result;
626
627 bases = type->tp_bases;
628 n = PyTuple_GET_SIZE(bases);
629 result = Py_BuildValue("[O]", (PyObject *)type);
630 if (result == NULL)
631 return NULL;
632 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000633 PyObject *base = PyTuple_GET_ITEM(bases, i);
634 PyObject *parentMRO;
635 if (PyType_Check(base))
636 parentMRO = PySequence_List(
637 ((PyTypeObject*)base)->tp_mro);
638 else
639 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 if (parentMRO == NULL) {
641 Py_DECREF(result);
642 return NULL;
643 }
644 if (serious_order_disagreements(result, parentMRO)) {
645 Py_DECREF(result);
646 return NULL;
647 }
648 ok = conservative_merge(result, parentMRO);
649 Py_DECREF(parentMRO);
650 if (ok < 0) {
651 Py_DECREF(result);
652 return NULL;
653 }
654 }
655 return result;
656}
657
658static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000659mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660{
661 PyTypeObject *type = (PyTypeObject *)self;
662
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 return mro_implementation(type);
664}
665
666static int
667mro_internal(PyTypeObject *type)
668{
669 PyObject *mro, *result, *tuple;
670
671 if (type->ob_type == &PyType_Type) {
672 result = mro_implementation(type);
673 }
674 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000675 static PyObject *mro_str;
676 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677 if (mro == NULL)
678 return -1;
679 result = PyObject_CallObject(mro, NULL);
680 Py_DECREF(mro);
681 }
682 if (result == NULL)
683 return -1;
684 tuple = PySequence_Tuple(result);
685 Py_DECREF(result);
686 type->tp_mro = tuple;
687 return 0;
688}
689
690
691/* Calculate the best base amongst multiple base classes.
692 This is the first one that's on the path to the "solid base". */
693
694static PyTypeObject *
695best_base(PyObject *bases)
696{
697 int i, n;
698 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000699 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700
701 assert(PyTuple_Check(bases));
702 n = PyTuple_GET_SIZE(bases);
703 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000704 base = NULL;
705 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000707 base_proto = PyTuple_GET_ITEM(bases, i);
708 if (PyClass_Check(base_proto))
709 continue;
710 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711 PyErr_SetString(
712 PyExc_TypeError,
713 "bases must be types");
714 return NULL;
715 }
Tim Petersa91e9642001-11-14 23:32:33 +0000716 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000718 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719 return NULL;
720 }
721 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000722 if (winner == NULL) {
723 winner = candidate;
724 base = base_i;
725 }
726 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727 ;
728 else if (PyType_IsSubtype(candidate, winner)) {
729 winner = candidate;
730 base = base_i;
731 }
732 else {
733 PyErr_SetString(
734 PyExc_TypeError,
735 "multiple bases have "
736 "instance lay-out conflict");
737 return NULL;
738 }
739 }
740 assert(base != NULL);
741 return base;
742}
743
744static int
745extra_ivars(PyTypeObject *type, PyTypeObject *base)
746{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000747 size_t t_size = type->tp_basicsize;
748 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000749
Guido van Rossum9676b222001-08-17 20:32:36 +0000750 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000751 if (type->tp_itemsize || base->tp_itemsize) {
752 /* If itemsize is involved, stricter rules */
753 return t_size != b_size ||
754 type->tp_itemsize != base->tp_itemsize;
755 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000756 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
757 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
758 t_size -= sizeof(PyObject *);
759 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
760 type->tp_dictoffset + sizeof(PyObject *) == t_size)
761 t_size -= sizeof(PyObject *);
762
763 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000764}
765
766static PyTypeObject *
767solid_base(PyTypeObject *type)
768{
769 PyTypeObject *base;
770
771 if (type->tp_base)
772 base = solid_base(type->tp_base);
773 else
774 base = &PyBaseObject_Type;
775 if (extra_ivars(type, base))
776 return type;
777 else
778 return base;
779}
780
781staticforward void object_dealloc(PyObject *);
782staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000783staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000784staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000785
786static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000787subtype_dict(PyObject *obj, void *context)
788{
789 PyObject **dictptr = _PyObject_GetDictPtr(obj);
790 PyObject *dict;
791
792 if (dictptr == NULL) {
793 PyErr_SetString(PyExc_AttributeError,
794 "This object has no __dict__");
795 return NULL;
796 }
797 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000798 if (dict == NULL)
799 *dictptr = dict = PyDict_New();
800 Py_XINCREF(dict);
801 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000802}
803
Guido van Rossum6661be32001-10-26 04:26:12 +0000804static int
805subtype_setdict(PyObject *obj, PyObject *value, void *context)
806{
807 PyObject **dictptr = _PyObject_GetDictPtr(obj);
808 PyObject *dict;
809
810 if (dictptr == NULL) {
811 PyErr_SetString(PyExc_AttributeError,
812 "This object has no __dict__");
813 return -1;
814 }
815 if (value == NULL || !PyDict_Check(value)) {
816 PyErr_SetString(PyExc_TypeError,
817 "__dict__ must be set to a dictionary");
818 return -1;
819 }
820 dict = *dictptr;
821 Py_INCREF(value);
822 *dictptr = value;
823 Py_XDECREF(dict);
824 return 0;
825}
826
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000827static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000828 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000829 {0},
830};
831
832static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000833type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
834{
835 PyObject *name, *bases, *dict;
836 static char *kwlist[] = {"name", "bases", "dict", 0};
837 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000838 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000840 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000841 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842
Tim Peters3abca122001-10-27 19:37:48 +0000843 assert(args != NULL && PyTuple_Check(args));
844 assert(kwds == NULL || PyDict_Check(kwds));
845
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000846 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000847 {
848 const int nargs = PyTuple_GET_SIZE(args);
849 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
850
851 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
852 PyObject *x = PyTuple_GET_ITEM(args, 0);
853 Py_INCREF(x->ob_type);
854 return (PyObject *) x->ob_type;
855 }
856
857 /* SF bug 475327 -- if that didn't trigger, we need 3
858 arguments. but PyArg_ParseTupleAndKeywords below may give
859 a msg saying type() needs exactly 3. */
860 if (nargs + nkwds != 3) {
861 PyErr_SetString(PyExc_TypeError,
862 "type() takes 1 or 3 arguments");
863 return NULL;
864 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000865 }
866
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000867 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
869 &name,
870 &PyTuple_Type, &bases,
871 &PyDict_Type, &dict))
872 return NULL;
873
874 /* Determine the proper metatype to deal with this,
875 and check for metatype conflicts while we're at it.
876 Note that if some other metatype wins to contract,
877 it's possible that its instances are not types. */
878 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000879 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000880 for (i = 0; i < nbases; i++) {
881 tmp = PyTuple_GET_ITEM(bases, i);
882 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000883 if (tmptype == &PyClass_Type)
884 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000885 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000887 if (PyType_IsSubtype(tmptype, winner)) {
888 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889 continue;
890 }
891 PyErr_SetString(PyExc_TypeError,
892 "metatype conflict among bases");
893 return NULL;
894 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000895 if (winner != metatype) {
896 if (winner->tp_new != type_new) /* Pass it to the winner */
897 return winner->tp_new(winner, args, kwds);
898 metatype = winner;
899 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900
901 /* Adjust for empty tuple bases */
902 if (nbases == 0) {
903 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
904 if (bases == NULL)
905 return NULL;
906 nbases = 1;
907 }
908 else
909 Py_INCREF(bases);
910
911 /* XXX From here until type is allocated, "return NULL" leaks bases! */
912
913 /* Calculate best base, and check that all bases are type objects */
914 base = best_base(bases);
915 if (base == NULL)
916 return NULL;
917 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
918 PyErr_Format(PyExc_TypeError,
919 "type '%.100s' is not an acceptable base type",
920 base->tp_name);
921 return NULL;
922 }
923
Tim Peters6d6c1a32001-08-02 04:15:00 +0000924 /* Check for a __slots__ sequence variable in dict, and count it */
925 slots = PyDict_GetItemString(dict, "__slots__");
926 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000927 add_dict = 0;
928 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000929 if (slots != NULL) {
930 /* Make it into a tuple */
931 if (PyString_Check(slots))
932 slots = Py_BuildValue("(O)", slots);
933 else
934 slots = PySequence_Tuple(slots);
935 if (slots == NULL)
936 return NULL;
937 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000938 if (nslots > 0 && base->tp_itemsize != 0) {
939 PyErr_Format(PyExc_TypeError,
940 "nonempty __slots__ "
941 "not supported for subtype of '%s'",
942 base->tp_name);
943 return NULL;
944 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000945 for (i = 0; i < nslots; i++) {
946 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
947 PyErr_SetString(PyExc_TypeError,
948 "__slots__ must be a sequence of strings");
949 Py_DECREF(slots);
950 return NULL;
951 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000952 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953 }
954 }
955 if (slots == NULL && base->tp_dictoffset == 0 &&
956 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000957 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000958 add_dict++;
959 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000960 if (slots == NULL && base->tp_weaklistoffset == 0 &&
961 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000962 nslots++;
963 add_weak++;
964 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965
966 /* XXX From here until type is safely allocated,
967 "return NULL" may leak slots! */
968
969 /* Allocate the type object */
970 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
971 if (type == NULL)
972 return NULL;
973
974 /* Keep name and slots alive in the extended type object */
975 et = (etype *)type;
976 Py_INCREF(name);
977 et->name = name;
978 et->slots = slots;
979
Guido van Rossumdc91b992001-08-08 22:26:22 +0000980 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
982 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000983 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
984 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000985
986 /* It's a new-style number unless it specifically inherits any
987 old-style numeric behavior */
988 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
989 (base->tp_as_number == NULL))
990 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
991
992 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 type->tp_as_number = &et->as_number;
994 type->tp_as_sequence = &et->as_sequence;
995 type->tp_as_mapping = &et->as_mapping;
996 type->tp_as_buffer = &et->as_buffer;
997 type->tp_name = PyString_AS_STRING(name);
998
999 /* Set tp_base and tp_bases */
1000 type->tp_bases = bases;
1001 Py_INCREF(base);
1002 type->tp_base = base;
1003
Guido van Rossum687ae002001-10-15 22:03:32 +00001004 /* Initialize tp_dict from passed-in dict */
1005 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006 if (dict == NULL) {
1007 Py_DECREF(type);
1008 return NULL;
1009 }
1010
Guido van Rossumc3542212001-08-16 09:18:56 +00001011 /* Set __module__ in the dict */
1012 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1013 tmp = PyEval_GetGlobals();
1014 if (tmp != NULL) {
1015 tmp = PyDict_GetItemString(tmp, "__name__");
1016 if (tmp != NULL) {
1017 if (PyDict_SetItemString(dict, "__module__",
1018 tmp) < 0)
1019 return NULL;
1020 }
1021 }
1022 }
1023
Tim Peters2f93e282001-10-04 05:27:00 +00001024 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1025 and is a string (tp_doc is a char* -- can't copy a general object
1026 into it).
1027 XXX What if it's a Unicode string? Don't know -- this ignores it.
1028 */
1029 {
1030 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1031 if (doc != NULL && PyString_Check(doc)) {
1032 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001033 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001034 if (type->tp_doc == NULL) {
1035 Py_DECREF(type);
1036 return NULL;
1037 }
1038 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1039 }
1040 }
1041
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042 /* Special-case __new__: if it's a plain function,
1043 make it a static function */
1044 tmp = PyDict_GetItemString(dict, "__new__");
1045 if (tmp != NULL && PyFunction_Check(tmp)) {
1046 tmp = PyStaticMethod_New(tmp);
1047 if (tmp == NULL) {
1048 Py_DECREF(type);
1049 return NULL;
1050 }
1051 PyDict_SetItemString(dict, "__new__", tmp);
1052 Py_DECREF(tmp);
1053 }
1054
1055 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1056 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001057 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001058 if (slots != NULL) {
1059 for (i = 0; i < nslots; i++, mp++) {
1060 mp->name = PyString_AS_STRING(
1061 PyTuple_GET_ITEM(slots, i));
1062 mp->type = T_OBJECT;
1063 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001064 if (base->tp_weaklistoffset == 0 &&
1065 strcmp(mp->name, "__weakref__") == 0)
1066 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001067 slotoffset += sizeof(PyObject *);
1068 }
1069 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001070 else {
1071 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001072 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001073 type->tp_dictoffset =
1074 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001075 else
1076 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001077 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001078 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001079 }
1080 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001081 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001082 type->tp_weaklistoffset = slotoffset;
1083 mp->name = "__weakref__";
1084 mp->type = T_OBJECT;
1085 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001086 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001087 mp++;
1088 slotoffset += sizeof(PyObject *);
1089 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001090 }
1091 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001092 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001093 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094
1095 /* Special case some slots */
1096 if (type->tp_dictoffset != 0 || nslots > 0) {
1097 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1098 type->tp_getattro = PyObject_GenericGetAttr;
1099 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1100 type->tp_setattro = PyObject_GenericSetAttr;
1101 }
1102 type->tp_dealloc = subtype_dealloc;
1103
Guido van Rossum9475a232001-10-05 20:51:39 +00001104 /* Enable GC unless there are really no instance variables possible */
1105 if (!(type->tp_basicsize == sizeof(PyObject) &&
1106 type->tp_itemsize == 0))
1107 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1108
Tim Peters6d6c1a32001-08-02 04:15:00 +00001109 /* Always override allocation strategy to use regular heap */
1110 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001111 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1112 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001113 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001114 type->tp_clear = base->tp_clear;
1115 }
1116 else
1117 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118
1119 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001120 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121 Py_DECREF(type);
1122 return NULL;
1123 }
1124
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001125 /* Put the proper slots in place */
1126 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001127
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 return (PyObject *)type;
1129}
1130
1131/* Internal API to look for a name through the MRO.
1132 This returns a borrowed reference, and doesn't set an exception! */
1133PyObject *
1134_PyType_Lookup(PyTypeObject *type, PyObject *name)
1135{
1136 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001137 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138
Guido van Rossum687ae002001-10-15 22:03:32 +00001139 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 mro = type->tp_mro;
1141 assert(PyTuple_Check(mro));
1142 n = PyTuple_GET_SIZE(mro);
1143 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001144 base = PyTuple_GET_ITEM(mro, i);
1145 if (PyClass_Check(base))
1146 dict = ((PyClassObject *)base)->cl_dict;
1147 else {
1148 assert(PyType_Check(base));
1149 dict = ((PyTypeObject *)base)->tp_dict;
1150 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 assert(dict && PyDict_Check(dict));
1152 res = PyDict_GetItem(dict, name);
1153 if (res != NULL)
1154 return res;
1155 }
1156 return NULL;
1157}
1158
1159/* This is similar to PyObject_GenericGetAttr(),
1160 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1161static PyObject *
1162type_getattro(PyTypeObject *type, PyObject *name)
1163{
1164 PyTypeObject *metatype = type->ob_type;
1165 PyObject *descr, *res;
1166 descrgetfunc f;
1167
1168 /* Initialize this type (we'll assume the metatype is initialized) */
1169 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001170 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171 return NULL;
1172 }
1173
1174 /* Get a descriptor from the metatype */
1175 descr = _PyType_Lookup(metatype, name);
1176 f = NULL;
1177 if (descr != NULL) {
1178 f = descr->ob_type->tp_descr_get;
1179 if (f != NULL && PyDescr_IsData(descr))
1180 return f(descr,
1181 (PyObject *)type, (PyObject *)metatype);
1182 }
1183
Guido van Rossum687ae002001-10-15 22:03:32 +00001184 /* Look in tp_dict of this type and its bases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001185 res = _PyType_Lookup(type, name);
1186 if (res != NULL) {
1187 f = res->ob_type->tp_descr_get;
1188 if (f != NULL)
1189 return f(res, (PyObject *)NULL, (PyObject *)type);
1190 Py_INCREF(res);
1191 return res;
1192 }
1193
1194 /* Use the descriptor from the metatype */
1195 if (f != NULL) {
1196 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1197 return res;
1198 }
1199 if (descr != NULL) {
1200 Py_INCREF(descr);
1201 return descr;
1202 }
1203
1204 /* Give up */
1205 PyErr_Format(PyExc_AttributeError,
1206 "type object '%.50s' has no attribute '%.400s'",
1207 type->tp_name, PyString_AS_STRING(name));
1208 return NULL;
1209}
1210
1211static int
1212type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1213{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001214 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1215 PyErr_Format(
1216 PyExc_TypeError,
1217 "can't set attributes of built-in/extension type '%s'",
1218 type->tp_name);
1219 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001220 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001221 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1222 return -1;
1223 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224}
1225
1226static void
1227type_dealloc(PyTypeObject *type)
1228{
1229 etype *et;
1230
1231 /* Assert this is a heap-allocated type object */
1232 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001233 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001234 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001235 et = (etype *)type;
1236 Py_XDECREF(type->tp_base);
1237 Py_XDECREF(type->tp_dict);
1238 Py_XDECREF(type->tp_bases);
1239 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001240 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001241 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 Py_XDECREF(et->name);
1243 Py_XDECREF(et->slots);
1244 type->ob_type->tp_free((PyObject *)type);
1245}
1246
Guido van Rossum1c450732001-10-08 15:18:27 +00001247static PyObject *
1248type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1249{
1250 PyObject *list, *raw, *ref;
1251 int i, n;
1252
1253 list = PyList_New(0);
1254 if (list == NULL)
1255 return NULL;
1256 raw = type->tp_subclasses;
1257 if (raw == NULL)
1258 return list;
1259 assert(PyList_Check(raw));
1260 n = PyList_GET_SIZE(raw);
1261 for (i = 0; i < n; i++) {
1262 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001263 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001264 ref = PyWeakref_GET_OBJECT(ref);
1265 if (ref != Py_None) {
1266 if (PyList_Append(list, ref) < 0) {
1267 Py_DECREF(list);
1268 return NULL;
1269 }
1270 }
1271 }
1272 return list;
1273}
1274
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001276 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001278 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1279 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001280 {0}
1281};
1282
1283static char type_doc[] =
1284"type(object) -> the object's type\n"
1285"type(name, bases, dict) -> a new type";
1286
Guido van Rossum048eb752001-10-02 21:24:57 +00001287static int
1288type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1289{
1290 etype *et;
1291 int err;
1292
1293 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1294 return 0;
1295
1296 et = (etype *)type;
1297
1298#define VISIT(SLOT) \
1299 if (SLOT) { \
1300 err = visit((PyObject *)(SLOT), arg); \
1301 if (err) \
1302 return err; \
1303 }
1304
1305 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001306 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001307 VISIT(type->tp_mro);
1308 VISIT(type->tp_bases);
1309 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001310 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001311 VISIT(et->slots);
1312
1313#undef VISIT
1314
1315 return 0;
1316}
1317
1318static int
1319type_clear(PyTypeObject *type)
1320{
1321 etype *et;
1322 PyObject *tmp;
1323
1324 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1325 return 0;
1326
1327 et = (etype *)type;
1328
1329#define CLEAR(SLOT) \
1330 if (SLOT) { \
1331 tmp = (PyObject *)(SLOT); \
1332 SLOT = NULL; \
1333 Py_DECREF(tmp); \
1334 }
1335
1336 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001337 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001338 CLEAR(type->tp_mro);
1339 CLEAR(type->tp_bases);
1340 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001341 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001342 CLEAR(et->slots);
1343
Tim Peters2f93e282001-10-04 05:27:00 +00001344 if (type->tp_doc != NULL) {
1345 PyObject_FREE(type->tp_doc);
1346 type->tp_doc = NULL;
1347 }
1348
Guido van Rossum048eb752001-10-02 21:24:57 +00001349#undef CLEAR
1350
1351 return 0;
1352}
1353
1354static int
1355type_is_gc(PyTypeObject *type)
1356{
1357 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1358}
1359
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001360PyTypeObject PyType_Type = {
1361 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362 0, /* ob_size */
1363 "type", /* tp_name */
1364 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001365 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 (destructor)type_dealloc, /* tp_dealloc */
1367 0, /* tp_print */
1368 0, /* tp_getattr */
1369 0, /* tp_setattr */
1370 type_compare, /* tp_compare */
1371 (reprfunc)type_repr, /* tp_repr */
1372 0, /* tp_as_number */
1373 0, /* tp_as_sequence */
1374 0, /* tp_as_mapping */
1375 (hashfunc)_Py_HashPointer, /* tp_hash */
1376 (ternaryfunc)type_call, /* tp_call */
1377 0, /* tp_str */
1378 (getattrofunc)type_getattro, /* tp_getattro */
1379 (setattrofunc)type_setattro, /* tp_setattro */
1380 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001381 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1382 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001384 (traverseproc)type_traverse, /* tp_traverse */
1385 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001387 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 0, /* tp_iter */
1389 0, /* tp_iternext */
1390 type_methods, /* tp_methods */
1391 type_members, /* tp_members */
1392 type_getsets, /* tp_getset */
1393 0, /* tp_base */
1394 0, /* tp_dict */
1395 0, /* tp_descr_get */
1396 0, /* tp_descr_set */
1397 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1398 0, /* tp_init */
1399 0, /* tp_alloc */
1400 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001401 _PyObject_GC_Del, /* tp_free */
1402 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001403};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001404
1405
1406/* The base type of all types (eventually)... except itself. */
1407
1408static int
1409object_init(PyObject *self, PyObject *args, PyObject *kwds)
1410{
1411 return 0;
1412}
1413
1414static void
1415object_dealloc(PyObject *self)
1416{
1417 self->ob_type->tp_free(self);
1418}
1419
Guido van Rossum8e248182001-08-12 05:17:56 +00001420static PyObject *
1421object_repr(PyObject *self)
1422{
Guido van Rossum76e69632001-08-16 18:52:43 +00001423 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001424 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001425
Guido van Rossum76e69632001-08-16 18:52:43 +00001426 type = self->ob_type;
1427 mod = type_module(type, NULL);
1428 if (mod == NULL)
1429 PyErr_Clear();
1430 else if (!PyString_Check(mod)) {
1431 Py_DECREF(mod);
1432 mod = NULL;
1433 }
1434 name = type_name(type, NULL);
1435 if (name == NULL)
1436 return NULL;
1437 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001438 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001439 PyString_AS_STRING(mod),
1440 PyString_AS_STRING(name),
1441 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001442 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001443 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001444 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001445 Py_XDECREF(mod);
1446 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001447 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001448}
1449
Guido van Rossumb8f63662001-08-15 23:57:02 +00001450static PyObject *
1451object_str(PyObject *self)
1452{
1453 unaryfunc f;
1454
1455 f = self->ob_type->tp_repr;
1456 if (f == NULL)
1457 f = object_repr;
1458 return f(self);
1459}
1460
Guido van Rossum8e248182001-08-12 05:17:56 +00001461static long
1462object_hash(PyObject *self)
1463{
1464 return _Py_HashPointer(self);
1465}
Guido van Rossum8e248182001-08-12 05:17:56 +00001466
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001467static PyObject *
1468object_get_class(PyObject *self, void *closure)
1469{
1470 Py_INCREF(self->ob_type);
1471 return (PyObject *)(self->ob_type);
1472}
1473
1474static int
1475equiv_structs(PyTypeObject *a, PyTypeObject *b)
1476{
1477 return a == b ||
1478 (a != NULL &&
1479 b != NULL &&
1480 a->tp_basicsize == b->tp_basicsize &&
1481 a->tp_itemsize == b->tp_itemsize &&
1482 a->tp_dictoffset == b->tp_dictoffset &&
1483 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1484 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1485 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1486}
1487
1488static int
1489same_slots_added(PyTypeObject *a, PyTypeObject *b)
1490{
1491 PyTypeObject *base = a->tp_base;
1492 int size;
1493
1494 if (base != b->tp_base)
1495 return 0;
1496 if (equiv_structs(a, base) && equiv_structs(b, base))
1497 return 1;
1498 size = base->tp_basicsize;
1499 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1500 size += sizeof(PyObject *);
1501 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1502 size += sizeof(PyObject *);
1503 return size == a->tp_basicsize && size == b->tp_basicsize;
1504}
1505
1506static int
1507object_set_class(PyObject *self, PyObject *value, void *closure)
1508{
1509 PyTypeObject *old = self->ob_type;
1510 PyTypeObject *new, *newbase, *oldbase;
1511
1512 if (!PyType_Check(value)) {
1513 PyErr_Format(PyExc_TypeError,
1514 "__class__ must be set to new-style class, not '%s' object",
1515 value->ob_type->tp_name);
1516 return -1;
1517 }
1518 new = (PyTypeObject *)value;
1519 newbase = new;
1520 oldbase = old;
1521 while (equiv_structs(newbase, newbase->tp_base))
1522 newbase = newbase->tp_base;
1523 while (equiv_structs(oldbase, oldbase->tp_base))
1524 oldbase = oldbase->tp_base;
1525 if (newbase != oldbase &&
1526 (newbase->tp_base != oldbase->tp_base ||
1527 !same_slots_added(newbase, oldbase))) {
1528 PyErr_Format(PyExc_TypeError,
1529 "__class__ assignment: "
1530 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001531 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001532 old->tp_name);
1533 return -1;
1534 }
1535 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1536 Py_INCREF(new);
1537 }
1538 self->ob_type = new;
1539 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1540 Py_DECREF(old);
1541 }
1542 return 0;
1543}
1544
1545static PyGetSetDef object_getsets[] = {
1546 {"__class__", object_get_class, object_set_class,
1547 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001548 {0}
1549};
1550
Guido van Rossum3926a632001-09-25 16:25:58 +00001551static PyObject *
1552object_reduce(PyObject *self, PyObject *args)
1553{
1554 /* Call copy_reg._reduce(self) */
1555 static PyObject *copy_reg_str;
1556 PyObject *copy_reg, *res;
1557
1558 if (!copy_reg_str) {
1559 copy_reg_str = PyString_InternFromString("copy_reg");
1560 if (copy_reg_str == NULL)
1561 return NULL;
1562 }
1563 copy_reg = PyImport_Import(copy_reg_str);
1564 if (!copy_reg)
1565 return NULL;
1566 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1567 Py_DECREF(copy_reg);
1568 return res;
1569}
1570
1571static PyMethodDef object_methods[] = {
1572 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1573 {0}
1574};
1575
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576PyTypeObject PyBaseObject_Type = {
1577 PyObject_HEAD_INIT(&PyType_Type)
1578 0, /* ob_size */
1579 "object", /* tp_name */
1580 sizeof(PyObject), /* tp_basicsize */
1581 0, /* tp_itemsize */
1582 (destructor)object_dealloc, /* tp_dealloc */
1583 0, /* tp_print */
1584 0, /* tp_getattr */
1585 0, /* tp_setattr */
1586 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001587 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 0, /* tp_as_number */
1589 0, /* tp_as_sequence */
1590 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001591 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001593 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001595 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596 0, /* tp_as_buffer */
1597 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1598 "The most base type", /* tp_doc */
1599 0, /* tp_traverse */
1600 0, /* tp_clear */
1601 0, /* tp_richcompare */
1602 0, /* tp_weaklistoffset */
1603 0, /* tp_iter */
1604 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001605 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001606 0, /* tp_members */
1607 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001608 0, /* tp_base */
1609 0, /* tp_dict */
1610 0, /* tp_descr_get */
1611 0, /* tp_descr_set */
1612 0, /* tp_dictoffset */
1613 object_init, /* tp_init */
1614 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001615 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001616 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617};
1618
1619
1620/* Initialize the __dict__ in a type object */
1621
1622static int
1623add_methods(PyTypeObject *type, PyMethodDef *meth)
1624{
Guido van Rossum687ae002001-10-15 22:03:32 +00001625 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626
1627 for (; meth->ml_name != NULL; meth++) {
1628 PyObject *descr;
1629 if (PyDict_GetItemString(dict, meth->ml_name))
1630 continue;
1631 descr = PyDescr_NewMethod(type, meth);
1632 if (descr == NULL)
1633 return -1;
1634 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1635 return -1;
1636 Py_DECREF(descr);
1637 }
1638 return 0;
1639}
1640
1641static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001642add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001643{
Guido van Rossum687ae002001-10-15 22:03:32 +00001644 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645
1646 for (; memb->name != NULL; memb++) {
1647 PyObject *descr;
1648 if (PyDict_GetItemString(dict, memb->name))
1649 continue;
1650 descr = PyDescr_NewMember(type, memb);
1651 if (descr == NULL)
1652 return -1;
1653 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1654 return -1;
1655 Py_DECREF(descr);
1656 }
1657 return 0;
1658}
1659
1660static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001661add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662{
Guido van Rossum687ae002001-10-15 22:03:32 +00001663 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664
1665 for (; gsp->name != NULL; gsp++) {
1666 PyObject *descr;
1667 if (PyDict_GetItemString(dict, gsp->name))
1668 continue;
1669 descr = PyDescr_NewGetSet(type, gsp);
1670
1671 if (descr == NULL)
1672 return -1;
1673 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1674 return -1;
1675 Py_DECREF(descr);
1676 }
1677 return 0;
1678}
1679
Guido van Rossum13d52f02001-08-10 21:24:08 +00001680static void
1681inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682{
1683 int oldsize, newsize;
1684
Guido van Rossum13d52f02001-08-10 21:24:08 +00001685 /* Special flag magic */
1686 if (!type->tp_as_buffer && base->tp_as_buffer) {
1687 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1688 type->tp_flags |=
1689 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1690 }
1691 if (!type->tp_as_sequence && base->tp_as_sequence) {
1692 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1693 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1694 }
1695 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1696 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1697 if ((!type->tp_as_number && base->tp_as_number) ||
1698 (!type->tp_as_sequence && base->tp_as_sequence)) {
1699 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1700 if (!type->tp_as_number && !type->tp_as_sequence) {
1701 type->tp_flags |= base->tp_flags &
1702 Py_TPFLAGS_HAVE_INPLACEOPS;
1703 }
1704 }
1705 /* Wow */
1706 }
1707 if (!type->tp_as_number && base->tp_as_number) {
1708 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1709 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1710 }
1711
1712 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001713 oldsize = base->tp_basicsize;
1714 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1715 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1716 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001717 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1718 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001719 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001720 if (type->tp_traverse == NULL)
1721 type->tp_traverse = base->tp_traverse;
1722 if (type->tp_clear == NULL)
1723 type->tp_clear = base->tp_clear;
1724 }
1725 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1726 if (base != &PyBaseObject_Type ||
1727 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1728 if (type->tp_new == NULL)
1729 type->tp_new = base->tp_new;
1730 }
1731 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001732 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001733
1734 /* Copy other non-function slots */
1735
1736#undef COPYVAL
1737#define COPYVAL(SLOT) \
1738 if (type->SLOT == 0) type->SLOT = base->SLOT
1739
1740 COPYVAL(tp_itemsize);
1741 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1742 COPYVAL(tp_weaklistoffset);
1743 }
1744 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1745 COPYVAL(tp_dictoffset);
1746 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001747}
1748
1749static void
1750inherit_slots(PyTypeObject *type, PyTypeObject *base)
1751{
1752 PyTypeObject *basebase;
1753
1754#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001755#undef COPYSLOT
1756#undef COPYNUM
1757#undef COPYSEQ
1758#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001759#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001760
1761#define SLOTDEFINED(SLOT) \
1762 (base->SLOT != 0 && \
1763 (basebase == NULL || base->SLOT != basebase->SLOT))
1764
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001766 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767
1768#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1769#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1770#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001771#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772
Guido van Rossum13d52f02001-08-10 21:24:08 +00001773 /* This won't inherit indirect slots (from tp_as_number etc.)
1774 if type doesn't provide the space. */
1775
1776 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1777 basebase = base->tp_base;
1778 if (basebase->tp_as_number == NULL)
1779 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001780 COPYNUM(nb_add);
1781 COPYNUM(nb_subtract);
1782 COPYNUM(nb_multiply);
1783 COPYNUM(nb_divide);
1784 COPYNUM(nb_remainder);
1785 COPYNUM(nb_divmod);
1786 COPYNUM(nb_power);
1787 COPYNUM(nb_negative);
1788 COPYNUM(nb_positive);
1789 COPYNUM(nb_absolute);
1790 COPYNUM(nb_nonzero);
1791 COPYNUM(nb_invert);
1792 COPYNUM(nb_lshift);
1793 COPYNUM(nb_rshift);
1794 COPYNUM(nb_and);
1795 COPYNUM(nb_xor);
1796 COPYNUM(nb_or);
1797 COPYNUM(nb_coerce);
1798 COPYNUM(nb_int);
1799 COPYNUM(nb_long);
1800 COPYNUM(nb_float);
1801 COPYNUM(nb_oct);
1802 COPYNUM(nb_hex);
1803 COPYNUM(nb_inplace_add);
1804 COPYNUM(nb_inplace_subtract);
1805 COPYNUM(nb_inplace_multiply);
1806 COPYNUM(nb_inplace_divide);
1807 COPYNUM(nb_inplace_remainder);
1808 COPYNUM(nb_inplace_power);
1809 COPYNUM(nb_inplace_lshift);
1810 COPYNUM(nb_inplace_rshift);
1811 COPYNUM(nb_inplace_and);
1812 COPYNUM(nb_inplace_xor);
1813 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001814 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1815 COPYNUM(nb_true_divide);
1816 COPYNUM(nb_floor_divide);
1817 COPYNUM(nb_inplace_true_divide);
1818 COPYNUM(nb_inplace_floor_divide);
1819 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 }
1821
Guido van Rossum13d52f02001-08-10 21:24:08 +00001822 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1823 basebase = base->tp_base;
1824 if (basebase->tp_as_sequence == NULL)
1825 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 COPYSEQ(sq_length);
1827 COPYSEQ(sq_concat);
1828 COPYSEQ(sq_repeat);
1829 COPYSEQ(sq_item);
1830 COPYSEQ(sq_slice);
1831 COPYSEQ(sq_ass_item);
1832 COPYSEQ(sq_ass_slice);
1833 COPYSEQ(sq_contains);
1834 COPYSEQ(sq_inplace_concat);
1835 COPYSEQ(sq_inplace_repeat);
1836 }
1837
Guido van Rossum13d52f02001-08-10 21:24:08 +00001838 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1839 basebase = base->tp_base;
1840 if (basebase->tp_as_mapping == NULL)
1841 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842 COPYMAP(mp_length);
1843 COPYMAP(mp_subscript);
1844 COPYMAP(mp_ass_subscript);
1845 }
1846
Tim Petersfc57ccb2001-10-12 02:38:24 +00001847 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1848 basebase = base->tp_base;
1849 if (basebase->tp_as_buffer == NULL)
1850 basebase = NULL;
1851 COPYBUF(bf_getreadbuffer);
1852 COPYBUF(bf_getwritebuffer);
1853 COPYBUF(bf_getsegcount);
1854 COPYBUF(bf_getcharbuffer);
1855 }
1856
Guido van Rossum13d52f02001-08-10 21:24:08 +00001857 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 COPYSLOT(tp_dealloc);
1860 COPYSLOT(tp_print);
1861 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1862 type->tp_getattr = base->tp_getattr;
1863 type->tp_getattro = base->tp_getattro;
1864 }
1865 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1866 type->tp_setattr = base->tp_setattr;
1867 type->tp_setattro = base->tp_setattro;
1868 }
1869 /* tp_compare see tp_richcompare */
1870 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001871 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001872 COPYSLOT(tp_call);
1873 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001875 if (type->tp_compare == NULL &&
1876 type->tp_richcompare == NULL &&
1877 type->tp_hash == NULL)
1878 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 type->tp_compare = base->tp_compare;
1880 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001881 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882 }
1883 }
1884 else {
1885 COPYSLOT(tp_compare);
1886 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1888 COPYSLOT(tp_iter);
1889 COPYSLOT(tp_iternext);
1890 }
1891 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1892 COPYSLOT(tp_descr_get);
1893 COPYSLOT(tp_descr_set);
1894 COPYSLOT(tp_dictoffset);
1895 COPYSLOT(tp_init);
1896 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897 COPYSLOT(tp_free);
1898 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899}
1900
Guido van Rossum13d52f02001-08-10 21:24:08 +00001901staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001902staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001903
Tim Peters6d6c1a32001-08-02 04:15:00 +00001904int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001905PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001907 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908 PyTypeObject *base;
1909 int i, n;
1910
Guido van Rossumd614f972001-08-10 17:39:49 +00001911 if (type->tp_flags & Py_TPFLAGS_READY) {
1912 assert(type->tp_dict != NULL);
1913 return 0;
1914 }
1915 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00001916
1917 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001918
1919 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1920 base = type->tp_base;
1921 if (base == NULL && type != &PyBaseObject_Type)
1922 base = type->tp_base = &PyBaseObject_Type;
1923
1924 /* Initialize tp_bases */
1925 bases = type->tp_bases;
1926 if (bases == NULL) {
1927 if (base == NULL)
1928 bases = PyTuple_New(0);
1929 else
1930 bases = Py_BuildValue("(O)", base);
1931 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001932 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933 type->tp_bases = bases;
1934 }
1935
1936 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001937 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001938 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001939 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 }
1941
Guido van Rossum687ae002001-10-15 22:03:32 +00001942 /* Initialize tp_dict */
1943 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001944 if (dict == NULL) {
1945 dict = PyDict_New();
1946 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001947 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00001948 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949 }
1950
Guido van Rossum687ae002001-10-15 22:03:32 +00001951 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001953 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954 if (type->tp_methods != NULL) {
1955 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001956 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001957 }
1958 if (type->tp_members != NULL) {
1959 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001960 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961 }
1962 if (type->tp_getset != NULL) {
1963 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001964 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001965 }
1966
Tim Peters6d6c1a32001-08-02 04:15:00 +00001967 /* Calculate method resolution order */
1968 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001969 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001970 }
1971
Guido van Rossum13d52f02001-08-10 21:24:08 +00001972 /* Inherit special flags from dominant base */
1973 if (type->tp_base != NULL)
1974 inherit_special(type, type->tp_base);
1975
Tim Peters6d6c1a32001-08-02 04:15:00 +00001976 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001977 bases = type->tp_mro;
1978 assert(bases != NULL);
1979 assert(PyTuple_Check(bases));
1980 n = PyTuple_GET_SIZE(bases);
1981 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001982 PyObject *b = PyTuple_GET_ITEM(bases, i);
1983 if (PyType_Check(b))
1984 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001985 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986
Guido van Rossum13d52f02001-08-10 21:24:08 +00001987 /* Some more special stuff */
1988 base = type->tp_base;
1989 if (base != NULL) {
1990 if (type->tp_as_number == NULL)
1991 type->tp_as_number = base->tp_as_number;
1992 if (type->tp_as_sequence == NULL)
1993 type->tp_as_sequence = base->tp_as_sequence;
1994 if (type->tp_as_mapping == NULL)
1995 type->tp_as_mapping = base->tp_as_mapping;
1996 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001997
Guido van Rossum1c450732001-10-08 15:18:27 +00001998 /* Link into each base class's list of subclasses */
1999 bases = type->tp_bases;
2000 n = PyTuple_GET_SIZE(bases);
2001 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002002 PyObject *b = PyTuple_GET_ITEM(bases, i);
2003 if (PyType_Check(b) &&
2004 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002005 goto error;
2006 }
2007
Guido van Rossum13d52f02001-08-10 21:24:08 +00002008 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002009 assert(type->tp_dict != NULL);
2010 type->tp_flags =
2011 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002013
2014 error:
2015 type->tp_flags &= ~Py_TPFLAGS_READYING;
2016 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002017}
2018
Guido van Rossum1c450732001-10-08 15:18:27 +00002019static int
2020add_subclass(PyTypeObject *base, PyTypeObject *type)
2021{
2022 int i;
2023 PyObject *list, *ref, *new;
2024
2025 list = base->tp_subclasses;
2026 if (list == NULL) {
2027 base->tp_subclasses = list = PyList_New(0);
2028 if (list == NULL)
2029 return -1;
2030 }
2031 assert(PyList_Check(list));
2032 new = PyWeakref_NewRef((PyObject *)type, NULL);
2033 i = PyList_GET_SIZE(list);
2034 while (--i >= 0) {
2035 ref = PyList_GET_ITEM(list, i);
2036 assert(PyWeakref_CheckRef(ref));
2037 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2038 return PyList_SetItem(list, i, new);
2039 }
2040 i = PyList_Append(list, new);
2041 Py_DECREF(new);
2042 return i;
2043}
2044
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045
2046/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2047
2048/* There's a wrapper *function* for each distinct function typedef used
2049 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2050 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2051 Most tables have only one entry; the tables for binary operators have two
2052 entries, one regular and one with reversed arguments. */
2053
2054static PyObject *
2055wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2056{
2057 inquiry func = (inquiry)wrapped;
2058 int res;
2059
2060 if (!PyArg_ParseTuple(args, ""))
2061 return NULL;
2062 res = (*func)(self);
2063 if (res == -1 && PyErr_Occurred())
2064 return NULL;
2065 return PyInt_FromLong((long)res);
2066}
2067
Tim Peters6d6c1a32001-08-02 04:15:00 +00002068static PyObject *
2069wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2070{
2071 binaryfunc func = (binaryfunc)wrapped;
2072 PyObject *other;
2073
2074 if (!PyArg_ParseTuple(args, "O", &other))
2075 return NULL;
2076 return (*func)(self, other);
2077}
2078
2079static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002080wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2081{
2082 binaryfunc func = (binaryfunc)wrapped;
2083 PyObject *other;
2084
2085 if (!PyArg_ParseTuple(args, "O", &other))
2086 return NULL;
2087 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002088 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002089 Py_INCREF(Py_NotImplemented);
2090 return Py_NotImplemented;
2091 }
2092 return (*func)(self, other);
2093}
2094
2095static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002096wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2097{
2098 binaryfunc func = (binaryfunc)wrapped;
2099 PyObject *other;
2100
2101 if (!PyArg_ParseTuple(args, "O", &other))
2102 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002103 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002104 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002105 Py_INCREF(Py_NotImplemented);
2106 return Py_NotImplemented;
2107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108 return (*func)(other, self);
2109}
2110
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002111static PyObject *
2112wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2113{
2114 coercion func = (coercion)wrapped;
2115 PyObject *other, *res;
2116 int ok;
2117
2118 if (!PyArg_ParseTuple(args, "O", &other))
2119 return NULL;
2120 ok = func(&self, &other);
2121 if (ok < 0)
2122 return NULL;
2123 if (ok > 0) {
2124 Py_INCREF(Py_NotImplemented);
2125 return Py_NotImplemented;
2126 }
2127 res = PyTuple_New(2);
2128 if (res == NULL) {
2129 Py_DECREF(self);
2130 Py_DECREF(other);
2131 return NULL;
2132 }
2133 PyTuple_SET_ITEM(res, 0, self);
2134 PyTuple_SET_ITEM(res, 1, other);
2135 return res;
2136}
2137
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138static PyObject *
2139wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2140{
2141 ternaryfunc func = (ternaryfunc)wrapped;
2142 PyObject *other;
2143 PyObject *third = Py_None;
2144
2145 /* Note: This wrapper only works for __pow__() */
2146
2147 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2148 return NULL;
2149 return (*func)(self, other, third);
2150}
2151
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002152static PyObject *
2153wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2154{
2155 ternaryfunc func = (ternaryfunc)wrapped;
2156 PyObject *other;
2157 PyObject *third = Py_None;
2158
2159 /* Note: This wrapper only works for __pow__() */
2160
2161 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2162 return NULL;
2163 return (*func)(other, self, third);
2164}
2165
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166static PyObject *
2167wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2168{
2169 unaryfunc func = (unaryfunc)wrapped;
2170
2171 if (!PyArg_ParseTuple(args, ""))
2172 return NULL;
2173 return (*func)(self);
2174}
2175
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176static PyObject *
2177wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2178{
2179 intargfunc func = (intargfunc)wrapped;
2180 int i;
2181
2182 if (!PyArg_ParseTuple(args, "i", &i))
2183 return NULL;
2184 return (*func)(self, i);
2185}
2186
Guido van Rossum5d815f32001-08-17 21:57:47 +00002187static int
2188getindex(PyObject *self, PyObject *arg)
2189{
2190 int i;
2191
2192 i = PyInt_AsLong(arg);
2193 if (i == -1 && PyErr_Occurred())
2194 return -1;
2195 if (i < 0) {
2196 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2197 if (sq && sq->sq_length) {
2198 int n = (*sq->sq_length)(self);
2199 if (n < 0)
2200 return -1;
2201 i += n;
2202 }
2203 }
2204 return i;
2205}
2206
2207static PyObject *
2208wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2209{
2210 intargfunc func = (intargfunc)wrapped;
2211 PyObject *arg;
2212 int i;
2213
Guido van Rossumf4593e02001-10-03 12:09:30 +00002214 if (PyTuple_GET_SIZE(args) == 1) {
2215 arg = PyTuple_GET_ITEM(args, 0);
2216 i = getindex(self, arg);
2217 if (i == -1 && PyErr_Occurred())
2218 return NULL;
2219 return (*func)(self, i);
2220 }
2221 PyArg_ParseTuple(args, "O", &arg);
2222 assert(PyErr_Occurred());
2223 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002224}
2225
Tim Peters6d6c1a32001-08-02 04:15:00 +00002226static PyObject *
2227wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2228{
2229 intintargfunc func = (intintargfunc)wrapped;
2230 int i, j;
2231
2232 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2233 return NULL;
2234 return (*func)(self, i, j);
2235}
2236
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002238wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239{
2240 intobjargproc func = (intobjargproc)wrapped;
2241 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002242 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002243
Guido van Rossum5d815f32001-08-17 21:57:47 +00002244 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2245 return NULL;
2246 i = getindex(self, arg);
2247 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002248 return NULL;
2249 res = (*func)(self, i, value);
2250 if (res == -1 && PyErr_Occurred())
2251 return NULL;
2252 Py_INCREF(Py_None);
2253 return Py_None;
2254}
2255
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002256static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002257wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002258{
2259 intobjargproc func = (intobjargproc)wrapped;
2260 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002261 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002262
Guido van Rossum5d815f32001-08-17 21:57:47 +00002263 if (!PyArg_ParseTuple(args, "O", &arg))
2264 return NULL;
2265 i = getindex(self, arg);
2266 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002267 return NULL;
2268 res = (*func)(self, i, NULL);
2269 if (res == -1 && PyErr_Occurred())
2270 return NULL;
2271 Py_INCREF(Py_None);
2272 return Py_None;
2273}
2274
Tim Peters6d6c1a32001-08-02 04:15:00 +00002275static PyObject *
2276wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2277{
2278 intintobjargproc func = (intintobjargproc)wrapped;
2279 int i, j, res;
2280 PyObject *value;
2281
2282 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2283 return NULL;
2284 res = (*func)(self, i, j, value);
2285 if (res == -1 && PyErr_Occurred())
2286 return NULL;
2287 Py_INCREF(Py_None);
2288 return Py_None;
2289}
2290
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002291static PyObject *
2292wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2293{
2294 intintobjargproc func = (intintobjargproc)wrapped;
2295 int i, j, res;
2296
2297 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2298 return NULL;
2299 res = (*func)(self, i, j, NULL);
2300 if (res == -1 && PyErr_Occurred())
2301 return NULL;
2302 Py_INCREF(Py_None);
2303 return Py_None;
2304}
2305
Tim Peters6d6c1a32001-08-02 04:15:00 +00002306/* XXX objobjproc is a misnomer; should be objargpred */
2307static PyObject *
2308wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2309{
2310 objobjproc func = (objobjproc)wrapped;
2311 int res;
2312 PyObject *value;
2313
2314 if (!PyArg_ParseTuple(args, "O", &value))
2315 return NULL;
2316 res = (*func)(self, value);
2317 if (res == -1 && PyErr_Occurred())
2318 return NULL;
2319 return PyInt_FromLong((long)res);
2320}
2321
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322static PyObject *
2323wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2324{
2325 objobjargproc func = (objobjargproc)wrapped;
2326 int res;
2327 PyObject *key, *value;
2328
2329 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2330 return NULL;
2331 res = (*func)(self, key, value);
2332 if (res == -1 && PyErr_Occurred())
2333 return NULL;
2334 Py_INCREF(Py_None);
2335 return Py_None;
2336}
2337
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002338static PyObject *
2339wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2340{
2341 objobjargproc func = (objobjargproc)wrapped;
2342 int res;
2343 PyObject *key;
2344
2345 if (!PyArg_ParseTuple(args, "O", &key))
2346 return NULL;
2347 res = (*func)(self, key, NULL);
2348 if (res == -1 && PyErr_Occurred())
2349 return NULL;
2350 Py_INCREF(Py_None);
2351 return Py_None;
2352}
2353
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354static PyObject *
2355wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2356{
2357 cmpfunc func = (cmpfunc)wrapped;
2358 int res;
2359 PyObject *other;
2360
2361 if (!PyArg_ParseTuple(args, "O", &other))
2362 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002363 if (other->ob_type->tp_compare != func &&
2364 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002365 PyErr_Format(
2366 PyExc_TypeError,
2367 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2368 self->ob_type->tp_name,
2369 self->ob_type->tp_name,
2370 other->ob_type->tp_name);
2371 return NULL;
2372 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373 res = (*func)(self, other);
2374 if (PyErr_Occurred())
2375 return NULL;
2376 return PyInt_FromLong((long)res);
2377}
2378
Tim Peters6d6c1a32001-08-02 04:15:00 +00002379static PyObject *
2380wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2381{
2382 setattrofunc func = (setattrofunc)wrapped;
2383 int res;
2384 PyObject *name, *value;
2385
2386 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2387 return NULL;
2388 res = (*func)(self, name, value);
2389 if (res < 0)
2390 return NULL;
2391 Py_INCREF(Py_None);
2392 return Py_None;
2393}
2394
2395static PyObject *
2396wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2397{
2398 setattrofunc func = (setattrofunc)wrapped;
2399 int res;
2400 PyObject *name;
2401
2402 if (!PyArg_ParseTuple(args, "O", &name))
2403 return NULL;
2404 res = (*func)(self, name, NULL);
2405 if (res < 0)
2406 return NULL;
2407 Py_INCREF(Py_None);
2408 return Py_None;
2409}
2410
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411static PyObject *
2412wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2413{
2414 hashfunc func = (hashfunc)wrapped;
2415 long res;
2416
2417 if (!PyArg_ParseTuple(args, ""))
2418 return NULL;
2419 res = (*func)(self);
2420 if (res == -1 && PyErr_Occurred())
2421 return NULL;
2422 return PyInt_FromLong(res);
2423}
2424
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002426wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427{
2428 ternaryfunc func = (ternaryfunc)wrapped;
2429
Guido van Rossumc8e56452001-10-22 00:43:43 +00002430 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431}
2432
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433static PyObject *
2434wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2435{
2436 richcmpfunc func = (richcmpfunc)wrapped;
2437 PyObject *other;
2438
2439 if (!PyArg_ParseTuple(args, "O", &other))
2440 return NULL;
2441 return (*func)(self, other, op);
2442}
2443
2444#undef RICHCMP_WRAPPER
2445#define RICHCMP_WRAPPER(NAME, OP) \
2446static PyObject * \
2447richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2448{ \
2449 return wrap_richcmpfunc(self, args, wrapped, OP); \
2450}
2451
Jack Jansen8e938b42001-08-08 15:29:49 +00002452RICHCMP_WRAPPER(lt, Py_LT)
2453RICHCMP_WRAPPER(le, Py_LE)
2454RICHCMP_WRAPPER(eq, Py_EQ)
2455RICHCMP_WRAPPER(ne, Py_NE)
2456RICHCMP_WRAPPER(gt, Py_GT)
2457RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002458
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459static PyObject *
2460wrap_next(PyObject *self, PyObject *args, void *wrapped)
2461{
2462 unaryfunc func = (unaryfunc)wrapped;
2463 PyObject *res;
2464
2465 if (!PyArg_ParseTuple(args, ""))
2466 return NULL;
2467 res = (*func)(self);
2468 if (res == NULL && !PyErr_Occurred())
2469 PyErr_SetNone(PyExc_StopIteration);
2470 return res;
2471}
2472
Tim Peters6d6c1a32001-08-02 04:15:00 +00002473static PyObject *
2474wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2475{
2476 descrgetfunc func = (descrgetfunc)wrapped;
2477 PyObject *obj;
2478 PyObject *type = NULL;
2479
2480 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2481 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002482 return (*func)(self, obj, type);
2483}
2484
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002486wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487{
2488 descrsetfunc func = (descrsetfunc)wrapped;
2489 PyObject *obj, *value;
2490 int ret;
2491
2492 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2493 return NULL;
2494 ret = (*func)(self, obj, value);
2495 if (ret < 0)
2496 return NULL;
2497 Py_INCREF(Py_None);
2498 return Py_None;
2499}
2500
Tim Peters6d6c1a32001-08-02 04:15:00 +00002501static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002502wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002503{
2504 initproc func = (initproc)wrapped;
2505
Guido van Rossumc8e56452001-10-22 00:43:43 +00002506 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002507 return NULL;
2508 Py_INCREF(Py_None);
2509 return Py_None;
2510}
2511
Tim Peters6d6c1a32001-08-02 04:15:00 +00002512static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002513tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514{
Barry Warsaw60f01882001-08-22 19:24:42 +00002515 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002516 PyObject *arg0, *res;
2517
2518 if (self == NULL || !PyType_Check(self))
2519 Py_FatalError("__new__() called with non-type 'self'");
2520 type = (PyTypeObject *)self;
2521 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002522 PyErr_Format(PyExc_TypeError,
2523 "%s.__new__(): not enough arguments",
2524 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002525 return NULL;
2526 }
2527 arg0 = PyTuple_GET_ITEM(args, 0);
2528 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002529 PyErr_Format(PyExc_TypeError,
2530 "%s.__new__(X): X is not a type object (%s)",
2531 type->tp_name,
2532 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002533 return NULL;
2534 }
2535 subtype = (PyTypeObject *)arg0;
2536 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002537 PyErr_Format(PyExc_TypeError,
2538 "%s.__new__(%s): %s is not a subtype of %s",
2539 type->tp_name,
2540 subtype->tp_name,
2541 subtype->tp_name,
2542 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002543 return NULL;
2544 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002545
2546 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002547 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002548 most derived base that's not a heap type is this type. */
2549 staticbase = subtype;
2550 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2551 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002552 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002553 PyErr_Format(PyExc_TypeError,
2554 "%s.__new__(%s) is not safe, use %s.__new__()",
2555 type->tp_name,
2556 subtype->tp_name,
2557 staticbase == NULL ? "?" : staticbase->tp_name);
2558 return NULL;
2559 }
2560
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002561 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2562 if (args == NULL)
2563 return NULL;
2564 res = type->tp_new(subtype, args, kwds);
2565 Py_DECREF(args);
2566 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002567}
2568
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002569static struct PyMethodDef tp_new_methoddef[] = {
2570 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2571 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572 {0}
2573};
2574
2575static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002576add_tp_new_wrapper(PyTypeObject *type)
2577{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002578 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002579
Guido van Rossum687ae002001-10-15 22:03:32 +00002580 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002581 return 0;
2582 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002583 if (func == NULL)
2584 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002585 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002586}
2587
Guido van Rossumf040ede2001-08-07 16:40:56 +00002588/* Slot wrappers that call the corresponding __foo__ slot. See comments
2589 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590
Guido van Rossumdc91b992001-08-08 22:26:22 +00002591#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002593FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002594{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002595 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002596 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002597}
2598
Guido van Rossumdc91b992001-08-08 22:26:22 +00002599#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002600static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002601FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002603 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002604 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002605}
2606
Guido van Rossumdc91b992001-08-08 22:26:22 +00002607
2608#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002609static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002610FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002611{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002612 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002613 int do_other = self->ob_type != other->ob_type && \
2614 other->ob_type->tp_as_number != NULL && \
2615 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002616 if (self->ob_type->tp_as_number != NULL && \
2617 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2618 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002619 if (do_other && \
2620 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2621 r = call_maybe( \
2622 other, ROPSTR, &rcache_str, "(O)", self); \
2623 if (r != Py_NotImplemented) \
2624 return r; \
2625 Py_DECREF(r); \
2626 do_other = 0; \
2627 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002628 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002629 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002630 if (r != Py_NotImplemented || \
2631 other->ob_type == self->ob_type) \
2632 return r; \
2633 Py_DECREF(r); \
2634 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002635 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002636 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002637 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002638 } \
2639 Py_INCREF(Py_NotImplemented); \
2640 return Py_NotImplemented; \
2641}
2642
2643#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2644 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2645
2646#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2647static PyObject * \
2648FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2649{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002650 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002651 return call_method(self, OPSTR, &cache_str, \
2652 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002653}
2654
2655static int
2656slot_sq_length(PyObject *self)
2657{
Guido van Rossum2730b132001-08-28 18:22:14 +00002658 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002659 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002660 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002661
2662 if (res == NULL)
2663 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002664 len = (int)PyInt_AsLong(res);
2665 Py_DECREF(res);
2666 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667}
2668
Guido van Rossumdc91b992001-08-08 22:26:22 +00002669SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2670SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002671
2672/* Super-optimized version of slot_sq_item.
2673 Other slots could do the same... */
2674static PyObject *
2675slot_sq_item(PyObject *self, int i)
2676{
2677 static PyObject *getitem_str;
2678 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2679 descrgetfunc f;
2680
2681 if (getitem_str == NULL) {
2682 getitem_str = PyString_InternFromString("__getitem__");
2683 if (getitem_str == NULL)
2684 return NULL;
2685 }
2686 func = _PyType_Lookup(self->ob_type, getitem_str);
2687 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002688 if ((f = func->ob_type->tp_descr_get) == NULL)
2689 Py_INCREF(func);
2690 else
2691 func = f(func, self, (PyObject *)(self->ob_type));
2692 ival = PyInt_FromLong(i);
2693 if (ival != NULL) {
2694 args = PyTuple_New(1);
2695 if (args != NULL) {
2696 PyTuple_SET_ITEM(args, 0, ival);
2697 retval = PyObject_Call(func, args, NULL);
2698 Py_XDECREF(args);
2699 Py_XDECREF(func);
2700 return retval;
2701 }
2702 }
2703 }
2704 else {
2705 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2706 }
2707 Py_XDECREF(args);
2708 Py_XDECREF(ival);
2709 Py_XDECREF(func);
2710 return NULL;
2711}
2712
Guido van Rossumdc91b992001-08-08 22:26:22 +00002713SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714
2715static int
2716slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2717{
2718 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002719 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720
2721 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002722 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002723 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002725 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002726 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727 if (res == NULL)
2728 return -1;
2729 Py_DECREF(res);
2730 return 0;
2731}
2732
2733static int
2734slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2735{
2736 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002737 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002738
2739 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002740 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002741 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002743 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002744 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745 if (res == NULL)
2746 return -1;
2747 Py_DECREF(res);
2748 return 0;
2749}
2750
2751static int
2752slot_sq_contains(PyObject *self, PyObject *value)
2753{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002754 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002755 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756
Guido van Rossum55f20992001-10-01 17:18:22 +00002757 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002758
2759 if (func != NULL) {
2760 args = Py_BuildValue("(O)", value);
2761 if (args == NULL)
2762 res = NULL;
2763 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002764 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002765 Py_DECREF(args);
2766 }
2767 Py_DECREF(func);
2768 if (res == NULL)
2769 return -1;
2770 return PyObject_IsTrue(res);
2771 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002772 else if (PyErr_Occurred())
2773 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002774 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002775 return _PySequence_IterSearch(self, value,
2776 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002777 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778}
2779
Guido van Rossumdc91b992001-08-08 22:26:22 +00002780SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2781SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782
2783#define slot_mp_length slot_sq_length
2784
Guido van Rossumdc91b992001-08-08 22:26:22 +00002785SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786
2787static int
2788slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2789{
2790 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002791 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002792
2793 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002794 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002795 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002797 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002798 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799 if (res == NULL)
2800 return -1;
2801 Py_DECREF(res);
2802 return 0;
2803}
2804
Guido van Rossumdc91b992001-08-08 22:26:22 +00002805SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2806SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2807SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2808SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2809SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2810SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2811
2812staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2813
2814SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2815 nb_power, "__pow__", "__rpow__")
2816
2817static PyObject *
2818slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2819{
Guido van Rossum2730b132001-08-28 18:22:14 +00002820 static PyObject *pow_str;
2821
Guido van Rossumdc91b992001-08-08 22:26:22 +00002822 if (modulus == Py_None)
2823 return slot_nb_power_binary(self, other);
2824 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002825 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002826 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002827}
2828
2829SLOT0(slot_nb_negative, "__neg__")
2830SLOT0(slot_nb_positive, "__pos__")
2831SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832
2833static int
2834slot_nb_nonzero(PyObject *self)
2835{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002836 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002837 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002838
Guido van Rossum55f20992001-10-01 17:18:22 +00002839 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002840 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002841 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002842 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002843 func = lookup_maybe(self, "__len__", &len_str);
2844 if (func == NULL) {
2845 if (PyErr_Occurred())
2846 return -1;
2847 else
2848 return 1;
2849 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002850 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002851 res = PyObject_CallObject(func, NULL);
2852 Py_DECREF(func);
2853 if (res == NULL)
2854 return -1;
2855 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002856}
2857
Guido van Rossumdc91b992001-08-08 22:26:22 +00002858SLOT0(slot_nb_invert, "__invert__")
2859SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2860SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2861SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2862SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2863SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002864
2865static int
2866slot_nb_coerce(PyObject **a, PyObject **b)
2867{
2868 static PyObject *coerce_str;
2869 PyObject *self = *a, *other = *b;
2870
2871 if (self->ob_type->tp_as_number != NULL &&
2872 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2873 PyObject *r;
2874 r = call_maybe(
2875 self, "__coerce__", &coerce_str, "(O)", other);
2876 if (r == NULL)
2877 return -1;
2878 if (r == Py_NotImplemented) {
2879 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002880 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002881 else {
2882 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2883 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002884 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00002885 Py_DECREF(r);
2886 return -1;
2887 }
2888 *a = PyTuple_GET_ITEM(r, 0);
2889 Py_INCREF(*a);
2890 *b = PyTuple_GET_ITEM(r, 1);
2891 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002892 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00002893 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002894 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002895 }
2896 if (other->ob_type->tp_as_number != NULL &&
2897 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2898 PyObject *r;
2899 r = call_maybe(
2900 other, "__coerce__", &coerce_str, "(O)", self);
2901 if (r == NULL)
2902 return -1;
2903 if (r == Py_NotImplemented) {
2904 Py_DECREF(r);
2905 return 1;
2906 }
2907 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2908 PyErr_SetString(PyExc_TypeError,
2909 "__coerce__ didn't return a 2-tuple");
2910 Py_DECREF(r);
2911 return -1;
2912 }
2913 *a = PyTuple_GET_ITEM(r, 1);
2914 Py_INCREF(*a);
2915 *b = PyTuple_GET_ITEM(r, 0);
2916 Py_INCREF(*b);
2917 Py_DECREF(r);
2918 return 0;
2919 }
2920 return 1;
2921}
2922
Guido van Rossumdc91b992001-08-08 22:26:22 +00002923SLOT0(slot_nb_int, "__int__")
2924SLOT0(slot_nb_long, "__long__")
2925SLOT0(slot_nb_float, "__float__")
2926SLOT0(slot_nb_oct, "__oct__")
2927SLOT0(slot_nb_hex, "__hex__")
2928SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2929SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2930SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2931SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2932SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2933SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2934SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2935SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2936SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2937SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2938SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2939SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2940 "__floordiv__", "__rfloordiv__")
2941SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2942SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2943SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002944
2945static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002946half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002947{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002948 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002949 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002950 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002951
Guido van Rossum60718732001-08-28 17:47:51 +00002952 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002953 if (func == NULL) {
2954 PyErr_Clear();
2955 }
2956 else {
2957 args = Py_BuildValue("(O)", other);
2958 if (args == NULL)
2959 res = NULL;
2960 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002961 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002962 Py_DECREF(args);
2963 }
2964 if (res != Py_NotImplemented) {
2965 if (res == NULL)
2966 return -2;
2967 c = PyInt_AsLong(res);
2968 Py_DECREF(res);
2969 if (c == -1 && PyErr_Occurred())
2970 return -2;
2971 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2972 }
2973 Py_DECREF(res);
2974 }
2975 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002976}
2977
Guido van Rossumab3b0342001-09-18 20:38:53 +00002978/* This slot is published for the benefit of try_3way_compare in object.c */
2979int
2980_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00002981{
2982 int c;
2983
Guido van Rossumab3b0342001-09-18 20:38:53 +00002984 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002985 c = half_compare(self, other);
2986 if (c <= 1)
2987 return c;
2988 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00002989 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002990 c = half_compare(other, self);
2991 if (c < -1)
2992 return -2;
2993 if (c <= 1)
2994 return -c;
2995 }
2996 return (void *)self < (void *)other ? -1 :
2997 (void *)self > (void *)other ? 1 : 0;
2998}
2999
3000static PyObject *
3001slot_tp_repr(PyObject *self)
3002{
3003 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003004 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003005
Guido van Rossum60718732001-08-28 17:47:51 +00003006 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003007 if (func != NULL) {
3008 res = PyEval_CallObject(func, NULL);
3009 Py_DECREF(func);
3010 return res;
3011 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003012 PyErr_Clear();
3013 return PyString_FromFormat("<%s object at %p>",
3014 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003015}
3016
3017static PyObject *
3018slot_tp_str(PyObject *self)
3019{
3020 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003021 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003022
Guido van Rossum60718732001-08-28 17:47:51 +00003023 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003024 if (func != NULL) {
3025 res = PyEval_CallObject(func, NULL);
3026 Py_DECREF(func);
3027 return res;
3028 }
3029 else {
3030 PyErr_Clear();
3031 return slot_tp_repr(self);
3032 }
3033}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003034
3035static long
3036slot_tp_hash(PyObject *self)
3037{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003038 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003039 static PyObject *hash_str, *eq_str, *cmp_str;
3040
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041 long h;
3042
Guido van Rossum60718732001-08-28 17:47:51 +00003043 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003044
3045 if (func != NULL) {
3046 res = PyEval_CallObject(func, NULL);
3047 Py_DECREF(func);
3048 if (res == NULL)
3049 return -1;
3050 h = PyInt_AsLong(res);
3051 }
3052 else {
3053 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003054 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003055 if (func == NULL) {
3056 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003057 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003058 }
3059 if (func != NULL) {
3060 Py_DECREF(func);
3061 PyErr_SetString(PyExc_TypeError, "unhashable type");
3062 return -1;
3063 }
3064 PyErr_Clear();
3065 h = _Py_HashPointer((void *)self);
3066 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067 if (h == -1 && !PyErr_Occurred())
3068 h = -2;
3069 return h;
3070}
3071
3072static PyObject *
3073slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3074{
Guido van Rossum60718732001-08-28 17:47:51 +00003075 static PyObject *call_str;
3076 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003077 PyObject *res;
3078
3079 if (meth == NULL)
3080 return NULL;
3081 res = PyObject_Call(meth, args, kwds);
3082 Py_DECREF(meth);
3083 return res;
3084}
3085
Guido van Rossum14a6f832001-10-17 13:59:09 +00003086/* There are two slot dispatch functions for tp_getattro.
3087
3088 - slot_tp_getattro() is used when __getattribute__ is overridden
3089 but no __getattr__ hook is present;
3090
3091 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3092
3093 The code in update_slot() and fixup_slot_dispatchers() always installs
3094 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3095 installs the simpler slot if necessary. */
3096
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097static PyObject *
3098slot_tp_getattro(PyObject *self, PyObject *name)
3099{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003100 static PyObject *getattribute_str = NULL;
3101 return call_method(self, "__getattribute__", &getattribute_str,
3102 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103}
3104
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003105static PyObject *
3106slot_tp_getattr_hook(PyObject *self, PyObject *name)
3107{
3108 PyTypeObject *tp = self->ob_type;
3109 PyObject *getattr, *getattribute, *res;
3110 static PyObject *getattribute_str = NULL;
3111 static PyObject *getattr_str = NULL;
3112
3113 if (getattr_str == NULL) {
3114 getattr_str = PyString_InternFromString("__getattr__");
3115 if (getattr_str == NULL)
3116 return NULL;
3117 }
3118 if (getattribute_str == NULL) {
3119 getattribute_str =
3120 PyString_InternFromString("__getattribute__");
3121 if (getattribute_str == NULL)
3122 return NULL;
3123 }
3124 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003125 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003126 /* No __getattr__ hook: use a simpler dispatcher */
3127 tp->tp_getattro = slot_tp_getattro;
3128 return slot_tp_getattro(self, name);
3129 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003130 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003131 if (getattribute == NULL ||
3132 (getattribute->ob_type == &PyWrapperDescr_Type &&
3133 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3134 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003135 res = PyObject_GenericGetAttr(self, name);
3136 else
3137 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003138 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003139 PyErr_Clear();
3140 res = PyObject_CallFunction(getattr, "OO", self, name);
3141 }
3142 return res;
3143}
3144
Tim Peters6d6c1a32001-08-02 04:15:00 +00003145static int
3146slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3147{
3148 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003149 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150
3151 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003152 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003153 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003155 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003156 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157 if (res == NULL)
3158 return -1;
3159 Py_DECREF(res);
3160 return 0;
3161}
3162
3163/* Map rich comparison operators to their __xx__ namesakes */
3164static char *name_op[] = {
3165 "__lt__",
3166 "__le__",
3167 "__eq__",
3168 "__ne__",
3169 "__gt__",
3170 "__ge__",
3171};
3172
3173static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003174half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003175{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003176 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003177 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178
Guido van Rossum60718732001-08-28 17:47:51 +00003179 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003180 if (func == NULL) {
3181 PyErr_Clear();
3182 Py_INCREF(Py_NotImplemented);
3183 return Py_NotImplemented;
3184 }
3185 args = Py_BuildValue("(O)", other);
3186 if (args == NULL)
3187 res = NULL;
3188 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003189 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003190 Py_DECREF(args);
3191 }
3192 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193 return res;
3194}
3195
Guido van Rossumb8f63662001-08-15 23:57:02 +00003196/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3197static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3198
3199static PyObject *
3200slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3201{
3202 PyObject *res;
3203
3204 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3205 res = half_richcompare(self, other, op);
3206 if (res != Py_NotImplemented)
3207 return res;
3208 Py_DECREF(res);
3209 }
3210 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3211 res = half_richcompare(other, self, swapped_op[op]);
3212 if (res != Py_NotImplemented) {
3213 return res;
3214 }
3215 Py_DECREF(res);
3216 }
3217 Py_INCREF(Py_NotImplemented);
3218 return Py_NotImplemented;
3219}
3220
3221static PyObject *
3222slot_tp_iter(PyObject *self)
3223{
3224 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003225 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003226
Guido van Rossum60718732001-08-28 17:47:51 +00003227 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003228 if (func != NULL) {
3229 res = PyObject_CallObject(func, NULL);
3230 Py_DECREF(func);
3231 return res;
3232 }
3233 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003234 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003235 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003236 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003237 return NULL;
3238 }
3239 Py_DECREF(func);
3240 return PySeqIter_New(self);
3241}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003242
3243static PyObject *
3244slot_tp_iternext(PyObject *self)
3245{
Guido van Rossum2730b132001-08-28 18:22:14 +00003246 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003247 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003248}
3249
Guido van Rossum1a493502001-08-17 16:47:50 +00003250static PyObject *
3251slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3252{
3253 PyTypeObject *tp = self->ob_type;
3254 PyObject *get;
3255 static PyObject *get_str = NULL;
3256
3257 if (get_str == NULL) {
3258 get_str = PyString_InternFromString("__get__");
3259 if (get_str == NULL)
3260 return NULL;
3261 }
3262 get = _PyType_Lookup(tp, get_str);
3263 if (get == NULL) {
3264 /* Avoid further slowdowns */
3265 if (tp->tp_descr_get == slot_tp_descr_get)
3266 tp->tp_descr_get = NULL;
3267 Py_INCREF(self);
3268 return self;
3269 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003270 if (obj == NULL)
3271 obj = Py_None;
3272 if (type == NULL)
3273 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003274 return PyObject_CallFunction(get, "OOO", self, obj, type);
3275}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003276
3277static int
3278slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3279{
Guido van Rossum2c252392001-08-24 10:13:31 +00003280 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003281 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003282
3283 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003284 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003285 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003286 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003287 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003288 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289 if (res == NULL)
3290 return -1;
3291 Py_DECREF(res);
3292 return 0;
3293}
3294
3295static int
3296slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3297{
Guido van Rossum60718732001-08-28 17:47:51 +00003298 static PyObject *init_str;
3299 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300 PyObject *res;
3301
3302 if (meth == NULL)
3303 return -1;
3304 res = PyObject_Call(meth, args, kwds);
3305 Py_DECREF(meth);
3306 if (res == NULL)
3307 return -1;
3308 Py_DECREF(res);
3309 return 0;
3310}
3311
3312static PyObject *
3313slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3314{
3315 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3316 PyObject *newargs, *x;
3317 int i, n;
3318
3319 if (func == NULL)
3320 return NULL;
3321 assert(PyTuple_Check(args));
3322 n = PyTuple_GET_SIZE(args);
3323 newargs = PyTuple_New(n+1);
3324 if (newargs == NULL)
3325 return NULL;
3326 Py_INCREF(type);
3327 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3328 for (i = 0; i < n; i++) {
3329 x = PyTuple_GET_ITEM(args, i);
3330 Py_INCREF(x);
3331 PyTuple_SET_ITEM(newargs, i+1, x);
3332 }
3333 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003334 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003335 Py_DECREF(func);
3336 return x;
3337}
3338
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003339
3340/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3341 functions. The offsets here are relative to the 'etype' structure, which
3342 incorporates the additional structures used for numbers, sequences and
3343 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3344 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3345 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3346
Guido van Rossum6d204072001-10-21 00:44:31 +00003347typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003348
3349#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003350#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003351#undef ETSLOT
3352#undef SQSLOT
3353#undef MPSLOT
3354#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003355#undef UNSLOT
3356#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003357#undef BINSLOT
3358#undef RBINSLOT
3359
Guido van Rossum6d204072001-10-21 00:44:31 +00003360#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3361 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003362#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3363 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3364 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003365#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3366 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3367#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3368 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3369#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3370 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3371#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3372 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3373#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3374 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3375 "x." NAME "() <==> " DOC)
3376#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3377 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3378 "x." NAME "(y) <==> x" DOC "y")
3379#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3380 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3381 "x." NAME "(y) <==> x" DOC "y")
3382#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3383 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3384 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003385
3386static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003387 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3388 "x.__len__() <==> len(x)"),
3389 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3390 "x.__add__(y) <==> x+y"),
3391 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3392 "x.__mul__(n) <==> x*n"),
3393 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3394 "x.__rmul__(n) <==> n*x"),
3395 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3396 "x.__getitem__(y) <==> x[y]"),
3397 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3398 "x.__getslice__(i, j) <==> x[i:j]"),
3399 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3400 "x.__setitem__(i, y) <==> x[i]=y"),
3401 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3402 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003403 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003404 wrap_intintobjargproc,
3405 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3406 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3407 "x.__delslice__(i, j) <==> del x[i:j]"),
3408 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3409 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003410 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003411 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003412 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003413 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003414
Guido van Rossum6d204072001-10-21 00:44:31 +00003415 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3416 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003417 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003418 wrap_binaryfunc,
3419 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003420 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003421 wrap_objobjargproc,
3422 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003423 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003424 wrap_delitem,
3425 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003426
Guido van Rossum6d204072001-10-21 00:44:31 +00003427 BINSLOT("__add__", nb_add, slot_nb_add,
3428 "+"),
3429 RBINSLOT("__radd__", nb_add, slot_nb_add,
3430 "+"),
3431 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3432 "-"),
3433 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3434 "-"),
3435 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3436 "*"),
3437 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3438 "*"),
3439 BINSLOT("__div__", nb_divide, slot_nb_divide,
3440 "/"),
3441 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3442 "/"),
3443 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3444 "%"),
3445 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3446 "%"),
3447 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3448 "divmod(x, y)"),
3449 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3450 "divmod(y, x)"),
3451 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3452 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3453 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3454 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3455 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3456 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3457 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3458 "abs(x)"),
3459 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc,
3460 "x != 0"),
3461 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3462 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3463 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3464 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3465 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3466 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3467 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3468 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3469 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3470 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3471 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3472 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3473 "x.__coerce__(y) <==> coerce(x, y)"),
3474 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3475 "int(x)"),
3476 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3477 "long(x)"),
3478 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3479 "float(x)"),
3480 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3481 "oct(x)"),
3482 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3483 "hex(x)"),
3484 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3485 wrap_binaryfunc, "+"),
3486 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3487 wrap_binaryfunc, "-"),
3488 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3489 wrap_binaryfunc, "*"),
3490 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3491 wrap_binaryfunc, "/"),
3492 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3493 wrap_binaryfunc, "%"),
3494 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3495 wrap_ternaryfunc, "**"),
3496 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3497 wrap_binaryfunc, "<<"),
3498 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3499 wrap_binaryfunc, ">>"),
3500 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3501 wrap_binaryfunc, "&"),
3502 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3503 wrap_binaryfunc, "^"),
3504 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3505 wrap_binaryfunc, "|"),
3506 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3507 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3508 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3509 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3510 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3511 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3512 IBSLOT("__itruediv__", nb_inplace_true_divide,
3513 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003514
Guido van Rossum6d204072001-10-21 00:44:31 +00003515 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3516 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003517 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003518 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3519 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003520 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003521 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3522 "x.__cmp__(y) <==> cmp(x,y)"),
3523 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3524 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003525 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3526 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003527 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003528 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3529 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3530 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3531 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3532 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3533 "x.__setattr__('name', value) <==> x.name = value"),
3534 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3535 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3536 "x.__delattr__('name') <==> del x.name"),
3537 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3538 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3539 "x.__lt__(y) <==> x<y"),
3540 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3541 "x.__le__(y) <==> x<=y"),
3542 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3543 "x.__eq__(y) <==> x==y"),
3544 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3545 "x.__ne__(y) <==> x!=y"),
3546 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3547 "x.__gt__(y) <==> x>y"),
3548 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3549 "x.__ge__(y) <==> x>=y"),
3550 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3551 "x.__iter__() <==> iter(x)"),
3552 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3553 "x.next() -> the next value, or raise StopIteration"),
3554 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3555 "descr.__get__(obj[, type]) -> value"),
3556 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3557 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003558 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003559 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003560 "see x.__class__.__doc__ for signature",
3561 PyWrapperFlag_KEYWORDS),
3562 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003563 {NULL}
3564};
3565
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003566static void **
3567slotptr(PyTypeObject *type, int offset)
3568{
3569 char *ptr;
3570
3571 assert(offset >= 0);
3572 assert(offset < offsetof(etype, as_buffer));
3573 if (offset >= offsetof(etype, as_mapping)) {
3574 ptr = (void *)type->tp_as_mapping;
3575 offset -= offsetof(etype, as_mapping);
3576 }
3577 else if (offset >= offsetof(etype, as_sequence)) {
3578 ptr = (void *)type->tp_as_sequence;
3579 offset -= offsetof(etype, as_sequence);
3580 }
3581 else if (offset >= offsetof(etype, as_number)) {
3582 ptr = (void *)type->tp_as_number;
3583 offset -= offsetof(etype, as_number);
3584 }
3585 else {
3586 ptr = (void *)type;
3587 }
3588 if (ptr != NULL)
3589 ptr += offset;
3590 return (void **)ptr;
3591}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003592
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003593staticforward int recurse_down_subclasses(PyTypeObject *type,
3594 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003595
3596static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003597update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003598{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003599 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003600
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003601 for (pp = pp0; *pp; pp++) {
3602 slotdef *p = *pp;
3603 PyObject *descr;
3604 PyWrapperDescrObject *d;
3605 void *generic = NULL, *specific = NULL;
3606 int use_generic = 0;
3607 int offset = p->offset;
3608 void **ptr = slotptr(type, offset);
3609 if (ptr == NULL)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003610 continue;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003611 do {
3612 descr = _PyType_Lookup(type, p->name_strobj);
3613 if (descr == NULL)
3614 continue;
3615 generic = p->function;
3616 if (descr->ob_type == &PyWrapperDescr_Type) {
3617 d = (PyWrapperDescrObject *)descr;
3618 if (d->d_base->wrapper == p->wrapper &&
3619 PyType_IsSubtype(type, d->d_type)) {
3620 if (specific == NULL ||
3621 specific == d->d_wrapped)
3622 specific = d->d_wrapped;
3623 else
3624 use_generic = 1;
3625 }
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003626 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003627 else
3628 use_generic = 1;
3629 } while ((++p)->offset == offset);
3630 if (specific && !use_generic)
3631 *ptr = specific;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003632 else
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003633 *ptr = generic;
3634 }
3635 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003636}
3637
3638static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003639recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003640{
3641 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003642 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003643 int i, n;
3644
3645 subclasses = type->tp_subclasses;
3646 if (subclasses == NULL)
3647 return 0;
3648 assert(PyList_Check(subclasses));
3649 n = PyList_GET_SIZE(subclasses);
3650 for (i = 0; i < n; i++) {
3651 ref = PyList_GET_ITEM(subclasses, i);
3652 assert(PyWeakref_CheckRef(ref));
3653 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3654 if (subclass == NULL)
3655 continue;
3656 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003657 /* Avoid recursing down into unaffected classes */
3658 dict = subclass->tp_dict;
3659 if (dict != NULL && PyDict_Check(dict) &&
3660 PyDict_GetItem(dict, name) != NULL)
3661 continue;
3662 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003663 return -1;
3664 }
3665 return 0;
3666}
3667
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003668static int
3669slotdef_cmp(const void *aa, const void *bb)
3670{
3671 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3672 int c = a->offset - b->offset;
3673 if (c != 0)
3674 return c;
3675 else
3676 return a - b;
3677}
3678
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003679static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003680init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003681{
3682 slotdef *p;
3683 static int initialized = 0;
3684
3685 if (initialized)
3686 return;
3687 for (p = slotdefs; p->name; p++) {
3688 p->name_strobj = PyString_InternFromString(p->name);
3689 if (!p->name_strobj)
3690 Py_FatalError("XXX ouch");
3691 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003692 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3693 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003694 initialized = 1;
3695}
3696
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003697static int
3698update_slot(PyTypeObject *type, PyObject *name)
3699{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003700 slotdef *ptrs[10];
3701 slotdef *p;
3702 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003703 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003704
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003705 init_slotdefs();
3706 pp = ptrs;
3707 for (p = slotdefs; p->name; p++) {
3708 /* XXX assume name is interned! */
3709 if (p->name_strobj == name)
3710 *pp++ = p;
3711 }
3712 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003713 for (pp = ptrs; *pp; pp++) {
3714 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003715 offset = p->offset;
3716 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003717 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003718 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003719 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003720 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003721}
3722
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003724fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003726 slotdef *p;
3727 PyObject *mro, *descr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003728 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003729 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003730 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003731 void *generic, *specific;
3732 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003733
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003734 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003735 mro = type->tp_mro;
3736 assert(PyTuple_Check(mro));
3737 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003738 for (p = slotdefs; p->name; ) {
3739 offset = p->offset;
3740 ptr = slotptr(type, offset);
3741 if (!ptr) {
3742 do {
3743 ++p;
3744 } while (p->offset == offset);
3745 continue;
3746 }
3747 generic = specific = NULL;
3748 use_generic = 0;
3749 do {
3750 descr = NULL;
3751 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003752 PyObject *b = PyTuple_GET_ITEM(mro, i);
3753 PyObject *dict = NULL;
3754 if (PyType_Check(b))
3755 dict = ((PyTypeObject *)b)->tp_dict;
3756 else if (PyClass_Check(b))
3757 dict = ((PyClassObject *)b)->cl_dict;
3758 if (dict != NULL) {
3759 descr = PyDict_GetItem(
3760 dict, p->name_strobj);
3761 if (descr != NULL)
3762 break;
3763 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003764 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003765 if (descr == NULL)
3766 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003767 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003768 if (descr->ob_type == &PyWrapperDescr_Type) {
3769 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003770 if (d->d_base->wrapper == p->wrapper &&
Guido van Rossumcaf59042001-10-17 07:15:43 +00003771 PyType_IsSubtype(type, d->d_type))
3772 {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003773 if (specific == NULL ||
Guido van Rossumcaf59042001-10-17 07:15:43 +00003774 specific == d->d_wrapped)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003775 specific = d->d_wrapped;
3776 else
3777 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003778 }
3779 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003780 else
3781 use_generic = 1;
3782 } while ((++p)->offset == offset);
3783 if (specific && !use_generic)
3784 *ptr = specific;
3785 else
3786 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003787 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003789
Guido van Rossum6d204072001-10-21 00:44:31 +00003790/* This function is called by PyType_Ready() to populate the type's
3791 dictionary with method descriptors for function slots. For each
3792 function slot (like tp_repr) that's defined in the type, one or
3793 more corresponding descriptors are added in the type's tp_dict
3794 dictionary under the appropriate name (like __repr__). Some
3795 function slots cause more than one descriptor to be added (for
3796 example, the nb_add slot adds both __add__ and __radd__
3797 descriptors) and some function slots compete for the same
3798 descriptor (for example both sq_item and mp_subscript generate a
3799 __getitem__ descriptor). This only adds new descriptors and
3800 doesn't overwrite entries in tp_dict that were previously
3801 defined. The descriptors contain a reference to the C function
3802 they must call, so that it's safe if they are copied into a
3803 subtype's __dict__ and the subtype has a different C function in
3804 its slot -- calling the method defined by the descriptor will call
3805 the C function that was used to create it, rather than the C
3806 function present in the slot when it is called. (This is important
3807 because a subtype may have a C function in the slot that calls the
3808 method from the dictionary, and we want to avoid infinite recursion
3809 here.) */
3810
3811static int
3812add_operators(PyTypeObject *type)
3813{
3814 PyObject *dict = type->tp_dict;
3815 slotdef *p;
3816 PyObject *descr;
3817 void **ptr;
3818
3819 init_slotdefs();
3820 for (p = slotdefs; p->name; p++) {
3821 if (p->wrapper == NULL)
3822 continue;
3823 ptr = slotptr(type, p->offset);
3824 if (!ptr || !*ptr)
3825 continue;
3826 if (PyDict_GetItem(dict, p->name_strobj))
3827 continue;
3828 descr = PyDescr_NewWrapper(type, p, *ptr);
3829 if (descr == NULL)
3830 return -1;
3831 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
3832 return -1;
3833 Py_DECREF(descr);
3834 }
3835 if (type->tp_new != NULL) {
3836 if (add_tp_new_wrapper(type) < 0)
3837 return -1;
3838 }
3839 return 0;
3840}
3841
Guido van Rossum705f0f52001-08-24 16:47:00 +00003842
3843/* Cooperative 'super' */
3844
3845typedef struct {
3846 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003847 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003848 PyObject *obj;
3849} superobject;
3850
Guido van Rossum6f799372001-09-20 20:46:19 +00003851static PyMemberDef super_members[] = {
3852 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3853 "the class invoking super()"},
3854 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3855 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003856 {0}
3857};
3858
Guido van Rossum705f0f52001-08-24 16:47:00 +00003859static void
3860super_dealloc(PyObject *self)
3861{
3862 superobject *su = (superobject *)self;
3863
Guido van Rossum048eb752001-10-02 21:24:57 +00003864 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003865 Py_XDECREF(su->obj);
3866 Py_XDECREF(su->type);
3867 self->ob_type->tp_free(self);
3868}
3869
3870static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003871super_repr(PyObject *self)
3872{
3873 superobject *su = (superobject *)self;
3874
3875 if (su->obj)
3876 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003877 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003878 su->type ? su->type->tp_name : "NULL",
3879 su->obj->ob_type->tp_name);
3880 else
3881 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003882 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003883 su->type ? su->type->tp_name : "NULL");
3884}
3885
3886static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003887super_getattro(PyObject *self, PyObject *name)
3888{
3889 superobject *su = (superobject *)self;
3890
3891 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00003892 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003893 descrgetfunc f;
3894 int i, n;
3895
Guido van Rossume705ef12001-08-29 15:47:06 +00003896 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003897 if (mro == NULL)
3898 n = 0;
3899 else {
3900 assert(PyTuple_Check(mro));
3901 n = PyTuple_GET_SIZE(mro);
3902 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003903 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003904 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003905 break;
3906 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003907 if (i >= n && PyType_Check(su->obj)) {
3908 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003909 if (mro == NULL)
3910 n = 0;
3911 else {
3912 assert(PyTuple_Check(mro));
3913 n = PyTuple_GET_SIZE(mro);
3914 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003915 for (i = 0; i < n; i++) {
3916 if ((PyObject *)(su->type) ==
3917 PyTuple_GET_ITEM(mro, i))
3918 break;
3919 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003920 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003921 i++;
3922 res = NULL;
3923 for (; i < n; i++) {
3924 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00003925 if (PyType_Check(tmp))
3926 dict = ((PyTypeObject *)tmp)->tp_dict;
3927 else if (PyClass_Check(tmp))
3928 dict = ((PyClassObject *)tmp)->cl_dict;
3929 else
3930 continue;
3931 res = PyDict_GetItem(dict, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003932 if (res != NULL) {
3933 Py_INCREF(res);
3934 f = res->ob_type->tp_descr_get;
3935 if (f != NULL) {
3936 tmp = f(res, su->obj, res);
3937 Py_DECREF(res);
3938 res = tmp;
3939 }
3940 return res;
3941 }
3942 }
3943 }
3944 return PyObject_GenericGetAttr(self, name);
3945}
3946
3947static PyObject *
3948super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3949{
3950 superobject *su = (superobject *)self;
3951 superobject *new;
3952
3953 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3954 /* Not binding to an object, or already bound */
3955 Py_INCREF(self);
3956 return self;
3957 }
3958 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3959 if (new == NULL)
3960 return NULL;
3961 Py_INCREF(su->type);
3962 Py_INCREF(obj);
3963 new->type = su->type;
3964 new->obj = obj;
3965 return (PyObject *)new;
3966}
3967
3968static int
3969super_init(PyObject *self, PyObject *args, PyObject *kwds)
3970{
3971 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003972 PyTypeObject *type;
3973 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003974
3975 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3976 return -1;
3977 if (obj == Py_None)
3978 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003979 if (obj != NULL &&
3980 !PyType_IsSubtype(obj->ob_type, type) &&
3981 !(PyType_Check(obj) &&
3982 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003983 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003984 "super(type, obj): "
3985 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003986 return -1;
3987 }
3988 Py_INCREF(type);
3989 Py_XINCREF(obj);
3990 su->type = type;
3991 su->obj = obj;
3992 return 0;
3993}
3994
3995static char super_doc[] =
3996"super(type) -> unbound super object\n"
3997"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003998"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003999"Typical use to call a cooperative superclass method:\n"
4000"class C(B):\n"
4001" def meth(self, arg):\n"
4002" super(C, self).meth(arg)";
4003
Guido van Rossum048eb752001-10-02 21:24:57 +00004004static int
4005super_traverse(PyObject *self, visitproc visit, void *arg)
4006{
4007 superobject *su = (superobject *)self;
4008 int err;
4009
4010#define VISIT(SLOT) \
4011 if (SLOT) { \
4012 err = visit((PyObject *)(SLOT), arg); \
4013 if (err) \
4014 return err; \
4015 }
4016
4017 VISIT(su->obj);
4018 VISIT(su->type);
4019
4020#undef VISIT
4021
4022 return 0;
4023}
4024
Guido van Rossum705f0f52001-08-24 16:47:00 +00004025PyTypeObject PySuper_Type = {
4026 PyObject_HEAD_INIT(&PyType_Type)
4027 0, /* ob_size */
4028 "super", /* tp_name */
4029 sizeof(superobject), /* tp_basicsize */
4030 0, /* tp_itemsize */
4031 /* methods */
4032 super_dealloc, /* tp_dealloc */
4033 0, /* tp_print */
4034 0, /* tp_getattr */
4035 0, /* tp_setattr */
4036 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004037 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004038 0, /* tp_as_number */
4039 0, /* tp_as_sequence */
4040 0, /* tp_as_mapping */
4041 0, /* tp_hash */
4042 0, /* tp_call */
4043 0, /* tp_str */
4044 super_getattro, /* tp_getattro */
4045 0, /* tp_setattro */
4046 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004047 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4048 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004049 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004050 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004051 0, /* tp_clear */
4052 0, /* tp_richcompare */
4053 0, /* tp_weaklistoffset */
4054 0, /* tp_iter */
4055 0, /* tp_iternext */
4056 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004057 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004058 0, /* tp_getset */
4059 0, /* tp_base */
4060 0, /* tp_dict */
4061 super_descr_get, /* tp_descr_get */
4062 0, /* tp_descr_set */
4063 0, /* tp_dictoffset */
4064 super_init, /* tp_init */
4065 PyType_GenericAlloc, /* tp_alloc */
4066 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004067 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004068};