blob: deb73201ebb7c5444b1d7a0c4605f14ac8cb6851 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum6f799372001-09-20 20:46:19 +00006static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00007 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
8 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
9 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000010 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000011 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
12 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
13 {"__dictoffset__", T_LONG,
14 offsetof(PyTypeObject, tp_dictoffset), READONLY},
15 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
16 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
17 {0}
18};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000019
Guido van Rossumc0b618a1997-05-02 03:12:38 +000020static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000021type_name(PyTypeObject *type, void *context)
22{
23 char *s;
24
25 s = strrchr(type->tp_name, '.');
26 if (s == NULL)
27 s = type->tp_name;
28 else
29 s++;
30 return PyString_FromString(s);
31}
32
33static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000034type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000035{
Guido van Rossumc3542212001-08-16 09:18:56 +000036 PyObject *mod;
37 char *s;
38
39 s = strrchr(type->tp_name, '.');
40 if (s != NULL)
41 return PyString_FromStringAndSize(type->tp_name,
42 (int)(s - type->tp_name));
43 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
44 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000045 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000046 if (mod != NULL && PyString_Check(mod)) {
47 Py_INCREF(mod);
48 return mod;
49 }
50 PyErr_SetString(PyExc_AttributeError, "__module__");
51 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000052}
53
Guido van Rossum3926a632001-09-25 16:25:58 +000054static int
55type_set_module(PyTypeObject *type, PyObject *value, void *context)
56{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000057 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000058 strrchr(type->tp_name, '.')) {
59 PyErr_Format(PyExc_TypeError,
60 "can't set %s.__module__", type->tp_name);
61 return -1;
62 }
63 if (!value) {
64 PyErr_Format(PyExc_TypeError,
65 "can't delete %s.__module__", type->tp_name);
66 return -1;
67 }
68 return PyDict_SetItemString(type->tp_dict, "__module__", value);
69}
70
Tim Peters6d6c1a32001-08-02 04:15:00 +000071static PyObject *
72type_dict(PyTypeObject *type, void *context)
73{
74 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 Py_INCREF(Py_None);
76 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000077 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000078 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079}
80
Tim Peters24008312002-03-17 18:56:20 +000081static PyObject *
82type_get_doc(PyTypeObject *type, void *context)
83{
84 PyObject *result;
85 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
86 if (type->tp_doc == NULL) {
87 Py_INCREF(Py_None);
88 return Py_None;
89 }
90 return PyString_FromString(type->tp_doc);
91 }
92 result = PyDict_GetItemString(type->tp_dict, "__doc__");
93 Py_INCREF(result);
94 return result;
95}
96
Neil Schemenauerf23473f2001-10-21 22:28:58 +000097static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000098 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +000099 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000101 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000102 {0}
103};
104
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000105static int
106type_compare(PyObject *v, PyObject *w)
107{
108 /* This is called with type objects only. So we
109 can just compare the addresses. */
110 Py_uintptr_t vv = (Py_uintptr_t)v;
111 Py_uintptr_t ww = (Py_uintptr_t)w;
112 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
113}
114
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000116type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000118 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000119 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000120
121 mod = type_module(type, NULL);
122 if (mod == NULL)
123 PyErr_Clear();
124 else if (!PyString_Check(mod)) {
125 Py_DECREF(mod);
126 mod = NULL;
127 }
128 name = type_name(type, NULL);
129 if (name == NULL)
130 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000131
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000132 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
133 kind = "class";
134 else
135 kind = "type";
136
Barry Warsaw7ce36942001-08-24 18:34:26 +0000137 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000138 rtn = PyString_FromFormat("<%s '%s.%s'>",
139 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000140 PyString_AS_STRING(mod),
141 PyString_AS_STRING(name));
142 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000143 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000144 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000145
Guido van Rossumc3542212001-08-16 09:18:56 +0000146 Py_XDECREF(mod);
147 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000148 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149}
150
Tim Peters6d6c1a32001-08-02 04:15:00 +0000151static PyObject *
152type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
153{
154 PyObject *obj;
155
156 if (type->tp_new == NULL) {
157 PyErr_Format(PyExc_TypeError,
158 "cannot create '%.100s' instances",
159 type->tp_name);
160 return NULL;
161 }
162
Tim Peters3f996e72001-09-13 19:18:27 +0000163 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000164 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000165 /* Ugly exception: when the call was type(something),
166 don't call tp_init on the result. */
167 if (type == &PyType_Type &&
168 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
169 (kwds == NULL ||
170 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
171 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000172 /* If the returned object is not an instance of type,
173 it won't be initialized. */
174 if (!PyType_IsSubtype(obj->ob_type, type))
175 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000176 type = obj->ob_type;
177 if (type->tp_init != NULL &&
178 type->tp_init(obj, args, kwds) < 0) {
179 Py_DECREF(obj);
180 obj = NULL;
181 }
182 }
183 return obj;
184}
185
186PyObject *
187PyType_GenericAlloc(PyTypeObject *type, int nitems)
188{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000189 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000190 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000191
192 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000193 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000194 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000195 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000196
Neil Schemenauerc806c882001-08-29 23:54:54 +0000197 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000198 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000199
Neil Schemenauerc806c882001-08-29 23:54:54 +0000200 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000201
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
203 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000204
Tim Peters6d6c1a32001-08-02 04:15:00 +0000205 if (type->tp_itemsize == 0)
206 PyObject_INIT(obj, type);
207 else
208 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000209
Tim Peters6d6c1a32001-08-02 04:15:00 +0000210 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000211 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000212 return obj;
213}
214
215PyObject *
216PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
217{
218 return type->tp_alloc(type, 0);
219}
220
Guido van Rossum9475a232001-10-05 20:51:39 +0000221/* Helpers for subtyping */
222
223static int
224subtype_traverse(PyObject *self, visitproc visit, void *arg)
225{
226 PyTypeObject *type, *base;
227 traverseproc f;
228 int err;
229
230 /* Find the nearest base with a different tp_traverse */
231 type = self->ob_type;
232 base = type->tp_base;
233 while ((f = base->tp_traverse) == subtype_traverse) {
234 base = base->tp_base;
235 assert(base);
236 }
237
238 if (type->tp_dictoffset != base->tp_dictoffset) {
239 PyObject **dictptr = _PyObject_GetDictPtr(self);
240 if (dictptr && *dictptr) {
241 err = visit(*dictptr, arg);
242 if (err)
243 return err;
244 }
245 }
246
247 if (f)
248 return f(self, visit, arg);
249 return 0;
250}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000251
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000252staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
253
254static int
255call_finalizer(PyObject *self)
256{
257 static PyObject *del_str = NULL;
258 PyObject *del, *res;
259 PyObject *error_type, *error_value, *error_traceback;
260
261 /* Temporarily resurrect the object. */
262#ifdef Py_TRACE_REFS
263#ifndef Py_REF_DEBUG
264# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
265#endif
266 /* much too complicated if Py_TRACE_REFS defined */
267 _Py_NewReference((PyObject *)self);
268#ifdef COUNT_ALLOCS
269 /* compensate for boost in _Py_NewReference; note that
270 * _Py_RefTotal was also boosted; we'll knock that down later.
271 */
272 self->ob_type->tp_allocs--;
273#endif
274#else /* !Py_TRACE_REFS */
275 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
276 Py_INCREF(self);
277#endif /* !Py_TRACE_REFS */
278
279 /* Save the current exception, if any. */
280 PyErr_Fetch(&error_type, &error_value, &error_traceback);
281
282 /* Execute __del__ method, if any. */
283 del = lookup_maybe(self, "__del__", &del_str);
284 if (del != NULL) {
285 res = PyEval_CallObject(del, NULL);
286 if (res == NULL)
287 PyErr_WriteUnraisable(del);
288 else
289 Py_DECREF(res);
290 Py_DECREF(del);
291 }
292
293 /* Restore the saved exception. */
294 PyErr_Restore(error_type, error_value, error_traceback);
295
296 /* Undo the temporary resurrection; can't use DECREF here, it would
297 * cause a recursive call.
298 */
299#ifdef Py_REF_DEBUG
300 /* _Py_RefTotal was boosted either by _Py_NewReference or
301 * Py_INCREF above.
302 */
303 _Py_RefTotal--;
304#endif
305 if (--self->ob_refcnt > 0) {
306#ifdef COUNT_ALLOCS
307 self->ob_type->tp_frees--;
308#endif
309 _PyObject_GC_TRACK(self);
310 return -1; /* __del__ added a reference; don't delete now */
311 }
312#ifdef Py_TRACE_REFS
313 _Py_ForgetReference((PyObject *)self);
314#ifdef COUNT_ALLOCS
315 /* compensate for increment in _Py_ForgetReference */
316 self->ob_type->tp_frees--;
317#endif
318#endif
319
320 return 0;
321}
322
Tim Peters6d6c1a32001-08-02 04:15:00 +0000323static void
324subtype_dealloc(PyObject *self)
325{
Guido van Rossum14227b42001-12-06 02:35:58 +0000326 PyTypeObject *type, *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000327 destructor f;
328
329 /* This exists so we can DECREF self->ob_type */
330
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000331 if (call_finalizer(self) < 0)
332 return;
333
Tim Peters6d6c1a32001-08-02 04:15:00 +0000334 /* Find the nearest base with a different tp_dealloc */
335 type = self->ob_type;
Guido van Rossum14227b42001-12-06 02:35:58 +0000336 base = type->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000337 while ((f = base->tp_dealloc) == subtype_dealloc) {
338 base = base->tp_base;
339 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000340 }
341
342 /* Clear __slots__ variables */
343 if (type->tp_basicsize != base->tp_basicsize &&
344 type->tp_itemsize == 0)
345 {
346 char *addr = ((char *)self);
347 char *p = addr + base->tp_basicsize;
348 char *q = addr + type->tp_basicsize;
349 for (; p < q; p += sizeof(PyObject *)) {
350 PyObject **pp;
351 if (p == addr + type->tp_dictoffset ||
352 p == addr + type->tp_weaklistoffset)
353 continue;
354 pp = (PyObject **)p;
355 if (*pp != NULL) {
356 Py_DECREF(*pp);
357 *pp = NULL;
Guido van Rossum33bab012001-12-05 22:45:48 +0000358 }
359 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000360 }
361
362 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000363 if (type->tp_dictoffset && !base->tp_dictoffset) {
364 PyObject **dictptr = _PyObject_GetDictPtr(self);
365 if (dictptr != NULL) {
366 PyObject *dict = *dictptr;
367 if (dict != NULL) {
368 Py_DECREF(dict);
369 *dictptr = NULL;
370 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371 }
372 }
373
Guido van Rossum9676b222001-08-17 20:32:36 +0000374 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000375 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000376 PyObject_ClearWeakRefs(self);
377
Tim Peters6d6c1a32001-08-02 04:15:00 +0000378 /* Finalize GC if the base doesn't do GC and we do */
379 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000380 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000381
382 /* Call the base tp_dealloc() */
383 assert(f);
384 f(self);
385
386 /* Can't reference self beyond this point */
387 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
388 Py_DECREF(type);
389 }
390}
391
Tim Peters6d6c1a32001-08-02 04:15:00 +0000392staticforward PyTypeObject *solid_base(PyTypeObject *type);
393
394typedef struct {
395 PyTypeObject type;
396 PyNumberMethods as_number;
397 PySequenceMethods as_sequence;
398 PyMappingMethods as_mapping;
399 PyBufferProcs as_buffer;
400 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000401 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000402} etype;
403
404/* type test with subclassing support */
405
406int
407PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
408{
409 PyObject *mro;
410
Guido van Rossum9478d072001-09-07 18:52:13 +0000411 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
412 return b == a || b == &PyBaseObject_Type;
413
Tim Peters6d6c1a32001-08-02 04:15:00 +0000414 mro = a->tp_mro;
415 if (mro != NULL) {
416 /* Deal with multiple inheritance without recursion
417 by walking the MRO tuple */
418 int i, n;
419 assert(PyTuple_Check(mro));
420 n = PyTuple_GET_SIZE(mro);
421 for (i = 0; i < n; i++) {
422 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
423 return 1;
424 }
425 return 0;
426 }
427 else {
428 /* a is not completely initilized yet; follow tp_base */
429 do {
430 if (a == b)
431 return 1;
432 a = a->tp_base;
433 } while (a != NULL);
434 return b == &PyBaseObject_Type;
435 }
436}
437
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000438/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000439 without looking in the instance dictionary
440 (so we can't use PyObject_GetAttr) but still binding
441 it to the instance. The arguments are the object,
442 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000443 static variable used to cache the interned Python string.
444
445 Two variants:
446
447 - lookup_maybe() returns NULL without raising an exception
448 when the _PyType_Lookup() call fails;
449
450 - lookup_method() always raises an exception upon errors.
451*/
Guido van Rossum60718732001-08-28 17:47:51 +0000452
453static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000454lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000455{
456 PyObject *res;
457
458 if (*attrobj == NULL) {
459 *attrobj = PyString_InternFromString(attrstr);
460 if (*attrobj == NULL)
461 return NULL;
462 }
463 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000464 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000465 descrgetfunc f;
466 if ((f = res->ob_type->tp_descr_get) == NULL)
467 Py_INCREF(res);
468 else
469 res = f(res, self, (PyObject *)(self->ob_type));
470 }
471 return res;
472}
473
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000474static PyObject *
475lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
476{
477 PyObject *res = lookup_maybe(self, attrstr, attrobj);
478 if (res == NULL && !PyErr_Occurred())
479 PyErr_SetObject(PyExc_AttributeError, *attrobj);
480 return res;
481}
482
Guido van Rossum2730b132001-08-28 18:22:14 +0000483/* A variation of PyObject_CallMethod that uses lookup_method()
484 instead of PyObject_GetAttrString(). This uses the same convention
485 as lookup_method to cache the interned name string object. */
486
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000487static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000488call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
489{
490 va_list va;
491 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000492 va_start(va, format);
493
Guido van Rossumda21c012001-10-03 00:50:18 +0000494 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000495 if (func == NULL) {
496 va_end(va);
497 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000498 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000499 return NULL;
500 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000501
502 if (format && *format)
503 args = Py_VaBuildValue(format, va);
504 else
505 args = PyTuple_New(0);
506
507 va_end(va);
508
509 if (args == NULL)
510 return NULL;
511
512 assert(PyTuple_Check(args));
513 retval = PyObject_Call(func, args, NULL);
514
515 Py_DECREF(args);
516 Py_DECREF(func);
517
518 return retval;
519}
520
521/* Clone of call_method() that returns NotImplemented when the lookup fails. */
522
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000523static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000524call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
525{
526 va_list va;
527 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000528 va_start(va, format);
529
Guido van Rossumda21c012001-10-03 00:50:18 +0000530 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000531 if (func == NULL) {
532 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000533 if (!PyErr_Occurred()) {
534 Py_INCREF(Py_NotImplemented);
535 return Py_NotImplemented;
536 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000537 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000538 }
539
540 if (format && *format)
541 args = Py_VaBuildValue(format, va);
542 else
543 args = PyTuple_New(0);
544
545 va_end(va);
546
Guido van Rossum717ce002001-09-14 16:58:08 +0000547 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000548 return NULL;
549
Guido van Rossum717ce002001-09-14 16:58:08 +0000550 assert(PyTuple_Check(args));
551 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000552
553 Py_DECREF(args);
554 Py_DECREF(func);
555
556 return retval;
557}
558
Tim Peters6d6c1a32001-08-02 04:15:00 +0000559/* Method resolution order algorithm from "Putting Metaclasses to Work"
560 by Forman and Danforth (Addison-Wesley 1999). */
561
562static int
563conservative_merge(PyObject *left, PyObject *right)
564{
565 int left_size;
566 int right_size;
567 int i, j, r, ok;
568 PyObject *temp, *rr;
569
570 assert(PyList_Check(left));
571 assert(PyList_Check(right));
572
573 again:
574 left_size = PyList_GET_SIZE(left);
575 right_size = PyList_GET_SIZE(right);
576 for (i = 0; i < left_size; i++) {
577 for (j = 0; j < right_size; j++) {
578 if (PyList_GET_ITEM(left, i) ==
579 PyList_GET_ITEM(right, j)) {
580 /* found a merge point */
581 temp = PyList_New(0);
582 if (temp == NULL)
583 return -1;
584 for (r = 0; r < j; r++) {
585 rr = PyList_GET_ITEM(right, r);
586 ok = PySequence_Contains(left, rr);
587 if (ok < 0) {
588 Py_DECREF(temp);
589 return -1;
590 }
591 if (!ok) {
592 ok = PyList_Append(temp, rr);
593 if (ok < 0) {
594 Py_DECREF(temp);
595 return -1;
596 }
597 }
598 }
599 ok = PyList_SetSlice(left, i, i, temp);
600 Py_DECREF(temp);
601 if (ok < 0)
602 return -1;
603 ok = PyList_SetSlice(right, 0, j+1, NULL);
604 if (ok < 0)
605 return -1;
606 goto again;
607 }
608 }
609 }
610 return PyList_SetSlice(left, left_size, left_size, right);
611}
612
613static int
614serious_order_disagreements(PyObject *left, PyObject *right)
615{
616 return 0; /* XXX later -- for now, we cheat: "don't do that" */
617}
618
Tim Petersa91e9642001-11-14 23:32:33 +0000619static int
620fill_classic_mro(PyObject *mro, PyObject *cls)
621{
622 PyObject *bases, *base;
623 int i, n;
624
625 assert(PyList_Check(mro));
626 assert(PyClass_Check(cls));
627 i = PySequence_Contains(mro, cls);
628 if (i < 0)
629 return -1;
630 if (!i) {
631 if (PyList_Append(mro, cls) < 0)
632 return -1;
633 }
634 bases = ((PyClassObject *)cls)->cl_bases;
635 assert(bases && PyTuple_Check(bases));
636 n = PyTuple_GET_SIZE(bases);
637 for (i = 0; i < n; i++) {
638 base = PyTuple_GET_ITEM(bases, i);
639 if (fill_classic_mro(mro, base) < 0)
640 return -1;
641 }
642 return 0;
643}
644
645static PyObject *
646classic_mro(PyObject *cls)
647{
648 PyObject *mro;
649
650 assert(PyClass_Check(cls));
651 mro = PyList_New(0);
652 if (mro != NULL) {
653 if (fill_classic_mro(mro, cls) == 0)
654 return mro;
655 Py_DECREF(mro);
656 }
657 return NULL;
658}
659
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660static PyObject *
661mro_implementation(PyTypeObject *type)
662{
663 int i, n, ok;
664 PyObject *bases, *result;
665
666 bases = type->tp_bases;
667 n = PyTuple_GET_SIZE(bases);
668 result = Py_BuildValue("[O]", (PyObject *)type);
669 if (result == NULL)
670 return NULL;
671 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000672 PyObject *base = PyTuple_GET_ITEM(bases, i);
673 PyObject *parentMRO;
674 if (PyType_Check(base))
675 parentMRO = PySequence_List(
676 ((PyTypeObject*)base)->tp_mro);
677 else
678 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679 if (parentMRO == NULL) {
680 Py_DECREF(result);
681 return NULL;
682 }
683 if (serious_order_disagreements(result, parentMRO)) {
684 Py_DECREF(result);
685 return NULL;
686 }
687 ok = conservative_merge(result, parentMRO);
688 Py_DECREF(parentMRO);
689 if (ok < 0) {
690 Py_DECREF(result);
691 return NULL;
692 }
693 }
694 return result;
695}
696
697static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000698mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699{
700 PyTypeObject *type = (PyTypeObject *)self;
701
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702 return mro_implementation(type);
703}
704
705static int
706mro_internal(PyTypeObject *type)
707{
708 PyObject *mro, *result, *tuple;
709
710 if (type->ob_type == &PyType_Type) {
711 result = mro_implementation(type);
712 }
713 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000714 static PyObject *mro_str;
715 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000716 if (mro == NULL)
717 return -1;
718 result = PyObject_CallObject(mro, NULL);
719 Py_DECREF(mro);
720 }
721 if (result == NULL)
722 return -1;
723 tuple = PySequence_Tuple(result);
724 Py_DECREF(result);
725 type->tp_mro = tuple;
726 return 0;
727}
728
729
730/* Calculate the best base amongst multiple base classes.
731 This is the first one that's on the path to the "solid base". */
732
733static PyTypeObject *
734best_base(PyObject *bases)
735{
736 int i, n;
737 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000738 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739
740 assert(PyTuple_Check(bases));
741 n = PyTuple_GET_SIZE(bases);
742 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000743 base = NULL;
744 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000745 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000746 base_proto = PyTuple_GET_ITEM(bases, i);
747 if (PyClass_Check(base_proto))
748 continue;
749 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750 PyErr_SetString(
751 PyExc_TypeError,
752 "bases must be types");
753 return NULL;
754 }
Tim Petersa91e9642001-11-14 23:32:33 +0000755 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000756 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000757 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758 return NULL;
759 }
760 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000761 if (winner == NULL) {
762 winner = candidate;
763 base = base_i;
764 }
765 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000766 ;
767 else if (PyType_IsSubtype(candidate, winner)) {
768 winner = candidate;
769 base = base_i;
770 }
771 else {
772 PyErr_SetString(
773 PyExc_TypeError,
774 "multiple bases have "
775 "instance lay-out conflict");
776 return NULL;
777 }
778 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000779 if (base == NULL)
780 PyErr_SetString(PyExc_TypeError,
781 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000782 return base;
783}
784
785static int
786extra_ivars(PyTypeObject *type, PyTypeObject *base)
787{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000788 size_t t_size = type->tp_basicsize;
789 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790
Guido van Rossum9676b222001-08-17 20:32:36 +0000791 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792 if (type->tp_itemsize || base->tp_itemsize) {
793 /* If itemsize is involved, stricter rules */
794 return t_size != b_size ||
795 type->tp_itemsize != base->tp_itemsize;
796 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000797 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
798 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
799 t_size -= sizeof(PyObject *);
800 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
801 type->tp_dictoffset + sizeof(PyObject *) == t_size)
802 t_size -= sizeof(PyObject *);
803
804 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000805}
806
807static PyTypeObject *
808solid_base(PyTypeObject *type)
809{
810 PyTypeObject *base;
811
812 if (type->tp_base)
813 base = solid_base(type->tp_base);
814 else
815 base = &PyBaseObject_Type;
816 if (extra_ivars(type, base))
817 return type;
818 else
819 return base;
820}
821
822staticforward void object_dealloc(PyObject *);
823staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000824staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000825staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000826
827static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000828subtype_dict(PyObject *obj, void *context)
829{
830 PyObject **dictptr = _PyObject_GetDictPtr(obj);
831 PyObject *dict;
832
833 if (dictptr == NULL) {
834 PyErr_SetString(PyExc_AttributeError,
835 "This object has no __dict__");
836 return NULL;
837 }
838 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000839 if (dict == NULL)
840 *dictptr = dict = PyDict_New();
841 Py_XINCREF(dict);
842 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000843}
844
Guido van Rossum6661be32001-10-26 04:26:12 +0000845static int
846subtype_setdict(PyObject *obj, PyObject *value, void *context)
847{
848 PyObject **dictptr = _PyObject_GetDictPtr(obj);
849 PyObject *dict;
850
851 if (dictptr == NULL) {
852 PyErr_SetString(PyExc_AttributeError,
853 "This object has no __dict__");
854 return -1;
855 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000856 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000857 PyErr_SetString(PyExc_TypeError,
858 "__dict__ must be set to a dictionary");
859 return -1;
860 }
861 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000862 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000863 *dictptr = value;
864 Py_XDECREF(dict);
865 return 0;
866}
867
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000868static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000869 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000870 {0},
871};
872
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000873/* bozo: __getstate__ that raises TypeError */
874
875static PyObject *
876bozo_func(PyObject *self, PyObject *args)
877{
878 PyErr_SetString(PyExc_TypeError,
879 "a class that defines __slots__ without "
880 "defining __getstate__ cannot be pickled");
881 return NULL;
882}
883
Neal Norwitz93c1e232002-03-31 16:06:11 +0000884static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000885
886static PyObject *bozo_obj = NULL;
887
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000888static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
890{
891 PyObject *name, *bases, *dict;
892 static char *kwlist[] = {"name", "bases", "dict", 0};
893 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000894 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000896 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000897 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000898
Tim Peters3abca122001-10-27 19:37:48 +0000899 assert(args != NULL && PyTuple_Check(args));
900 assert(kwds == NULL || PyDict_Check(kwds));
901
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000902 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000903 {
904 const int nargs = PyTuple_GET_SIZE(args);
905 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
906
907 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
908 PyObject *x = PyTuple_GET_ITEM(args, 0);
909 Py_INCREF(x->ob_type);
910 return (PyObject *) x->ob_type;
911 }
912
913 /* SF bug 475327 -- if that didn't trigger, we need 3
914 arguments. but PyArg_ParseTupleAndKeywords below may give
915 a msg saying type() needs exactly 3. */
916 if (nargs + nkwds != 3) {
917 PyErr_SetString(PyExc_TypeError,
918 "type() takes 1 or 3 arguments");
919 return NULL;
920 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000921 }
922
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000923 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000924 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
925 &name,
926 &PyTuple_Type, &bases,
927 &PyDict_Type, &dict))
928 return NULL;
929
930 /* Determine the proper metatype to deal with this,
931 and check for metatype conflicts while we're at it.
932 Note that if some other metatype wins to contract,
933 it's possible that its instances are not types. */
934 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000935 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000936 for (i = 0; i < nbases; i++) {
937 tmp = PyTuple_GET_ITEM(bases, i);
938 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000939 if (tmptype == &PyClass_Type)
940 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000941 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000942 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000943 if (PyType_IsSubtype(tmptype, winner)) {
944 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000945 continue;
946 }
947 PyErr_SetString(PyExc_TypeError,
948 "metatype conflict among bases");
949 return NULL;
950 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000951 if (winner != metatype) {
952 if (winner->tp_new != type_new) /* Pass it to the winner */
953 return winner->tp_new(winner, args, kwds);
954 metatype = winner;
955 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000956
957 /* Adjust for empty tuple bases */
958 if (nbases == 0) {
959 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
960 if (bases == NULL)
961 return NULL;
962 nbases = 1;
963 }
964 else
965 Py_INCREF(bases);
966
967 /* XXX From here until type is allocated, "return NULL" leaks bases! */
968
969 /* Calculate best base, and check that all bases are type objects */
970 base = best_base(bases);
971 if (base == NULL)
972 return NULL;
973 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
974 PyErr_Format(PyExc_TypeError,
975 "type '%.100s' is not an acceptable base type",
976 base->tp_name);
977 return NULL;
978 }
979
Tim Peters6d6c1a32001-08-02 04:15:00 +0000980 /* Check for a __slots__ sequence variable in dict, and count it */
981 slots = PyDict_GetItemString(dict, "__slots__");
982 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000983 add_dict = 0;
984 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 if (slots != NULL) {
986 /* Make it into a tuple */
987 if (PyString_Check(slots))
988 slots = Py_BuildValue("(O)", slots);
989 else
990 slots = PySequence_Tuple(slots);
991 if (slots == NULL)
992 return NULL;
993 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000994 if (nslots > 0 && base->tp_itemsize != 0) {
995 PyErr_Format(PyExc_TypeError,
996 "nonempty __slots__ "
997 "not supported for subtype of '%s'",
998 base->tp_name);
999 return NULL;
1000 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001 for (i = 0; i < nslots; i++) {
1002 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
1003 PyErr_SetString(PyExc_TypeError,
1004 "__slots__ must be a sequence of strings");
1005 Py_DECREF(slots);
1006 return NULL;
1007 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001008 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009 }
1010 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001011 if (slots != NULL) {
1012 /* See if *this* class defines __getstate__ */
1013 PyObject *getstate = PyDict_GetItemString(dict,
1014 "__getstate__");
1015 if (getstate == NULL) {
1016 /* If not, provide a bozo that raises TypeError */
1017 if (bozo_obj == NULL) {
1018 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1019 if (bozo_obj == NULL) {
1020 /* XXX decref various things */
1021 return NULL;
1022 }
1023 }
1024 if (PyDict_SetItemString(dict,
1025 "__getstate__",
1026 bozo_obj) < 0) {
1027 /* XXX decref various things */
1028 return NULL;
1029 }
1030 }
1031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032 if (slots == NULL && base->tp_dictoffset == 0 &&
1033 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001034 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001035 add_dict++;
1036 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001037 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1038 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001039 nslots++;
1040 add_weak++;
1041 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042
1043 /* XXX From here until type is safely allocated,
1044 "return NULL" may leak slots! */
1045
1046 /* Allocate the type object */
1047 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1048 if (type == NULL)
1049 return NULL;
1050
1051 /* Keep name and slots alive in the extended type object */
1052 et = (etype *)type;
1053 Py_INCREF(name);
1054 et->name = name;
1055 et->slots = slots;
1056
Guido van Rossumdc91b992001-08-08 22:26:22 +00001057 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001058 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1059 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001060 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1061 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001062
1063 /* It's a new-style number unless it specifically inherits any
1064 old-style numeric behavior */
1065 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1066 (base->tp_as_number == NULL))
1067 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1068
1069 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070 type->tp_as_number = &et->as_number;
1071 type->tp_as_sequence = &et->as_sequence;
1072 type->tp_as_mapping = &et->as_mapping;
1073 type->tp_as_buffer = &et->as_buffer;
1074 type->tp_name = PyString_AS_STRING(name);
1075
1076 /* Set tp_base and tp_bases */
1077 type->tp_bases = bases;
1078 Py_INCREF(base);
1079 type->tp_base = base;
1080
Guido van Rossum687ae002001-10-15 22:03:32 +00001081 /* Initialize tp_dict from passed-in dict */
1082 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 if (dict == NULL) {
1084 Py_DECREF(type);
1085 return NULL;
1086 }
1087
Guido van Rossumc3542212001-08-16 09:18:56 +00001088 /* Set __module__ in the dict */
1089 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1090 tmp = PyEval_GetGlobals();
1091 if (tmp != NULL) {
1092 tmp = PyDict_GetItemString(tmp, "__name__");
1093 if (tmp != NULL) {
1094 if (PyDict_SetItemString(dict, "__module__",
1095 tmp) < 0)
1096 return NULL;
1097 }
1098 }
1099 }
1100
Tim Peters2f93e282001-10-04 05:27:00 +00001101 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001102 and is a string. The __doc__ accessor will first look for tp_doc;
1103 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001104 */
1105 {
1106 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1107 if (doc != NULL && PyString_Check(doc)) {
1108 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001109 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001110 if (type->tp_doc == NULL) {
1111 Py_DECREF(type);
1112 return NULL;
1113 }
1114 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1115 }
1116 }
1117
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118 /* Special-case __new__: if it's a plain function,
1119 make it a static function */
1120 tmp = PyDict_GetItemString(dict, "__new__");
1121 if (tmp != NULL && PyFunction_Check(tmp)) {
1122 tmp = PyStaticMethod_New(tmp);
1123 if (tmp == NULL) {
1124 Py_DECREF(type);
1125 return NULL;
1126 }
1127 PyDict_SetItemString(dict, "__new__", tmp);
1128 Py_DECREF(tmp);
1129 }
1130
1131 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1132 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001133 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001134 if (slots != NULL) {
1135 for (i = 0; i < nslots; i++, mp++) {
1136 mp->name = PyString_AS_STRING(
1137 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001138 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001140 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001141 strcmp(mp->name, "__weakref__") == 0) {
1142 mp->type = T_OBJECT;
Guido van Rossum9676b222001-08-17 20:32:36 +00001143 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001144 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001145 slotoffset += sizeof(PyObject *);
1146 }
1147 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001148 else {
1149 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001150 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001151 type->tp_dictoffset =
1152 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001153 else
1154 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001155 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001156 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001157 }
1158 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001159 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001160 type->tp_weaklistoffset = slotoffset;
1161 mp->name = "__weakref__";
1162 mp->type = T_OBJECT;
1163 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001164 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001165 mp++;
1166 slotoffset += sizeof(PyObject *);
1167 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168 }
1169 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001170 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001171 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001172
1173 /* Special case some slots */
1174 if (type->tp_dictoffset != 0 || nslots > 0) {
1175 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1176 type->tp_getattro = PyObject_GenericGetAttr;
1177 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1178 type->tp_setattro = PyObject_GenericSetAttr;
1179 }
1180 type->tp_dealloc = subtype_dealloc;
1181
Guido van Rossum9475a232001-10-05 20:51:39 +00001182 /* Enable GC unless there are really no instance variables possible */
1183 if (!(type->tp_basicsize == sizeof(PyObject) &&
1184 type->tp_itemsize == 0))
1185 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1186
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 /* Always override allocation strategy to use regular heap */
1188 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001189 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001190 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001191 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001192 type->tp_clear = base->tp_clear;
1193 }
1194 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001195 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196
1197 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001198 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 Py_DECREF(type);
1200 return NULL;
1201 }
1202
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001203 /* Put the proper slots in place */
1204 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001205
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206 return (PyObject *)type;
1207}
1208
1209/* Internal API to look for a name through the MRO.
1210 This returns a borrowed reference, and doesn't set an exception! */
1211PyObject *
1212_PyType_Lookup(PyTypeObject *type, PyObject *name)
1213{
1214 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001215 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216
Guido van Rossum687ae002001-10-15 22:03:32 +00001217 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 mro = type->tp_mro;
1219 assert(PyTuple_Check(mro));
1220 n = PyTuple_GET_SIZE(mro);
1221 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001222 base = PyTuple_GET_ITEM(mro, i);
1223 if (PyClass_Check(base))
1224 dict = ((PyClassObject *)base)->cl_dict;
1225 else {
1226 assert(PyType_Check(base));
1227 dict = ((PyTypeObject *)base)->tp_dict;
1228 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229 assert(dict && PyDict_Check(dict));
1230 res = PyDict_GetItem(dict, name);
1231 if (res != NULL)
1232 return res;
1233 }
1234 return NULL;
1235}
1236
1237/* This is similar to PyObject_GenericGetAttr(),
1238 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1239static PyObject *
1240type_getattro(PyTypeObject *type, PyObject *name)
1241{
1242 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001243 PyObject *meta_attribute, *attribute;
1244 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245
1246 /* Initialize this type (we'll assume the metatype is initialized) */
1247 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001248 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 return NULL;
1250 }
1251
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001252 /* No readable descriptor found yet */
1253 meta_get = NULL;
1254
1255 /* Look for the attribute in the metatype */
1256 meta_attribute = _PyType_Lookup(metatype, name);
1257
1258 if (meta_attribute != NULL) {
1259 meta_get = meta_attribute->ob_type->tp_descr_get;
1260
1261 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1262 /* Data descriptors implement tp_descr_set to intercept
1263 * writes. Assume the attribute is not overridden in
1264 * type's tp_dict (and bases): call the descriptor now.
1265 */
1266 return meta_get(meta_attribute, (PyObject *)type,
1267 (PyObject *)metatype);
1268 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001269 }
1270
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001271 /* No data descriptor found on metatype. Look in tp_dict of this
1272 * type and its bases */
1273 attribute = _PyType_Lookup(type, name);
1274 if (attribute != NULL) {
1275 /* Implement descriptor functionality, if any */
1276 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1277 if (local_get != NULL) {
1278 /* NULL 2nd argument indicates the descriptor was
1279 * found on the target object itself (or a base) */
1280 return local_get(attribute, (PyObject *)NULL,
1281 (PyObject *)type);
1282 }
1283
1284 Py_INCREF(attribute);
1285 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286 }
1287
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001288 /* No attribute found in local __dict__ (or bases): use the
1289 * descriptor from the metatype, if any */
1290 if (meta_get != NULL)
1291 return meta_get(meta_attribute, (PyObject *)type,
1292 (PyObject *)metatype);
1293
1294 /* If an ordinary attribute was found on the metatype, return it now */
1295 if (meta_attribute != NULL) {
1296 Py_INCREF(meta_attribute);
1297 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298 }
1299
1300 /* Give up */
1301 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001302 "type object '%.50s' has no attribute '%.400s'",
1303 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 return NULL;
1305}
1306
1307static int
1308type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1309{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001310 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1311 PyErr_Format(
1312 PyExc_TypeError,
1313 "can't set attributes of built-in/extension type '%s'",
1314 type->tp_name);
1315 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001316 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001317 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1318 return -1;
1319 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001320}
1321
1322static void
1323type_dealloc(PyTypeObject *type)
1324{
1325 etype *et;
1326
1327 /* Assert this is a heap-allocated type object */
1328 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001329 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001330 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 et = (etype *)type;
1332 Py_XDECREF(type->tp_base);
1333 Py_XDECREF(type->tp_dict);
1334 Py_XDECREF(type->tp_bases);
1335 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001336 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001337 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338 Py_XDECREF(et->name);
1339 Py_XDECREF(et->slots);
1340 type->ob_type->tp_free((PyObject *)type);
1341}
1342
Guido van Rossum1c450732001-10-08 15:18:27 +00001343static PyObject *
1344type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1345{
1346 PyObject *list, *raw, *ref;
1347 int i, n;
1348
1349 list = PyList_New(0);
1350 if (list == NULL)
1351 return NULL;
1352 raw = type->tp_subclasses;
1353 if (raw == NULL)
1354 return list;
1355 assert(PyList_Check(raw));
1356 n = PyList_GET_SIZE(raw);
1357 for (i = 0; i < n; i++) {
1358 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001359 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001360 ref = PyWeakref_GET_OBJECT(ref);
1361 if (ref != Py_None) {
1362 if (PyList_Append(list, ref) < 0) {
1363 Py_DECREF(list);
1364 return NULL;
1365 }
1366 }
1367 }
1368 return list;
1369}
1370
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001372 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001374 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1375 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376 {0}
1377};
1378
1379static char type_doc[] =
1380"type(object) -> the object's type\n"
1381"type(name, bases, dict) -> a new type";
1382
Guido van Rossum048eb752001-10-02 21:24:57 +00001383static int
1384type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1385{
1386 etype *et;
1387 int err;
1388
1389 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1390 return 0;
1391
1392 et = (etype *)type;
1393
1394#define VISIT(SLOT) \
1395 if (SLOT) { \
1396 err = visit((PyObject *)(SLOT), arg); \
1397 if (err) \
1398 return err; \
1399 }
1400
1401 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001402 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001403 VISIT(type->tp_mro);
1404 VISIT(type->tp_bases);
1405 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001406 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001407 VISIT(et->slots);
1408
1409#undef VISIT
1410
1411 return 0;
1412}
1413
1414static int
1415type_clear(PyTypeObject *type)
1416{
1417 etype *et;
1418 PyObject *tmp;
1419
1420 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1421 return 0;
1422
1423 et = (etype *)type;
1424
1425#define CLEAR(SLOT) \
1426 if (SLOT) { \
1427 tmp = (PyObject *)(SLOT); \
1428 SLOT = NULL; \
1429 Py_DECREF(tmp); \
1430 }
1431
1432 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001433 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001434 CLEAR(type->tp_mro);
1435 CLEAR(type->tp_bases);
1436 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001437 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001438 CLEAR(et->slots);
1439
Tim Peters2f93e282001-10-04 05:27:00 +00001440 if (type->tp_doc != NULL) {
1441 PyObject_FREE(type->tp_doc);
1442 type->tp_doc = NULL;
1443 }
1444
Guido van Rossum048eb752001-10-02 21:24:57 +00001445#undef CLEAR
1446
1447 return 0;
1448}
1449
1450static int
1451type_is_gc(PyTypeObject *type)
1452{
1453 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1454}
1455
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001456PyTypeObject PyType_Type = {
1457 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 0, /* ob_size */
1459 "type", /* tp_name */
1460 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001461 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001462 (destructor)type_dealloc, /* tp_dealloc */
1463 0, /* tp_print */
1464 0, /* tp_getattr */
1465 0, /* tp_setattr */
1466 type_compare, /* tp_compare */
1467 (reprfunc)type_repr, /* tp_repr */
1468 0, /* tp_as_number */
1469 0, /* tp_as_sequence */
1470 0, /* tp_as_mapping */
1471 (hashfunc)_Py_HashPointer, /* tp_hash */
1472 (ternaryfunc)type_call, /* tp_call */
1473 0, /* tp_str */
1474 (getattrofunc)type_getattro, /* tp_getattro */
1475 (setattrofunc)type_setattro, /* tp_setattro */
1476 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001477 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1478 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001480 (traverseproc)type_traverse, /* tp_traverse */
1481 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001483 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 0, /* tp_iter */
1485 0, /* tp_iternext */
1486 type_methods, /* tp_methods */
1487 type_members, /* tp_members */
1488 type_getsets, /* tp_getset */
1489 0, /* tp_base */
1490 0, /* tp_dict */
1491 0, /* tp_descr_get */
1492 0, /* tp_descr_set */
1493 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1494 0, /* tp_init */
1495 0, /* tp_alloc */
1496 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001497 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001498 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001499};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500
1501
1502/* The base type of all types (eventually)... except itself. */
1503
1504static int
1505object_init(PyObject *self, PyObject *args, PyObject *kwds)
1506{
1507 return 0;
1508}
1509
1510static void
1511object_dealloc(PyObject *self)
1512{
1513 self->ob_type->tp_free(self);
1514}
1515
Guido van Rossum8e248182001-08-12 05:17:56 +00001516static PyObject *
1517object_repr(PyObject *self)
1518{
Guido van Rossum76e69632001-08-16 18:52:43 +00001519 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001520 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001521
Guido van Rossum76e69632001-08-16 18:52:43 +00001522 type = self->ob_type;
1523 mod = type_module(type, NULL);
1524 if (mod == NULL)
1525 PyErr_Clear();
1526 else if (!PyString_Check(mod)) {
1527 Py_DECREF(mod);
1528 mod = NULL;
1529 }
1530 name = type_name(type, NULL);
1531 if (name == NULL)
1532 return NULL;
1533 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001534 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001535 PyString_AS_STRING(mod),
1536 PyString_AS_STRING(name),
1537 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001538 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001539 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001540 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001541 Py_XDECREF(mod);
1542 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001543 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001544}
1545
Guido van Rossumb8f63662001-08-15 23:57:02 +00001546static PyObject *
1547object_str(PyObject *self)
1548{
1549 unaryfunc f;
1550
1551 f = self->ob_type->tp_repr;
1552 if (f == NULL)
1553 f = object_repr;
1554 return f(self);
1555}
1556
Guido van Rossum8e248182001-08-12 05:17:56 +00001557static long
1558object_hash(PyObject *self)
1559{
1560 return _Py_HashPointer(self);
1561}
Guido van Rossum8e248182001-08-12 05:17:56 +00001562
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001563static PyObject *
1564object_get_class(PyObject *self, void *closure)
1565{
1566 Py_INCREF(self->ob_type);
1567 return (PyObject *)(self->ob_type);
1568}
1569
1570static int
1571equiv_structs(PyTypeObject *a, PyTypeObject *b)
1572{
1573 return a == b ||
1574 (a != NULL &&
1575 b != NULL &&
1576 a->tp_basicsize == b->tp_basicsize &&
1577 a->tp_itemsize == b->tp_itemsize &&
1578 a->tp_dictoffset == b->tp_dictoffset &&
1579 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1580 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1581 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1582}
1583
1584static int
1585same_slots_added(PyTypeObject *a, PyTypeObject *b)
1586{
1587 PyTypeObject *base = a->tp_base;
1588 int size;
1589
1590 if (base != b->tp_base)
1591 return 0;
1592 if (equiv_structs(a, base) && equiv_structs(b, base))
1593 return 1;
1594 size = base->tp_basicsize;
1595 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1596 size += sizeof(PyObject *);
1597 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1598 size += sizeof(PyObject *);
1599 return size == a->tp_basicsize && size == b->tp_basicsize;
1600}
1601
1602static int
1603object_set_class(PyObject *self, PyObject *value, void *closure)
1604{
1605 PyTypeObject *old = self->ob_type;
1606 PyTypeObject *new, *newbase, *oldbase;
1607
Guido van Rossumb6b89422002-04-15 01:03:30 +00001608 if (value == NULL) {
1609 PyErr_SetString(PyExc_TypeError,
1610 "can't delete __class__ attribute");
1611 return -1;
1612 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001613 if (!PyType_Check(value)) {
1614 PyErr_Format(PyExc_TypeError,
1615 "__class__ must be set to new-style class, not '%s' object",
1616 value->ob_type->tp_name);
1617 return -1;
1618 }
1619 new = (PyTypeObject *)value;
1620 newbase = new;
1621 oldbase = old;
1622 while (equiv_structs(newbase, newbase->tp_base))
1623 newbase = newbase->tp_base;
1624 while (equiv_structs(oldbase, oldbase->tp_base))
1625 oldbase = oldbase->tp_base;
1626 if (newbase != oldbase &&
1627 (newbase->tp_base != oldbase->tp_base ||
1628 !same_slots_added(newbase, oldbase))) {
1629 PyErr_Format(PyExc_TypeError,
1630 "__class__ assignment: "
1631 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001632 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001633 old->tp_name);
1634 return -1;
1635 }
1636 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1637 Py_INCREF(new);
1638 }
1639 self->ob_type = new;
1640 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1641 Py_DECREF(old);
1642 }
1643 return 0;
1644}
1645
1646static PyGetSetDef object_getsets[] = {
1647 {"__class__", object_get_class, object_set_class,
1648 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649 {0}
1650};
1651
Guido van Rossum3926a632001-09-25 16:25:58 +00001652static PyObject *
1653object_reduce(PyObject *self, PyObject *args)
1654{
1655 /* Call copy_reg._reduce(self) */
1656 static PyObject *copy_reg_str;
1657 PyObject *copy_reg, *res;
1658
1659 if (!copy_reg_str) {
1660 copy_reg_str = PyString_InternFromString("copy_reg");
1661 if (copy_reg_str == NULL)
1662 return NULL;
1663 }
1664 copy_reg = PyImport_Import(copy_reg_str);
1665 if (!copy_reg)
1666 return NULL;
1667 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1668 Py_DECREF(copy_reg);
1669 return res;
1670}
1671
1672static PyMethodDef object_methods[] = {
1673 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1674 {0}
1675};
1676
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677PyTypeObject PyBaseObject_Type = {
1678 PyObject_HEAD_INIT(&PyType_Type)
1679 0, /* ob_size */
1680 "object", /* tp_name */
1681 sizeof(PyObject), /* tp_basicsize */
1682 0, /* tp_itemsize */
1683 (destructor)object_dealloc, /* tp_dealloc */
1684 0, /* tp_print */
1685 0, /* tp_getattr */
1686 0, /* tp_setattr */
1687 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001688 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689 0, /* tp_as_number */
1690 0, /* tp_as_sequence */
1691 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001692 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001694 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001695 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001696 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001697 0, /* tp_as_buffer */
1698 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1699 "The most base type", /* tp_doc */
1700 0, /* tp_traverse */
1701 0, /* tp_clear */
1702 0, /* tp_richcompare */
1703 0, /* tp_weaklistoffset */
1704 0, /* tp_iter */
1705 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001706 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001707 0, /* tp_members */
1708 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709 0, /* tp_base */
1710 0, /* tp_dict */
1711 0, /* tp_descr_get */
1712 0, /* tp_descr_set */
1713 0, /* tp_dictoffset */
1714 object_init, /* tp_init */
1715 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001716 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001717 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718};
1719
1720
1721/* Initialize the __dict__ in a type object */
1722
Fred Drake7bf97152002-03-28 05:33:33 +00001723static PyObject *
1724create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1725{
1726 PyObject *cfunc;
1727 PyObject *result;
1728
1729 cfunc = PyCFunction_New(meth, NULL);
1730 if (cfunc == NULL)
1731 return NULL;
1732 result = func(cfunc);
1733 Py_DECREF(cfunc);
1734 return result;
1735}
1736
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737static int
1738add_methods(PyTypeObject *type, PyMethodDef *meth)
1739{
Guido van Rossum687ae002001-10-15 22:03:32 +00001740 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741
1742 for (; meth->ml_name != NULL; meth++) {
1743 PyObject *descr;
1744 if (PyDict_GetItemString(dict, meth->ml_name))
1745 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001746 if (meth->ml_flags & METH_CLASS) {
1747 if (meth->ml_flags & METH_STATIC) {
1748 PyErr_SetString(PyExc_ValueError,
1749 "method cannot be both class and static");
1750 return -1;
1751 }
1752 descr = create_specialmethod(meth, PyClassMethod_New);
1753 }
1754 else if (meth->ml_flags & METH_STATIC) {
1755 descr = create_specialmethod(meth, PyStaticMethod_New);
1756 }
1757 else {
1758 descr = PyDescr_NewMethod(type, meth);
1759 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001760 if (descr == NULL)
1761 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001762 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763 return -1;
1764 Py_DECREF(descr);
1765 }
1766 return 0;
1767}
1768
1769static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001770add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771{
Guido van Rossum687ae002001-10-15 22:03:32 +00001772 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773
1774 for (; memb->name != NULL; memb++) {
1775 PyObject *descr;
1776 if (PyDict_GetItemString(dict, memb->name))
1777 continue;
1778 descr = PyDescr_NewMember(type, memb);
1779 if (descr == NULL)
1780 return -1;
1781 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1782 return -1;
1783 Py_DECREF(descr);
1784 }
1785 return 0;
1786}
1787
1788static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001789add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001790{
Guido van Rossum687ae002001-10-15 22:03:32 +00001791 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792
1793 for (; gsp->name != NULL; gsp++) {
1794 PyObject *descr;
1795 if (PyDict_GetItemString(dict, gsp->name))
1796 continue;
1797 descr = PyDescr_NewGetSet(type, gsp);
1798
1799 if (descr == NULL)
1800 return -1;
1801 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1802 return -1;
1803 Py_DECREF(descr);
1804 }
1805 return 0;
1806}
1807
Guido van Rossum13d52f02001-08-10 21:24:08 +00001808static void
1809inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810{
1811 int oldsize, newsize;
1812
Guido van Rossum13d52f02001-08-10 21:24:08 +00001813 /* Special flag magic */
1814 if (!type->tp_as_buffer && base->tp_as_buffer) {
1815 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1816 type->tp_flags |=
1817 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1818 }
1819 if (!type->tp_as_sequence && base->tp_as_sequence) {
1820 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1821 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1822 }
1823 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1824 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1825 if ((!type->tp_as_number && base->tp_as_number) ||
1826 (!type->tp_as_sequence && base->tp_as_sequence)) {
1827 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1828 if (!type->tp_as_number && !type->tp_as_sequence) {
1829 type->tp_flags |= base->tp_flags &
1830 Py_TPFLAGS_HAVE_INPLACEOPS;
1831 }
1832 }
1833 /* Wow */
1834 }
1835 if (!type->tp_as_number && base->tp_as_number) {
1836 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1837 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1838 }
1839
1840 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001841 oldsize = base->tp_basicsize;
1842 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1843 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1844 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001845 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1846 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001847 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001848 if (type->tp_traverse == NULL)
1849 type->tp_traverse = base->tp_traverse;
1850 if (type->tp_clear == NULL)
1851 type->tp_clear = base->tp_clear;
1852 }
1853 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001854 /* The condition below could use some explanation.
1855 It appears that tp_new is not inherited for static types
1856 whose base class is 'object'; this seems to be a precaution
1857 so that old extension types don't suddenly become
1858 callable (object.__new__ wouldn't insure the invariants
1859 that the extension type's own factory function ensures).
1860 Heap types, of course, are under our control, so they do
1861 inherit tp_new; static extension types that specify some
1862 other built-in type as the default are considered
1863 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001864 if (base != &PyBaseObject_Type ||
1865 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1866 if (type->tp_new == NULL)
1867 type->tp_new = base->tp_new;
1868 }
1869 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001870 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001871
1872 /* Copy other non-function slots */
1873
1874#undef COPYVAL
1875#define COPYVAL(SLOT) \
1876 if (type->SLOT == 0) type->SLOT = base->SLOT
1877
1878 COPYVAL(tp_itemsize);
1879 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1880 COPYVAL(tp_weaklistoffset);
1881 }
1882 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1883 COPYVAL(tp_dictoffset);
1884 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001885}
1886
1887static void
1888inherit_slots(PyTypeObject *type, PyTypeObject *base)
1889{
1890 PyTypeObject *basebase;
1891
1892#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893#undef COPYSLOT
1894#undef COPYNUM
1895#undef COPYSEQ
1896#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001897#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001898
1899#define SLOTDEFINED(SLOT) \
1900 (base->SLOT != 0 && \
1901 (basebase == NULL || base->SLOT != basebase->SLOT))
1902
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001904 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905
1906#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1907#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1908#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001909#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910
Guido van Rossum13d52f02001-08-10 21:24:08 +00001911 /* This won't inherit indirect slots (from tp_as_number etc.)
1912 if type doesn't provide the space. */
1913
1914 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1915 basebase = base->tp_base;
1916 if (basebase->tp_as_number == NULL)
1917 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001918 COPYNUM(nb_add);
1919 COPYNUM(nb_subtract);
1920 COPYNUM(nb_multiply);
1921 COPYNUM(nb_divide);
1922 COPYNUM(nb_remainder);
1923 COPYNUM(nb_divmod);
1924 COPYNUM(nb_power);
1925 COPYNUM(nb_negative);
1926 COPYNUM(nb_positive);
1927 COPYNUM(nb_absolute);
1928 COPYNUM(nb_nonzero);
1929 COPYNUM(nb_invert);
1930 COPYNUM(nb_lshift);
1931 COPYNUM(nb_rshift);
1932 COPYNUM(nb_and);
1933 COPYNUM(nb_xor);
1934 COPYNUM(nb_or);
1935 COPYNUM(nb_coerce);
1936 COPYNUM(nb_int);
1937 COPYNUM(nb_long);
1938 COPYNUM(nb_float);
1939 COPYNUM(nb_oct);
1940 COPYNUM(nb_hex);
1941 COPYNUM(nb_inplace_add);
1942 COPYNUM(nb_inplace_subtract);
1943 COPYNUM(nb_inplace_multiply);
1944 COPYNUM(nb_inplace_divide);
1945 COPYNUM(nb_inplace_remainder);
1946 COPYNUM(nb_inplace_power);
1947 COPYNUM(nb_inplace_lshift);
1948 COPYNUM(nb_inplace_rshift);
1949 COPYNUM(nb_inplace_and);
1950 COPYNUM(nb_inplace_xor);
1951 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001952 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1953 COPYNUM(nb_true_divide);
1954 COPYNUM(nb_floor_divide);
1955 COPYNUM(nb_inplace_true_divide);
1956 COPYNUM(nb_inplace_floor_divide);
1957 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001958 }
1959
Guido van Rossum13d52f02001-08-10 21:24:08 +00001960 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1961 basebase = base->tp_base;
1962 if (basebase->tp_as_sequence == NULL)
1963 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964 COPYSEQ(sq_length);
1965 COPYSEQ(sq_concat);
1966 COPYSEQ(sq_repeat);
1967 COPYSEQ(sq_item);
1968 COPYSEQ(sq_slice);
1969 COPYSEQ(sq_ass_item);
1970 COPYSEQ(sq_ass_slice);
1971 COPYSEQ(sq_contains);
1972 COPYSEQ(sq_inplace_concat);
1973 COPYSEQ(sq_inplace_repeat);
1974 }
1975
Guido van Rossum13d52f02001-08-10 21:24:08 +00001976 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1977 basebase = base->tp_base;
1978 if (basebase->tp_as_mapping == NULL)
1979 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980 COPYMAP(mp_length);
1981 COPYMAP(mp_subscript);
1982 COPYMAP(mp_ass_subscript);
1983 }
1984
Tim Petersfc57ccb2001-10-12 02:38:24 +00001985 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1986 basebase = base->tp_base;
1987 if (basebase->tp_as_buffer == NULL)
1988 basebase = NULL;
1989 COPYBUF(bf_getreadbuffer);
1990 COPYBUF(bf_getwritebuffer);
1991 COPYBUF(bf_getsegcount);
1992 COPYBUF(bf_getcharbuffer);
1993 }
1994
Guido van Rossum13d52f02001-08-10 21:24:08 +00001995 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996
Tim Peters6d6c1a32001-08-02 04:15:00 +00001997 COPYSLOT(tp_dealloc);
1998 COPYSLOT(tp_print);
1999 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2000 type->tp_getattr = base->tp_getattr;
2001 type->tp_getattro = base->tp_getattro;
2002 }
2003 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2004 type->tp_setattr = base->tp_setattr;
2005 type->tp_setattro = base->tp_setattro;
2006 }
2007 /* tp_compare see tp_richcompare */
2008 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002009 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010 COPYSLOT(tp_call);
2011 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002013 if (type->tp_compare == NULL &&
2014 type->tp_richcompare == NULL &&
2015 type->tp_hash == NULL)
2016 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002017 type->tp_compare = base->tp_compare;
2018 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002019 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020 }
2021 }
2022 else {
2023 COPYSLOT(tp_compare);
2024 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2026 COPYSLOT(tp_iter);
2027 COPYSLOT(tp_iternext);
2028 }
2029 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2030 COPYSLOT(tp_descr_get);
2031 COPYSLOT(tp_descr_set);
2032 COPYSLOT(tp_dictoffset);
2033 COPYSLOT(tp_init);
2034 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002036 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038}
2039
Guido van Rossum13d52f02001-08-10 21:24:08 +00002040staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002041staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002042
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002044PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002046 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047 PyTypeObject *base;
2048 int i, n;
2049
Guido van Rossumd614f972001-08-10 17:39:49 +00002050 if (type->tp_flags & Py_TPFLAGS_READY) {
2051 assert(type->tp_dict != NULL);
2052 return 0;
2053 }
2054 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002055
2056 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057
2058 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2059 base = type->tp_base;
2060 if (base == NULL && type != &PyBaseObject_Type)
2061 base = type->tp_base = &PyBaseObject_Type;
2062
Guido van Rossum0986d822002-04-08 01:38:42 +00002063 /* Initialize ob_type if NULL. This means extensions that want to be
2064 compilable separately on Windows can call PyType_Ready() instead of
2065 initializing the ob_type field of their type objects. */
2066 if (type->ob_type == NULL)
2067 type->ob_type = base->ob_type;
2068
Tim Peters6d6c1a32001-08-02 04:15:00 +00002069 /* Initialize tp_bases */
2070 bases = type->tp_bases;
2071 if (bases == NULL) {
2072 if (base == NULL)
2073 bases = PyTuple_New(0);
2074 else
2075 bases = Py_BuildValue("(O)", base);
2076 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002077 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002078 type->tp_bases = bases;
2079 }
2080
2081 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002082 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002083 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002084 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002085 }
2086
Guido van Rossum687ae002001-10-15 22:03:32 +00002087 /* Initialize tp_dict */
2088 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 if (dict == NULL) {
2090 dict = PyDict_New();
2091 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002092 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002093 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 }
2095
Guido van Rossum687ae002001-10-15 22:03:32 +00002096 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002098 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099 if (type->tp_methods != NULL) {
2100 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002101 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 }
2103 if (type->tp_members != NULL) {
2104 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002105 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 }
2107 if (type->tp_getset != NULL) {
2108 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002109 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110 }
2111
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112 /* Calculate method resolution order */
2113 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002114 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002115 }
2116
Guido van Rossum13d52f02001-08-10 21:24:08 +00002117 /* Inherit special flags from dominant base */
2118 if (type->tp_base != NULL)
2119 inherit_special(type, type->tp_base);
2120
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002122 bases = type->tp_mro;
2123 assert(bases != NULL);
2124 assert(PyTuple_Check(bases));
2125 n = PyTuple_GET_SIZE(bases);
2126 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002127 PyObject *b = PyTuple_GET_ITEM(bases, i);
2128 if (PyType_Check(b))
2129 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002130 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002131
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002132 /* if the type dictionary doesn't contain a __doc__, set it from
2133 the tp_doc slot.
2134 */
2135 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2136 if (type->tp_doc != NULL) {
2137 PyObject *doc = PyString_FromString(type->tp_doc);
2138 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2139 Py_DECREF(doc);
2140 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002141 PyDict_SetItemString(type->tp_dict,
2142 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002143 }
2144 }
2145
Guido van Rossum13d52f02001-08-10 21:24:08 +00002146 /* Some more special stuff */
2147 base = type->tp_base;
2148 if (base != NULL) {
2149 if (type->tp_as_number == NULL)
2150 type->tp_as_number = base->tp_as_number;
2151 if (type->tp_as_sequence == NULL)
2152 type->tp_as_sequence = base->tp_as_sequence;
2153 if (type->tp_as_mapping == NULL)
2154 type->tp_as_mapping = base->tp_as_mapping;
2155 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156
Guido van Rossum1c450732001-10-08 15:18:27 +00002157 /* Link into each base class's list of subclasses */
2158 bases = type->tp_bases;
2159 n = PyTuple_GET_SIZE(bases);
2160 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002161 PyObject *b = PyTuple_GET_ITEM(bases, i);
2162 if (PyType_Check(b) &&
2163 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002164 goto error;
2165 }
2166
Guido van Rossum13d52f02001-08-10 21:24:08 +00002167 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002168 assert(type->tp_dict != NULL);
2169 type->tp_flags =
2170 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002171 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002172
2173 error:
2174 type->tp_flags &= ~Py_TPFLAGS_READYING;
2175 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176}
2177
Guido van Rossum1c450732001-10-08 15:18:27 +00002178static int
2179add_subclass(PyTypeObject *base, PyTypeObject *type)
2180{
2181 int i;
2182 PyObject *list, *ref, *new;
2183
2184 list = base->tp_subclasses;
2185 if (list == NULL) {
2186 base->tp_subclasses = list = PyList_New(0);
2187 if (list == NULL)
2188 return -1;
2189 }
2190 assert(PyList_Check(list));
2191 new = PyWeakref_NewRef((PyObject *)type, NULL);
2192 i = PyList_GET_SIZE(list);
2193 while (--i >= 0) {
2194 ref = PyList_GET_ITEM(list, i);
2195 assert(PyWeakref_CheckRef(ref));
2196 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2197 return PyList_SetItem(list, i, new);
2198 }
2199 i = PyList_Append(list, new);
2200 Py_DECREF(new);
2201 return i;
2202}
2203
Tim Peters6d6c1a32001-08-02 04:15:00 +00002204
2205/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2206
2207/* There's a wrapper *function* for each distinct function typedef used
2208 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2209 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2210 Most tables have only one entry; the tables for binary operators have two
2211 entries, one regular and one with reversed arguments. */
2212
2213static PyObject *
2214wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2215{
2216 inquiry func = (inquiry)wrapped;
2217 int res;
2218
2219 if (!PyArg_ParseTuple(args, ""))
2220 return NULL;
2221 res = (*func)(self);
2222 if (res == -1 && PyErr_Occurred())
2223 return NULL;
2224 return PyInt_FromLong((long)res);
2225}
2226
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227static PyObject *
2228wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2229{
2230 binaryfunc func = (binaryfunc)wrapped;
2231 PyObject *other;
2232
2233 if (!PyArg_ParseTuple(args, "O", &other))
2234 return NULL;
2235 return (*func)(self, other);
2236}
2237
2238static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002239wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2240{
2241 binaryfunc func = (binaryfunc)wrapped;
2242 PyObject *other;
2243
2244 if (!PyArg_ParseTuple(args, "O", &other))
2245 return NULL;
2246 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002247 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002248 Py_INCREF(Py_NotImplemented);
2249 return Py_NotImplemented;
2250 }
2251 return (*func)(self, other);
2252}
2253
2254static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002255wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2256{
2257 binaryfunc func = (binaryfunc)wrapped;
2258 PyObject *other;
2259
2260 if (!PyArg_ParseTuple(args, "O", &other))
2261 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002262 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002263 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002264 Py_INCREF(Py_NotImplemented);
2265 return Py_NotImplemented;
2266 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002267 return (*func)(other, self);
2268}
2269
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002270static PyObject *
2271wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2272{
2273 coercion func = (coercion)wrapped;
2274 PyObject *other, *res;
2275 int ok;
2276
2277 if (!PyArg_ParseTuple(args, "O", &other))
2278 return NULL;
2279 ok = func(&self, &other);
2280 if (ok < 0)
2281 return NULL;
2282 if (ok > 0) {
2283 Py_INCREF(Py_NotImplemented);
2284 return Py_NotImplemented;
2285 }
2286 res = PyTuple_New(2);
2287 if (res == NULL) {
2288 Py_DECREF(self);
2289 Py_DECREF(other);
2290 return NULL;
2291 }
2292 PyTuple_SET_ITEM(res, 0, self);
2293 PyTuple_SET_ITEM(res, 1, other);
2294 return res;
2295}
2296
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297static PyObject *
2298wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2299{
2300 ternaryfunc func = (ternaryfunc)wrapped;
2301 PyObject *other;
2302 PyObject *third = Py_None;
2303
2304 /* Note: This wrapper only works for __pow__() */
2305
2306 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2307 return NULL;
2308 return (*func)(self, other, third);
2309}
2310
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002311static PyObject *
2312wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2313{
2314 ternaryfunc func = (ternaryfunc)wrapped;
2315 PyObject *other;
2316 PyObject *third = Py_None;
2317
2318 /* Note: This wrapper only works for __pow__() */
2319
2320 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2321 return NULL;
2322 return (*func)(other, self, third);
2323}
2324
Tim Peters6d6c1a32001-08-02 04:15:00 +00002325static PyObject *
2326wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2327{
2328 unaryfunc func = (unaryfunc)wrapped;
2329
2330 if (!PyArg_ParseTuple(args, ""))
2331 return NULL;
2332 return (*func)(self);
2333}
2334
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335static PyObject *
2336wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2337{
2338 intargfunc func = (intargfunc)wrapped;
2339 int i;
2340
2341 if (!PyArg_ParseTuple(args, "i", &i))
2342 return NULL;
2343 return (*func)(self, i);
2344}
2345
Guido van Rossum5d815f32001-08-17 21:57:47 +00002346static int
2347getindex(PyObject *self, PyObject *arg)
2348{
2349 int i;
2350
2351 i = PyInt_AsLong(arg);
2352 if (i == -1 && PyErr_Occurred())
2353 return -1;
2354 if (i < 0) {
2355 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2356 if (sq && sq->sq_length) {
2357 int n = (*sq->sq_length)(self);
2358 if (n < 0)
2359 return -1;
2360 i += n;
2361 }
2362 }
2363 return i;
2364}
2365
2366static PyObject *
2367wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2368{
2369 intargfunc func = (intargfunc)wrapped;
2370 PyObject *arg;
2371 int i;
2372
Guido van Rossumf4593e02001-10-03 12:09:30 +00002373 if (PyTuple_GET_SIZE(args) == 1) {
2374 arg = PyTuple_GET_ITEM(args, 0);
2375 i = getindex(self, arg);
2376 if (i == -1 && PyErr_Occurred())
2377 return NULL;
2378 return (*func)(self, i);
2379 }
2380 PyArg_ParseTuple(args, "O", &arg);
2381 assert(PyErr_Occurred());
2382 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002383}
2384
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385static PyObject *
2386wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2387{
2388 intintargfunc func = (intintargfunc)wrapped;
2389 int i, j;
2390
2391 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2392 return NULL;
2393 return (*func)(self, i, j);
2394}
2395
Tim Peters6d6c1a32001-08-02 04:15:00 +00002396static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002397wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398{
2399 intobjargproc func = (intobjargproc)wrapped;
2400 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002401 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402
Guido van Rossum5d815f32001-08-17 21:57:47 +00002403 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2404 return NULL;
2405 i = getindex(self, arg);
2406 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002407 return NULL;
2408 res = (*func)(self, i, value);
2409 if (res == -1 && PyErr_Occurred())
2410 return NULL;
2411 Py_INCREF(Py_None);
2412 return Py_None;
2413}
2414
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002415static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002416wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002417{
2418 intobjargproc func = (intobjargproc)wrapped;
2419 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002420 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002421
Guido van Rossum5d815f32001-08-17 21:57:47 +00002422 if (!PyArg_ParseTuple(args, "O", &arg))
2423 return NULL;
2424 i = getindex(self, arg);
2425 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002426 return NULL;
2427 res = (*func)(self, i, NULL);
2428 if (res == -1 && PyErr_Occurred())
2429 return NULL;
2430 Py_INCREF(Py_None);
2431 return Py_None;
2432}
2433
Tim Peters6d6c1a32001-08-02 04:15:00 +00002434static PyObject *
2435wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2436{
2437 intintobjargproc func = (intintobjargproc)wrapped;
2438 int i, j, res;
2439 PyObject *value;
2440
2441 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2442 return NULL;
2443 res = (*func)(self, i, j, value);
2444 if (res == -1 && PyErr_Occurred())
2445 return NULL;
2446 Py_INCREF(Py_None);
2447 return Py_None;
2448}
2449
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002450static PyObject *
2451wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2452{
2453 intintobjargproc func = (intintobjargproc)wrapped;
2454 int i, j, res;
2455
2456 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2457 return NULL;
2458 res = (*func)(self, i, j, NULL);
2459 if (res == -1 && PyErr_Occurred())
2460 return NULL;
2461 Py_INCREF(Py_None);
2462 return Py_None;
2463}
2464
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465/* XXX objobjproc is a misnomer; should be objargpred */
2466static PyObject *
2467wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2468{
2469 objobjproc func = (objobjproc)wrapped;
2470 int res;
2471 PyObject *value;
2472
2473 if (!PyArg_ParseTuple(args, "O", &value))
2474 return NULL;
2475 res = (*func)(self, value);
2476 if (res == -1 && PyErr_Occurred())
2477 return NULL;
2478 return PyInt_FromLong((long)res);
2479}
2480
Tim Peters6d6c1a32001-08-02 04:15:00 +00002481static PyObject *
2482wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2483{
2484 objobjargproc func = (objobjargproc)wrapped;
2485 int res;
2486 PyObject *key, *value;
2487
2488 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2489 return NULL;
2490 res = (*func)(self, key, value);
2491 if (res == -1 && PyErr_Occurred())
2492 return NULL;
2493 Py_INCREF(Py_None);
2494 return Py_None;
2495}
2496
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002497static PyObject *
2498wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2499{
2500 objobjargproc func = (objobjargproc)wrapped;
2501 int res;
2502 PyObject *key;
2503
2504 if (!PyArg_ParseTuple(args, "O", &key))
2505 return NULL;
2506 res = (*func)(self, key, NULL);
2507 if (res == -1 && PyErr_Occurred())
2508 return NULL;
2509 Py_INCREF(Py_None);
2510 return Py_None;
2511}
2512
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513static PyObject *
2514wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2515{
2516 cmpfunc func = (cmpfunc)wrapped;
2517 int res;
2518 PyObject *other;
2519
2520 if (!PyArg_ParseTuple(args, "O", &other))
2521 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002522 if (other->ob_type->tp_compare != func &&
2523 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002524 PyErr_Format(
2525 PyExc_TypeError,
2526 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2527 self->ob_type->tp_name,
2528 self->ob_type->tp_name,
2529 other->ob_type->tp_name);
2530 return NULL;
2531 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532 res = (*func)(self, other);
2533 if (PyErr_Occurred())
2534 return NULL;
2535 return PyInt_FromLong((long)res);
2536}
2537
Tim Peters6d6c1a32001-08-02 04:15:00 +00002538static PyObject *
2539wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2540{
2541 setattrofunc func = (setattrofunc)wrapped;
2542 int res;
2543 PyObject *name, *value;
2544
2545 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2546 return NULL;
2547 res = (*func)(self, name, value);
2548 if (res < 0)
2549 return NULL;
2550 Py_INCREF(Py_None);
2551 return Py_None;
2552}
2553
2554static PyObject *
2555wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2556{
2557 setattrofunc func = (setattrofunc)wrapped;
2558 int res;
2559 PyObject *name;
2560
2561 if (!PyArg_ParseTuple(args, "O", &name))
2562 return NULL;
2563 res = (*func)(self, name, NULL);
2564 if (res < 0)
2565 return NULL;
2566 Py_INCREF(Py_None);
2567 return Py_None;
2568}
2569
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570static PyObject *
2571wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2572{
2573 hashfunc func = (hashfunc)wrapped;
2574 long res;
2575
2576 if (!PyArg_ParseTuple(args, ""))
2577 return NULL;
2578 res = (*func)(self);
2579 if (res == -1 && PyErr_Occurred())
2580 return NULL;
2581 return PyInt_FromLong(res);
2582}
2583
Tim Peters6d6c1a32001-08-02 04:15:00 +00002584static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002585wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586{
2587 ternaryfunc func = (ternaryfunc)wrapped;
2588
Guido van Rossumc8e56452001-10-22 00:43:43 +00002589 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590}
2591
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592static PyObject *
2593wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2594{
2595 richcmpfunc func = (richcmpfunc)wrapped;
2596 PyObject *other;
2597
2598 if (!PyArg_ParseTuple(args, "O", &other))
2599 return NULL;
2600 return (*func)(self, other, op);
2601}
2602
2603#undef RICHCMP_WRAPPER
2604#define RICHCMP_WRAPPER(NAME, OP) \
2605static PyObject * \
2606richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2607{ \
2608 return wrap_richcmpfunc(self, args, wrapped, OP); \
2609}
2610
Jack Jansen8e938b42001-08-08 15:29:49 +00002611RICHCMP_WRAPPER(lt, Py_LT)
2612RICHCMP_WRAPPER(le, Py_LE)
2613RICHCMP_WRAPPER(eq, Py_EQ)
2614RICHCMP_WRAPPER(ne, Py_NE)
2615RICHCMP_WRAPPER(gt, Py_GT)
2616RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002617
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618static PyObject *
2619wrap_next(PyObject *self, PyObject *args, void *wrapped)
2620{
2621 unaryfunc func = (unaryfunc)wrapped;
2622 PyObject *res;
2623
2624 if (!PyArg_ParseTuple(args, ""))
2625 return NULL;
2626 res = (*func)(self);
2627 if (res == NULL && !PyErr_Occurred())
2628 PyErr_SetNone(PyExc_StopIteration);
2629 return res;
2630}
2631
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632static PyObject *
2633wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2634{
2635 descrgetfunc func = (descrgetfunc)wrapped;
2636 PyObject *obj;
2637 PyObject *type = NULL;
2638
2639 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2640 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002641 return (*func)(self, obj, type);
2642}
2643
Tim Peters6d6c1a32001-08-02 04:15:00 +00002644static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002645wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646{
2647 descrsetfunc func = (descrsetfunc)wrapped;
2648 PyObject *obj, *value;
2649 int ret;
2650
2651 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2652 return NULL;
2653 ret = (*func)(self, obj, value);
2654 if (ret < 0)
2655 return NULL;
2656 Py_INCREF(Py_None);
2657 return Py_None;
2658}
2659
Tim Peters6d6c1a32001-08-02 04:15:00 +00002660static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002661wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662{
2663 initproc func = (initproc)wrapped;
2664
Guido van Rossumc8e56452001-10-22 00:43:43 +00002665 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666 return NULL;
2667 Py_INCREF(Py_None);
2668 return Py_None;
2669}
2670
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002672tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002673{
Barry Warsaw60f01882001-08-22 19:24:42 +00002674 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002675 PyObject *arg0, *res;
2676
2677 if (self == NULL || !PyType_Check(self))
2678 Py_FatalError("__new__() called with non-type 'self'");
2679 type = (PyTypeObject *)self;
2680 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002681 PyErr_Format(PyExc_TypeError,
2682 "%s.__new__(): not enough arguments",
2683 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002684 return NULL;
2685 }
2686 arg0 = PyTuple_GET_ITEM(args, 0);
2687 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002688 PyErr_Format(PyExc_TypeError,
2689 "%s.__new__(X): X is not a type object (%s)",
2690 type->tp_name,
2691 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002692 return NULL;
2693 }
2694 subtype = (PyTypeObject *)arg0;
2695 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002696 PyErr_Format(PyExc_TypeError,
2697 "%s.__new__(%s): %s is not a subtype of %s",
2698 type->tp_name,
2699 subtype->tp_name,
2700 subtype->tp_name,
2701 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002702 return NULL;
2703 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002704
2705 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002706 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002707 most derived base that's not a heap type is this type. */
2708 staticbase = subtype;
2709 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2710 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002711 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002712 PyErr_Format(PyExc_TypeError,
2713 "%s.__new__(%s) is not safe, use %s.__new__()",
2714 type->tp_name,
2715 subtype->tp_name,
2716 staticbase == NULL ? "?" : staticbase->tp_name);
2717 return NULL;
2718 }
2719
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002720 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2721 if (args == NULL)
2722 return NULL;
2723 res = type->tp_new(subtype, args, kwds);
2724 Py_DECREF(args);
2725 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726}
2727
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002728static struct PyMethodDef tp_new_methoddef[] = {
2729 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2730 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731 {0}
2732};
2733
2734static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002735add_tp_new_wrapper(PyTypeObject *type)
2736{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002737 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002738
Guido van Rossum687ae002001-10-15 22:03:32 +00002739 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002740 return 0;
2741 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002742 if (func == NULL)
2743 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002744 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002745}
2746
Guido van Rossumf040ede2001-08-07 16:40:56 +00002747/* Slot wrappers that call the corresponding __foo__ slot. See comments
2748 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002749
Guido van Rossumdc91b992001-08-08 22:26:22 +00002750#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002752FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002754 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002755 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756}
2757
Guido van Rossumdc91b992001-08-08 22:26:22 +00002758#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002760FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002762 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002763 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764}
2765
Guido van Rossumdc91b992001-08-08 22:26:22 +00002766
2767#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002769FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002771 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002772 int do_other = self->ob_type != other->ob_type && \
2773 other->ob_type->tp_as_number != NULL && \
2774 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002775 if (self->ob_type->tp_as_number != NULL && \
2776 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2777 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002778 if (do_other && \
2779 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2780 r = call_maybe( \
2781 other, ROPSTR, &rcache_str, "(O)", self); \
2782 if (r != Py_NotImplemented) \
2783 return r; \
2784 Py_DECREF(r); \
2785 do_other = 0; \
2786 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002787 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002788 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002789 if (r != Py_NotImplemented || \
2790 other->ob_type == self->ob_type) \
2791 return r; \
2792 Py_DECREF(r); \
2793 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002794 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002795 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002796 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002797 } \
2798 Py_INCREF(Py_NotImplemented); \
2799 return Py_NotImplemented; \
2800}
2801
2802#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2803 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2804
2805#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2806static PyObject * \
2807FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2808{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002809 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002810 return call_method(self, OPSTR, &cache_str, \
2811 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812}
2813
2814static int
2815slot_sq_length(PyObject *self)
2816{
Guido van Rossum2730b132001-08-28 18:22:14 +00002817 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002818 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002819 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820
2821 if (res == NULL)
2822 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002823 len = (int)PyInt_AsLong(res);
2824 Py_DECREF(res);
2825 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002826}
2827
Guido van Rossumdc91b992001-08-08 22:26:22 +00002828SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2829SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002830
2831/* Super-optimized version of slot_sq_item.
2832 Other slots could do the same... */
2833static PyObject *
2834slot_sq_item(PyObject *self, int i)
2835{
2836 static PyObject *getitem_str;
2837 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2838 descrgetfunc f;
2839
2840 if (getitem_str == NULL) {
2841 getitem_str = PyString_InternFromString("__getitem__");
2842 if (getitem_str == NULL)
2843 return NULL;
2844 }
2845 func = _PyType_Lookup(self->ob_type, getitem_str);
2846 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002847 if ((f = func->ob_type->tp_descr_get) == NULL)
2848 Py_INCREF(func);
2849 else
2850 func = f(func, self, (PyObject *)(self->ob_type));
2851 ival = PyInt_FromLong(i);
2852 if (ival != NULL) {
2853 args = PyTuple_New(1);
2854 if (args != NULL) {
2855 PyTuple_SET_ITEM(args, 0, ival);
2856 retval = PyObject_Call(func, args, NULL);
2857 Py_XDECREF(args);
2858 Py_XDECREF(func);
2859 return retval;
2860 }
2861 }
2862 }
2863 else {
2864 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2865 }
2866 Py_XDECREF(args);
2867 Py_XDECREF(ival);
2868 Py_XDECREF(func);
2869 return NULL;
2870}
2871
Guido van Rossumdc91b992001-08-08 22:26:22 +00002872SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002873
2874static int
2875slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2876{
2877 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002878 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002879
2880 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002881 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002882 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002884 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002885 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002886 if (res == NULL)
2887 return -1;
2888 Py_DECREF(res);
2889 return 0;
2890}
2891
2892static int
2893slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2894{
2895 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002896 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002897
2898 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002899 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002900 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002902 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002903 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002904 if (res == NULL)
2905 return -1;
2906 Py_DECREF(res);
2907 return 0;
2908}
2909
2910static int
2911slot_sq_contains(PyObject *self, PyObject *value)
2912{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002913 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002914 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915
Guido van Rossum55f20992001-10-01 17:18:22 +00002916 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002917
2918 if (func != NULL) {
2919 args = Py_BuildValue("(O)", value);
2920 if (args == NULL)
2921 res = NULL;
2922 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002923 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002924 Py_DECREF(args);
2925 }
2926 Py_DECREF(func);
2927 if (res == NULL)
2928 return -1;
2929 return PyObject_IsTrue(res);
2930 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002931 else if (PyErr_Occurred())
2932 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002933 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002934 return _PySequence_IterSearch(self, value,
2935 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002936 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002937}
2938
Guido van Rossumdc91b992001-08-08 22:26:22 +00002939SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2940SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941
2942#define slot_mp_length slot_sq_length
2943
Guido van Rossumdc91b992001-08-08 22:26:22 +00002944SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945
2946static int
2947slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2948{
2949 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002950 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002951
2952 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002953 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002954 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002955 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002956 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002957 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002958 if (res == NULL)
2959 return -1;
2960 Py_DECREF(res);
2961 return 0;
2962}
2963
Guido van Rossumdc91b992001-08-08 22:26:22 +00002964SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2965SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2966SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2967SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2968SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2969SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2970
2971staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2972
2973SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2974 nb_power, "__pow__", "__rpow__")
2975
2976static PyObject *
2977slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2978{
Guido van Rossum2730b132001-08-28 18:22:14 +00002979 static PyObject *pow_str;
2980
Guido van Rossumdc91b992001-08-08 22:26:22 +00002981 if (modulus == Py_None)
2982 return slot_nb_power_binary(self, other);
2983 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002984 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002985 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002986}
2987
2988SLOT0(slot_nb_negative, "__neg__")
2989SLOT0(slot_nb_positive, "__pos__")
2990SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002991
2992static int
2993slot_nb_nonzero(PyObject *self)
2994{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002995 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002996 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997
Guido van Rossum55f20992001-10-01 17:18:22 +00002998 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002999 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003000 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003001 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003002 func = lookup_maybe(self, "__len__", &len_str);
3003 if (func == NULL) {
3004 if (PyErr_Occurred())
3005 return -1;
3006 else
3007 return 1;
3008 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003009 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003010 res = PyObject_CallObject(func, NULL);
3011 Py_DECREF(func);
3012 if (res == NULL)
3013 return -1;
3014 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015}
3016
Guido van Rossumdc91b992001-08-08 22:26:22 +00003017SLOT0(slot_nb_invert, "__invert__")
3018SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3019SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3020SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3021SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3022SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003023
3024static int
3025slot_nb_coerce(PyObject **a, PyObject **b)
3026{
3027 static PyObject *coerce_str;
3028 PyObject *self = *a, *other = *b;
3029
3030 if (self->ob_type->tp_as_number != NULL &&
3031 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3032 PyObject *r;
3033 r = call_maybe(
3034 self, "__coerce__", &coerce_str, "(O)", other);
3035 if (r == NULL)
3036 return -1;
3037 if (r == Py_NotImplemented) {
3038 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003039 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003040 else {
3041 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3042 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003043 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003044 Py_DECREF(r);
3045 return -1;
3046 }
3047 *a = PyTuple_GET_ITEM(r, 0);
3048 Py_INCREF(*a);
3049 *b = PyTuple_GET_ITEM(r, 1);
3050 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003051 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003052 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003053 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003054 }
3055 if (other->ob_type->tp_as_number != NULL &&
3056 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3057 PyObject *r;
3058 r = call_maybe(
3059 other, "__coerce__", &coerce_str, "(O)", self);
3060 if (r == NULL)
3061 return -1;
3062 if (r == Py_NotImplemented) {
3063 Py_DECREF(r);
3064 return 1;
3065 }
3066 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3067 PyErr_SetString(PyExc_TypeError,
3068 "__coerce__ didn't return a 2-tuple");
3069 Py_DECREF(r);
3070 return -1;
3071 }
3072 *a = PyTuple_GET_ITEM(r, 1);
3073 Py_INCREF(*a);
3074 *b = PyTuple_GET_ITEM(r, 0);
3075 Py_INCREF(*b);
3076 Py_DECREF(r);
3077 return 0;
3078 }
3079 return 1;
3080}
3081
Guido van Rossumdc91b992001-08-08 22:26:22 +00003082SLOT0(slot_nb_int, "__int__")
3083SLOT0(slot_nb_long, "__long__")
3084SLOT0(slot_nb_float, "__float__")
3085SLOT0(slot_nb_oct, "__oct__")
3086SLOT0(slot_nb_hex, "__hex__")
3087SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3088SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3089SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3090SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3091SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3092SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3093SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3094SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3095SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3096SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3097SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3098SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3099 "__floordiv__", "__rfloordiv__")
3100SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3101SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3102SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103
3104static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003105half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003107 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003108 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003109 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110
Guido van Rossum60718732001-08-28 17:47:51 +00003111 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003112 if (func == NULL) {
3113 PyErr_Clear();
3114 }
3115 else {
3116 args = Py_BuildValue("(O)", other);
3117 if (args == NULL)
3118 res = NULL;
3119 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003120 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003121 Py_DECREF(args);
3122 }
3123 if (res != Py_NotImplemented) {
3124 if (res == NULL)
3125 return -2;
3126 c = PyInt_AsLong(res);
3127 Py_DECREF(res);
3128 if (c == -1 && PyErr_Occurred())
3129 return -2;
3130 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3131 }
3132 Py_DECREF(res);
3133 }
3134 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003135}
3136
Guido van Rossumab3b0342001-09-18 20:38:53 +00003137/* This slot is published for the benefit of try_3way_compare in object.c */
3138int
3139_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003140{
3141 int c;
3142
Guido van Rossumab3b0342001-09-18 20:38:53 +00003143 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003144 c = half_compare(self, other);
3145 if (c <= 1)
3146 return c;
3147 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003148 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003149 c = half_compare(other, self);
3150 if (c < -1)
3151 return -2;
3152 if (c <= 1)
3153 return -c;
3154 }
3155 return (void *)self < (void *)other ? -1 :
3156 (void *)self > (void *)other ? 1 : 0;
3157}
3158
3159static PyObject *
3160slot_tp_repr(PyObject *self)
3161{
3162 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003163 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003164
Guido van Rossum60718732001-08-28 17:47:51 +00003165 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003166 if (func != NULL) {
3167 res = PyEval_CallObject(func, NULL);
3168 Py_DECREF(func);
3169 return res;
3170 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003171 PyErr_Clear();
3172 return PyString_FromFormat("<%s object at %p>",
3173 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003174}
3175
3176static PyObject *
3177slot_tp_str(PyObject *self)
3178{
3179 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003180 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003181
Guido van Rossum60718732001-08-28 17:47:51 +00003182 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003183 if (func != NULL) {
3184 res = PyEval_CallObject(func, NULL);
3185 Py_DECREF(func);
3186 return res;
3187 }
3188 else {
3189 PyErr_Clear();
3190 return slot_tp_repr(self);
3191 }
3192}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193
3194static long
3195slot_tp_hash(PyObject *self)
3196{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003197 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003198 static PyObject *hash_str, *eq_str, *cmp_str;
3199
Tim Peters6d6c1a32001-08-02 04:15:00 +00003200 long h;
3201
Guido van Rossum60718732001-08-28 17:47:51 +00003202 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003203
3204 if (func != NULL) {
3205 res = PyEval_CallObject(func, NULL);
3206 Py_DECREF(func);
3207 if (res == NULL)
3208 return -1;
3209 h = PyInt_AsLong(res);
3210 }
3211 else {
3212 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003213 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003214 if (func == NULL) {
3215 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003216 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003217 }
3218 if (func != NULL) {
3219 Py_DECREF(func);
3220 PyErr_SetString(PyExc_TypeError, "unhashable type");
3221 return -1;
3222 }
3223 PyErr_Clear();
3224 h = _Py_HashPointer((void *)self);
3225 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003226 if (h == -1 && !PyErr_Occurred())
3227 h = -2;
3228 return h;
3229}
3230
3231static PyObject *
3232slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3233{
Guido van Rossum60718732001-08-28 17:47:51 +00003234 static PyObject *call_str;
3235 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003236 PyObject *res;
3237
3238 if (meth == NULL)
3239 return NULL;
3240 res = PyObject_Call(meth, args, kwds);
3241 Py_DECREF(meth);
3242 return res;
3243}
3244
Guido van Rossum14a6f832001-10-17 13:59:09 +00003245/* There are two slot dispatch functions for tp_getattro.
3246
3247 - slot_tp_getattro() is used when __getattribute__ is overridden
3248 but no __getattr__ hook is present;
3249
3250 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3251
Guido van Rossumc334df52002-04-04 23:44:47 +00003252 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3253 detects the absence of __getattr__ and then installs the simpler slot if
3254 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003255
Tim Peters6d6c1a32001-08-02 04:15:00 +00003256static PyObject *
3257slot_tp_getattro(PyObject *self, PyObject *name)
3258{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003259 static PyObject *getattribute_str = NULL;
3260 return call_method(self, "__getattribute__", &getattribute_str,
3261 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262}
3263
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003264static PyObject *
3265slot_tp_getattr_hook(PyObject *self, PyObject *name)
3266{
3267 PyTypeObject *tp = self->ob_type;
3268 PyObject *getattr, *getattribute, *res;
3269 static PyObject *getattribute_str = NULL;
3270 static PyObject *getattr_str = NULL;
3271
3272 if (getattr_str == NULL) {
3273 getattr_str = PyString_InternFromString("__getattr__");
3274 if (getattr_str == NULL)
3275 return NULL;
3276 }
3277 if (getattribute_str == NULL) {
3278 getattribute_str =
3279 PyString_InternFromString("__getattribute__");
3280 if (getattribute_str == NULL)
3281 return NULL;
3282 }
3283 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003284 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003285 /* No __getattr__ hook: use a simpler dispatcher */
3286 tp->tp_getattro = slot_tp_getattro;
3287 return slot_tp_getattro(self, name);
3288 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003289 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003290 if (getattribute == NULL ||
3291 (getattribute->ob_type == &PyWrapperDescr_Type &&
3292 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3293 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003294 res = PyObject_GenericGetAttr(self, name);
3295 else
3296 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003297 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003298 PyErr_Clear();
3299 res = PyObject_CallFunction(getattr, "OO", self, name);
3300 }
3301 return res;
3302}
3303
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304static int
3305slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3306{
3307 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003308 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003309
3310 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003311 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003312 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003314 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003315 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316 if (res == NULL)
3317 return -1;
3318 Py_DECREF(res);
3319 return 0;
3320}
3321
3322/* Map rich comparison operators to their __xx__ namesakes */
3323static char *name_op[] = {
3324 "__lt__",
3325 "__le__",
3326 "__eq__",
3327 "__ne__",
3328 "__gt__",
3329 "__ge__",
3330};
3331
3332static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003333half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003334{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003335 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003336 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003337
Guido van Rossum60718732001-08-28 17:47:51 +00003338 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003339 if (func == NULL) {
3340 PyErr_Clear();
3341 Py_INCREF(Py_NotImplemented);
3342 return Py_NotImplemented;
3343 }
3344 args = Py_BuildValue("(O)", other);
3345 if (args == NULL)
3346 res = NULL;
3347 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003348 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003349 Py_DECREF(args);
3350 }
3351 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352 return res;
3353}
3354
Guido van Rossumb8f63662001-08-15 23:57:02 +00003355/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3356static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3357
3358static PyObject *
3359slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3360{
3361 PyObject *res;
3362
3363 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3364 res = half_richcompare(self, other, op);
3365 if (res != Py_NotImplemented)
3366 return res;
3367 Py_DECREF(res);
3368 }
3369 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3370 res = half_richcompare(other, self, swapped_op[op]);
3371 if (res != Py_NotImplemented) {
3372 return res;
3373 }
3374 Py_DECREF(res);
3375 }
3376 Py_INCREF(Py_NotImplemented);
3377 return Py_NotImplemented;
3378}
3379
3380static PyObject *
3381slot_tp_iter(PyObject *self)
3382{
3383 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003384 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003385
Guido van Rossum60718732001-08-28 17:47:51 +00003386 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003387 if (func != NULL) {
3388 res = PyObject_CallObject(func, NULL);
3389 Py_DECREF(func);
3390 return res;
3391 }
3392 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003393 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003394 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003395 PyErr_SetString(PyExc_TypeError,
3396 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003397 return NULL;
3398 }
3399 Py_DECREF(func);
3400 return PySeqIter_New(self);
3401}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402
3403static PyObject *
3404slot_tp_iternext(PyObject *self)
3405{
Guido van Rossum2730b132001-08-28 18:22:14 +00003406 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003407 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003408}
3409
Guido van Rossum1a493502001-08-17 16:47:50 +00003410static PyObject *
3411slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3412{
3413 PyTypeObject *tp = self->ob_type;
3414 PyObject *get;
3415 static PyObject *get_str = NULL;
3416
3417 if (get_str == NULL) {
3418 get_str = PyString_InternFromString("__get__");
3419 if (get_str == NULL)
3420 return NULL;
3421 }
3422 get = _PyType_Lookup(tp, get_str);
3423 if (get == NULL) {
3424 /* Avoid further slowdowns */
3425 if (tp->tp_descr_get == slot_tp_descr_get)
3426 tp->tp_descr_get = NULL;
3427 Py_INCREF(self);
3428 return self;
3429 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003430 if (obj == NULL)
3431 obj = Py_None;
3432 if (type == NULL)
3433 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003434 return PyObject_CallFunction(get, "OOO", self, obj, type);
3435}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436
3437static int
3438slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3439{
Guido van Rossum2c252392001-08-24 10:13:31 +00003440 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003441 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003442
3443 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003444 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003445 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003446 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003447 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003448 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449 if (res == NULL)
3450 return -1;
3451 Py_DECREF(res);
3452 return 0;
3453}
3454
3455static int
3456slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3457{
Guido van Rossum60718732001-08-28 17:47:51 +00003458 static PyObject *init_str;
3459 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460 PyObject *res;
3461
3462 if (meth == NULL)
3463 return -1;
3464 res = PyObject_Call(meth, args, kwds);
3465 Py_DECREF(meth);
3466 if (res == NULL)
3467 return -1;
3468 Py_DECREF(res);
3469 return 0;
3470}
3471
3472static PyObject *
3473slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3474{
3475 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3476 PyObject *newargs, *x;
3477 int i, n;
3478
3479 if (func == NULL)
3480 return NULL;
3481 assert(PyTuple_Check(args));
3482 n = PyTuple_GET_SIZE(args);
3483 newargs = PyTuple_New(n+1);
3484 if (newargs == NULL)
3485 return NULL;
3486 Py_INCREF(type);
3487 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3488 for (i = 0; i < n; i++) {
3489 x = PyTuple_GET_ITEM(args, i);
3490 Py_INCREF(x);
3491 PyTuple_SET_ITEM(newargs, i+1, x);
3492 }
3493 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003494 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003495 Py_DECREF(func);
3496 return x;
3497}
3498
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003499
3500/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3501 functions. The offsets here are relative to the 'etype' structure, which
3502 incorporates the additional structures used for numbers, sequences and
3503 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3504 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003505 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3506 terminated with an all-zero entry. (This table is further initialized and
3507 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003508
Guido van Rossum6d204072001-10-21 00:44:31 +00003509typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003510
3511#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003512#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003513#undef ETSLOT
3514#undef SQSLOT
3515#undef MPSLOT
3516#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003517#undef UNSLOT
3518#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003519#undef BINSLOT
3520#undef RBINSLOT
3521
Guido van Rossum6d204072001-10-21 00:44:31 +00003522#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3523 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003524#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3525 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3526 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003527#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3528 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3529#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3530 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3531#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3532 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3533#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3534 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3535#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3536 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3537 "x." NAME "() <==> " DOC)
3538#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3539 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3540 "x." NAME "(y) <==> x" DOC "y")
3541#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3542 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3543 "x." NAME "(y) <==> x" DOC "y")
3544#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3545 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3546 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003547
3548static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003549 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3550 "x.__len__() <==> len(x)"),
3551 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3552 "x.__add__(y) <==> x+y"),
3553 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3554 "x.__mul__(n) <==> x*n"),
3555 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3556 "x.__rmul__(n) <==> n*x"),
3557 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3558 "x.__getitem__(y) <==> x[y]"),
3559 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3560 "x.__getslice__(i, j) <==> x[i:j]"),
3561 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3562 "x.__setitem__(i, y) <==> x[i]=y"),
3563 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3564 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003565 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003566 wrap_intintobjargproc,
3567 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3568 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3569 "x.__delslice__(i, j) <==> del x[i:j]"),
3570 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3571 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003572 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003573 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003574 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003575 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003576
Guido van Rossum6d204072001-10-21 00:44:31 +00003577 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3578 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003579 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003580 wrap_binaryfunc,
3581 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003582 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003583 wrap_objobjargproc,
3584 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003585 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003586 wrap_delitem,
3587 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003588
Guido van Rossum6d204072001-10-21 00:44:31 +00003589 BINSLOT("__add__", nb_add, slot_nb_add,
3590 "+"),
3591 RBINSLOT("__radd__", nb_add, slot_nb_add,
3592 "+"),
3593 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3594 "-"),
3595 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3596 "-"),
3597 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3598 "*"),
3599 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3600 "*"),
3601 BINSLOT("__div__", nb_divide, slot_nb_divide,
3602 "/"),
3603 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3604 "/"),
3605 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3606 "%"),
3607 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3608 "%"),
3609 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3610 "divmod(x, y)"),
3611 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3612 "divmod(y, x)"),
3613 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3614 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3615 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3616 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3617 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3618 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3619 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3620 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003621 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003622 "x != 0"),
3623 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3624 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3625 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3626 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3627 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3628 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3629 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3630 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3631 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3632 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3633 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3634 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3635 "x.__coerce__(y) <==> coerce(x, y)"),
3636 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3637 "int(x)"),
3638 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3639 "long(x)"),
3640 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3641 "float(x)"),
3642 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3643 "oct(x)"),
3644 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3645 "hex(x)"),
3646 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3647 wrap_binaryfunc, "+"),
3648 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3649 wrap_binaryfunc, "-"),
3650 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3651 wrap_binaryfunc, "*"),
3652 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3653 wrap_binaryfunc, "/"),
3654 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3655 wrap_binaryfunc, "%"),
3656 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3657 wrap_ternaryfunc, "**"),
3658 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3659 wrap_binaryfunc, "<<"),
3660 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3661 wrap_binaryfunc, ">>"),
3662 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3663 wrap_binaryfunc, "&"),
3664 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3665 wrap_binaryfunc, "^"),
3666 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3667 wrap_binaryfunc, "|"),
3668 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3669 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3670 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3671 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3672 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3673 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3674 IBSLOT("__itruediv__", nb_inplace_true_divide,
3675 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003676
Guido van Rossum6d204072001-10-21 00:44:31 +00003677 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3678 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003679 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003680 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3681 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003682 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003683 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3684 "x.__cmp__(y) <==> cmp(x,y)"),
3685 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3686 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003687 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3688 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003689 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003690 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3691 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3692 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3693 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3694 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3695 "x.__setattr__('name', value) <==> x.name = value"),
3696 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3697 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3698 "x.__delattr__('name') <==> del x.name"),
3699 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3700 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3701 "x.__lt__(y) <==> x<y"),
3702 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3703 "x.__le__(y) <==> x<=y"),
3704 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3705 "x.__eq__(y) <==> x==y"),
3706 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3707 "x.__ne__(y) <==> x!=y"),
3708 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3709 "x.__gt__(y) <==> x>y"),
3710 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3711 "x.__ge__(y) <==> x>=y"),
3712 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3713 "x.__iter__() <==> iter(x)"),
3714 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3715 "x.next() -> the next value, or raise StopIteration"),
3716 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3717 "descr.__get__(obj[, type]) -> value"),
3718 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3719 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003720 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003721 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003722 "see x.__class__.__doc__ for signature",
3723 PyWrapperFlag_KEYWORDS),
3724 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003725 {NULL}
3726};
3727
Guido van Rossumc334df52002-04-04 23:44:47 +00003728/* Given a type pointer and an offset gotten from a slotdef entry, return a
3729 pointer to the actual slot. This is not quite the same as simply adding
3730 the offset to the type pointer, since it takes care to indirect through the
3731 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3732 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003733static void **
3734slotptr(PyTypeObject *type, int offset)
3735{
3736 char *ptr;
3737
3738 assert(offset >= 0);
3739 assert(offset < offsetof(etype, as_buffer));
3740 if (offset >= offsetof(etype, as_mapping)) {
3741 ptr = (void *)type->tp_as_mapping;
3742 offset -= offsetof(etype, as_mapping);
3743 }
3744 else if (offset >= offsetof(etype, as_sequence)) {
3745 ptr = (void *)type->tp_as_sequence;
3746 offset -= offsetof(etype, as_sequence);
3747 }
3748 else if (offset >= offsetof(etype, as_number)) {
3749 ptr = (void *)type->tp_as_number;
3750 offset -= offsetof(etype, as_number);
3751 }
3752 else {
3753 ptr = (void *)type;
3754 }
3755 if (ptr != NULL)
3756 ptr += offset;
3757 return (void **)ptr;
3758}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003759
Guido van Rossumc334df52002-04-04 23:44:47 +00003760/* Length of array of slotdef pointers used to store slots with the
3761 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3762 the same __name__, for any __name__. Since that's a static property, it is
3763 appropriate to declare fixed-size arrays for this. */
3764#define MAX_EQUIV 10
3765
3766/* Return a slot pointer for a given name, but ONLY if the attribute has
3767 exactly one slot function. The name must be an interned string. */
3768static void **
3769resolve_slotdups(PyTypeObject *type, PyObject *name)
3770{
3771 /* XXX Maybe this could be optimized more -- but is it worth it? */
3772
3773 /* pname and ptrs act as a little cache */
3774 static PyObject *pname;
3775 static slotdef *ptrs[MAX_EQUIV];
3776 slotdef *p, **pp;
3777 void **res, **ptr;
3778
3779 if (pname != name) {
3780 /* Collect all slotdefs that match name into ptrs. */
3781 pname = name;
3782 pp = ptrs;
3783 for (p = slotdefs; p->name_strobj; p++) {
3784 if (p->name_strobj == name)
3785 *pp++ = p;
3786 }
3787 *pp = NULL;
3788 }
3789
3790 /* Look in all matching slots of the type; if exactly one of these has
3791 a filled-in slot, return its value. Otherwise return NULL. */
3792 res = NULL;
3793 for (pp = ptrs; *pp; pp++) {
3794 ptr = slotptr(type, (*pp)->offset);
3795 if (ptr == NULL || *ptr == NULL)
3796 continue;
3797 if (res != NULL)
3798 return NULL;
3799 res = ptr;
3800 }
3801 return res;
3802}
3803
3804/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3805 does some incredibly complex thinking and then sticks something into the
3806 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3807 interests, and then stores a generic wrapper or a specific function into
3808 the slot.) Return a pointer to the next slotdef with a different offset,
3809 because that's convenient for fixup_slot_dispatchers(). */
3810static slotdef *
3811update_one_slot(PyTypeObject *type, slotdef *p)
3812{
3813 PyObject *descr;
3814 PyWrapperDescrObject *d;
3815 void *generic = NULL, *specific = NULL;
3816 int use_generic = 0;
3817 int offset = p->offset;
3818 void **ptr = slotptr(type, offset);
3819
3820 if (ptr == NULL) {
3821 do {
3822 ++p;
3823 } while (p->offset == offset);
3824 return p;
3825 }
3826 do {
3827 descr = _PyType_Lookup(type, p->name_strobj);
3828 if (descr == NULL)
3829 continue;
3830 if (descr->ob_type == &PyWrapperDescr_Type) {
3831 void **tptr = resolve_slotdups(type, p->name_strobj);
3832 if (tptr == NULL || tptr == ptr)
3833 generic = p->function;
3834 d = (PyWrapperDescrObject *)descr;
3835 if (d->d_base->wrapper == p->wrapper &&
3836 PyType_IsSubtype(type, d->d_type))
3837 {
3838 if (specific == NULL ||
3839 specific == d->d_wrapped)
3840 specific = d->d_wrapped;
3841 else
3842 use_generic = 1;
3843 }
3844 }
3845 else {
3846 use_generic = 1;
3847 generic = p->function;
3848 }
3849 } while ((++p)->offset == offset);
3850 if (specific && !use_generic)
3851 *ptr = specific;
3852 else
3853 *ptr = generic;
3854 return p;
3855}
3856
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003857staticforward int recurse_down_subclasses(PyTypeObject *type,
3858 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003859
Guido van Rossumc334df52002-04-04 23:44:47 +00003860/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3861 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003862static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003863update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003864{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003865 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003866
Guido van Rossumc334df52002-04-04 23:44:47 +00003867 for (pp = pp0; *pp; pp++)
3868 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003869 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003870}
3871
Guido van Rossumc334df52002-04-04 23:44:47 +00003872/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3873 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003874static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003875recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003876{
3877 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003878 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003879 int i, n;
3880
3881 subclasses = type->tp_subclasses;
3882 if (subclasses == NULL)
3883 return 0;
3884 assert(PyList_Check(subclasses));
3885 n = PyList_GET_SIZE(subclasses);
3886 for (i = 0; i < n; i++) {
3887 ref = PyList_GET_ITEM(subclasses, i);
3888 assert(PyWeakref_CheckRef(ref));
3889 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3890 if (subclass == NULL)
3891 continue;
3892 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003893 /* Avoid recursing down into unaffected classes */
3894 dict = subclass->tp_dict;
3895 if (dict != NULL && PyDict_Check(dict) &&
3896 PyDict_GetItem(dict, name) != NULL)
3897 continue;
3898 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003899 return -1;
3900 }
3901 return 0;
3902}
3903
Guido van Rossumc334df52002-04-04 23:44:47 +00003904/* Comparison function for qsort() to compare slotdefs by their offset, and
3905 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003906static int
3907slotdef_cmp(const void *aa, const void *bb)
3908{
3909 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3910 int c = a->offset - b->offset;
3911 if (c != 0)
3912 return c;
3913 else
3914 return a - b;
3915}
3916
Guido van Rossumc334df52002-04-04 23:44:47 +00003917/* Initialize the slotdefs table by adding interned string objects for the
3918 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003919static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003920init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003921{
3922 slotdef *p;
3923 static int initialized = 0;
3924
3925 if (initialized)
3926 return;
3927 for (p = slotdefs; p->name; p++) {
3928 p->name_strobj = PyString_InternFromString(p->name);
3929 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00003930 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003931 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003932 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3933 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003934 initialized = 1;
3935}
3936
Guido van Rossumc334df52002-04-04 23:44:47 +00003937/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003938static int
3939update_slot(PyTypeObject *type, PyObject *name)
3940{
Guido van Rossumc334df52002-04-04 23:44:47 +00003941 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003942 slotdef *p;
3943 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003944 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003945
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003946 init_slotdefs();
3947 pp = ptrs;
3948 for (p = slotdefs; p->name; p++) {
3949 /* XXX assume name is interned! */
3950 if (p->name_strobj == name)
3951 *pp++ = p;
3952 }
3953 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003954 for (pp = ptrs; *pp; pp++) {
3955 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003956 offset = p->offset;
3957 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003958 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003959 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003960 }
Guido van Rossumc334df52002-04-04 23:44:47 +00003961 if (ptrs[0] == NULL)
3962 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003963 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003964}
3965
Guido van Rossumc334df52002-04-04 23:44:47 +00003966/* Store the proper functions in the slot dispatches at class (type)
3967 definition time, based upon which operations the class overrides in its
3968 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003970fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003972 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003974 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00003975 for (p = slotdefs; p->name; )
3976 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003978
Guido van Rossum6d204072001-10-21 00:44:31 +00003979/* This function is called by PyType_Ready() to populate the type's
3980 dictionary with method descriptors for function slots. For each
3981 function slot (like tp_repr) that's defined in the type, one or
3982 more corresponding descriptors are added in the type's tp_dict
3983 dictionary under the appropriate name (like __repr__). Some
3984 function slots cause more than one descriptor to be added (for
3985 example, the nb_add slot adds both __add__ and __radd__
3986 descriptors) and some function slots compete for the same
3987 descriptor (for example both sq_item and mp_subscript generate a
3988 __getitem__ descriptor). This only adds new descriptors and
3989 doesn't overwrite entries in tp_dict that were previously
3990 defined. The descriptors contain a reference to the C function
3991 they must call, so that it's safe if they are copied into a
3992 subtype's __dict__ and the subtype has a different C function in
3993 its slot -- calling the method defined by the descriptor will call
3994 the C function that was used to create it, rather than the C
3995 function present in the slot when it is called. (This is important
3996 because a subtype may have a C function in the slot that calls the
3997 method from the dictionary, and we want to avoid infinite recursion
3998 here.) */
3999
4000static int
4001add_operators(PyTypeObject *type)
4002{
4003 PyObject *dict = type->tp_dict;
4004 slotdef *p;
4005 PyObject *descr;
4006 void **ptr;
4007
4008 init_slotdefs();
4009 for (p = slotdefs; p->name; p++) {
4010 if (p->wrapper == NULL)
4011 continue;
4012 ptr = slotptr(type, p->offset);
4013 if (!ptr || !*ptr)
4014 continue;
4015 if (PyDict_GetItem(dict, p->name_strobj))
4016 continue;
4017 descr = PyDescr_NewWrapper(type, p, *ptr);
4018 if (descr == NULL)
4019 return -1;
4020 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4021 return -1;
4022 Py_DECREF(descr);
4023 }
4024 if (type->tp_new != NULL) {
4025 if (add_tp_new_wrapper(type) < 0)
4026 return -1;
4027 }
4028 return 0;
4029}
4030
Guido van Rossum705f0f52001-08-24 16:47:00 +00004031
4032/* Cooperative 'super' */
4033
4034typedef struct {
4035 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004036 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004037 PyObject *obj;
4038} superobject;
4039
Guido van Rossum6f799372001-09-20 20:46:19 +00004040static PyMemberDef super_members[] = {
4041 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4042 "the class invoking super()"},
4043 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4044 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004045 {0}
4046};
4047
Guido van Rossum705f0f52001-08-24 16:47:00 +00004048static void
4049super_dealloc(PyObject *self)
4050{
4051 superobject *su = (superobject *)self;
4052
Guido van Rossum048eb752001-10-02 21:24:57 +00004053 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004054 Py_XDECREF(su->obj);
4055 Py_XDECREF(su->type);
4056 self->ob_type->tp_free(self);
4057}
4058
4059static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004060super_repr(PyObject *self)
4061{
4062 superobject *su = (superobject *)self;
4063
4064 if (su->obj)
4065 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004066 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004067 su->type ? su->type->tp_name : "NULL",
4068 su->obj->ob_type->tp_name);
4069 else
4070 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004071 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004072 su->type ? su->type->tp_name : "NULL");
4073}
4074
4075static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004076super_getattro(PyObject *self, PyObject *name)
4077{
4078 superobject *su = (superobject *)self;
4079
4080 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004081 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004082 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004083 descrgetfunc f;
4084 int i, n;
4085
Guido van Rossum155db9a2002-04-02 17:53:47 +00004086 starttype = su->obj->ob_type;
4087 mro = starttype->tp_mro;
4088
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004089 if (mro == NULL)
4090 n = 0;
4091 else {
4092 assert(PyTuple_Check(mro));
4093 n = PyTuple_GET_SIZE(mro);
4094 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004095 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004096 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004097 break;
4098 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004099 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004100 starttype = (PyTypeObject *)(su->obj);
4101 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004102 if (mro == NULL)
4103 n = 0;
4104 else {
4105 assert(PyTuple_Check(mro));
4106 n = PyTuple_GET_SIZE(mro);
4107 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004108 for (i = 0; i < n; i++) {
4109 if ((PyObject *)(su->type) ==
4110 PyTuple_GET_ITEM(mro, i))
4111 break;
4112 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004113 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004114 i++;
4115 res = NULL;
4116 for (; i < n; i++) {
4117 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004118 if (PyType_Check(tmp))
4119 dict = ((PyTypeObject *)tmp)->tp_dict;
4120 else if (PyClass_Check(tmp))
4121 dict = ((PyClassObject *)tmp)->cl_dict;
4122 else
4123 continue;
4124 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004125 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004126 Py_INCREF(res);
4127 f = res->ob_type->tp_descr_get;
4128 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004129 tmp = f(res, su->obj,
4130 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004131 Py_DECREF(res);
4132 res = tmp;
4133 }
4134 return res;
4135 }
4136 }
4137 }
4138 return PyObject_GenericGetAttr(self, name);
4139}
4140
Guido van Rossum5b443c62001-12-03 15:38:28 +00004141static int
4142supercheck(PyTypeObject *type, PyObject *obj)
4143{
4144 if (!PyType_IsSubtype(obj->ob_type, type) &&
4145 !(PyType_Check(obj) &&
4146 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4147 PyErr_SetString(PyExc_TypeError,
4148 "super(type, obj): "
4149 "obj must be an instance or subtype of type");
4150 return -1;
4151 }
4152 else
4153 return 0;
4154}
4155
Guido van Rossum705f0f52001-08-24 16:47:00 +00004156static PyObject *
4157super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4158{
4159 superobject *su = (superobject *)self;
4160 superobject *new;
4161
4162 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4163 /* Not binding to an object, or already bound */
4164 Py_INCREF(self);
4165 return self;
4166 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004167 if (su->ob_type != &PySuper_Type)
4168 /* If su is an instance of a subclass of super,
4169 call its type */
4170 return PyObject_CallFunction((PyObject *)su->ob_type,
4171 "OO", su->type, obj);
4172 else {
4173 /* Inline the common case */
4174 if (supercheck(su->type, obj) < 0)
4175 return NULL;
4176 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4177 NULL, NULL);
4178 if (new == NULL)
4179 return NULL;
4180 Py_INCREF(su->type);
4181 Py_INCREF(obj);
4182 new->type = su->type;
4183 new->obj = obj;
4184 return (PyObject *)new;
4185 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004186}
4187
4188static int
4189super_init(PyObject *self, PyObject *args, PyObject *kwds)
4190{
4191 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004192 PyTypeObject *type;
4193 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004194
4195 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4196 return -1;
4197 if (obj == Py_None)
4198 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004199 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004200 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004201 Py_INCREF(type);
4202 Py_XINCREF(obj);
4203 su->type = type;
4204 su->obj = obj;
4205 return 0;
4206}
4207
4208static char super_doc[] =
4209"super(type) -> unbound super object\n"
4210"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004211"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004212"Typical use to call a cooperative superclass method:\n"
4213"class C(B):\n"
4214" def meth(self, arg):\n"
4215" super(C, self).meth(arg)";
4216
Guido van Rossum048eb752001-10-02 21:24:57 +00004217static int
4218super_traverse(PyObject *self, visitproc visit, void *arg)
4219{
4220 superobject *su = (superobject *)self;
4221 int err;
4222
4223#define VISIT(SLOT) \
4224 if (SLOT) { \
4225 err = visit((PyObject *)(SLOT), arg); \
4226 if (err) \
4227 return err; \
4228 }
4229
4230 VISIT(su->obj);
4231 VISIT(su->type);
4232
4233#undef VISIT
4234
4235 return 0;
4236}
4237
Guido van Rossum705f0f52001-08-24 16:47:00 +00004238PyTypeObject PySuper_Type = {
4239 PyObject_HEAD_INIT(&PyType_Type)
4240 0, /* ob_size */
4241 "super", /* tp_name */
4242 sizeof(superobject), /* tp_basicsize */
4243 0, /* tp_itemsize */
4244 /* methods */
4245 super_dealloc, /* tp_dealloc */
4246 0, /* tp_print */
4247 0, /* tp_getattr */
4248 0, /* tp_setattr */
4249 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004250 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004251 0, /* tp_as_number */
4252 0, /* tp_as_sequence */
4253 0, /* tp_as_mapping */
4254 0, /* tp_hash */
4255 0, /* tp_call */
4256 0, /* tp_str */
4257 super_getattro, /* tp_getattro */
4258 0, /* tp_setattro */
4259 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004260 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4261 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004262 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004263 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004264 0, /* tp_clear */
4265 0, /* tp_richcompare */
4266 0, /* tp_weaklistoffset */
4267 0, /* tp_iter */
4268 0, /* tp_iternext */
4269 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004270 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004271 0, /* tp_getset */
4272 0, /* tp_base */
4273 0, /* tp_dict */
4274 super_descr_get, /* tp_descr_get */
4275 0, /* tp_descr_set */
4276 0, /* tp_dictoffset */
4277 super_init, /* tp_init */
4278 PyType_GenericAlloc, /* tp_alloc */
4279 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004280 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004281};