blob: 51ed4301fde2c54e30779ab09d392af2c80e399e [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))
Tim Peters6d483d32001-10-06 21:27:34 +0000193 obj = _PyObject_GC_Malloc(type, nitems);
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) {
1190 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
1195 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 */
Guido van Rossum048eb752001-10-02 21:24:57 +00001497 _PyObject_GC_Del, /* tp_free */
1498 (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
1608 if (!PyType_Check(value)) {
1609 PyErr_Format(PyExc_TypeError,
1610 "__class__ must be set to new-style class, not '%s' object",
1611 value->ob_type->tp_name);
1612 return -1;
1613 }
1614 new = (PyTypeObject *)value;
1615 newbase = new;
1616 oldbase = old;
1617 while (equiv_structs(newbase, newbase->tp_base))
1618 newbase = newbase->tp_base;
1619 while (equiv_structs(oldbase, oldbase->tp_base))
1620 oldbase = oldbase->tp_base;
1621 if (newbase != oldbase &&
1622 (newbase->tp_base != oldbase->tp_base ||
1623 !same_slots_added(newbase, oldbase))) {
1624 PyErr_Format(PyExc_TypeError,
1625 "__class__ assignment: "
1626 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001627 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001628 old->tp_name);
1629 return -1;
1630 }
1631 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1632 Py_INCREF(new);
1633 }
1634 self->ob_type = new;
1635 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1636 Py_DECREF(old);
1637 }
1638 return 0;
1639}
1640
1641static PyGetSetDef object_getsets[] = {
1642 {"__class__", object_get_class, object_set_class,
1643 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001644 {0}
1645};
1646
Guido van Rossum3926a632001-09-25 16:25:58 +00001647static PyObject *
1648object_reduce(PyObject *self, PyObject *args)
1649{
1650 /* Call copy_reg._reduce(self) */
1651 static PyObject *copy_reg_str;
1652 PyObject *copy_reg, *res;
1653
1654 if (!copy_reg_str) {
1655 copy_reg_str = PyString_InternFromString("copy_reg");
1656 if (copy_reg_str == NULL)
1657 return NULL;
1658 }
1659 copy_reg = PyImport_Import(copy_reg_str);
1660 if (!copy_reg)
1661 return NULL;
1662 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1663 Py_DECREF(copy_reg);
1664 return res;
1665}
1666
1667static PyMethodDef object_methods[] = {
1668 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1669 {0}
1670};
1671
Tim Peters6d6c1a32001-08-02 04:15:00 +00001672PyTypeObject PyBaseObject_Type = {
1673 PyObject_HEAD_INIT(&PyType_Type)
1674 0, /* ob_size */
1675 "object", /* tp_name */
1676 sizeof(PyObject), /* tp_basicsize */
1677 0, /* tp_itemsize */
1678 (destructor)object_dealloc, /* tp_dealloc */
1679 0, /* tp_print */
1680 0, /* tp_getattr */
1681 0, /* tp_setattr */
1682 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001683 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 0, /* tp_as_number */
1685 0, /* tp_as_sequence */
1686 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001687 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001689 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001691 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001692 0, /* tp_as_buffer */
1693 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1694 "The most base type", /* tp_doc */
1695 0, /* tp_traverse */
1696 0, /* tp_clear */
1697 0, /* tp_richcompare */
1698 0, /* tp_weaklistoffset */
1699 0, /* tp_iter */
1700 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001701 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001702 0, /* tp_members */
1703 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704 0, /* tp_base */
1705 0, /* tp_dict */
1706 0, /* tp_descr_get */
1707 0, /* tp_descr_set */
1708 0, /* tp_dictoffset */
1709 object_init, /* tp_init */
1710 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001711 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001712 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713};
1714
1715
1716/* Initialize the __dict__ in a type object */
1717
Fred Drake7bf97152002-03-28 05:33:33 +00001718static PyObject *
1719create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1720{
1721 PyObject *cfunc;
1722 PyObject *result;
1723
1724 cfunc = PyCFunction_New(meth, NULL);
1725 if (cfunc == NULL)
1726 return NULL;
1727 result = func(cfunc);
1728 Py_DECREF(cfunc);
1729 return result;
1730}
1731
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732static int
1733add_methods(PyTypeObject *type, PyMethodDef *meth)
1734{
Guido van Rossum687ae002001-10-15 22:03:32 +00001735 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001736
1737 for (; meth->ml_name != NULL; meth++) {
1738 PyObject *descr;
1739 if (PyDict_GetItemString(dict, meth->ml_name))
1740 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001741 if (meth->ml_flags & METH_CLASS) {
1742 if (meth->ml_flags & METH_STATIC) {
1743 PyErr_SetString(PyExc_ValueError,
1744 "method cannot be both class and static");
1745 return -1;
1746 }
1747 descr = create_specialmethod(meth, PyClassMethod_New);
1748 }
1749 else if (meth->ml_flags & METH_STATIC) {
1750 descr = create_specialmethod(meth, PyStaticMethod_New);
1751 }
1752 else {
1753 descr = PyDescr_NewMethod(type, meth);
1754 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001755 if (descr == NULL)
1756 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001757 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758 return -1;
1759 Py_DECREF(descr);
1760 }
1761 return 0;
1762}
1763
1764static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001765add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766{
Guido van Rossum687ae002001-10-15 22:03:32 +00001767 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768
1769 for (; memb->name != NULL; memb++) {
1770 PyObject *descr;
1771 if (PyDict_GetItemString(dict, memb->name))
1772 continue;
1773 descr = PyDescr_NewMember(type, memb);
1774 if (descr == NULL)
1775 return -1;
1776 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1777 return -1;
1778 Py_DECREF(descr);
1779 }
1780 return 0;
1781}
1782
1783static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001784add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785{
Guido van Rossum687ae002001-10-15 22:03:32 +00001786 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787
1788 for (; gsp->name != NULL; gsp++) {
1789 PyObject *descr;
1790 if (PyDict_GetItemString(dict, gsp->name))
1791 continue;
1792 descr = PyDescr_NewGetSet(type, gsp);
1793
1794 if (descr == NULL)
1795 return -1;
1796 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1797 return -1;
1798 Py_DECREF(descr);
1799 }
1800 return 0;
1801}
1802
Guido van Rossum13d52f02001-08-10 21:24:08 +00001803static void
1804inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805{
1806 int oldsize, newsize;
1807
Guido van Rossum13d52f02001-08-10 21:24:08 +00001808 /* Special flag magic */
1809 if (!type->tp_as_buffer && base->tp_as_buffer) {
1810 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1811 type->tp_flags |=
1812 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1813 }
1814 if (!type->tp_as_sequence && base->tp_as_sequence) {
1815 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1816 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1817 }
1818 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1819 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1820 if ((!type->tp_as_number && base->tp_as_number) ||
1821 (!type->tp_as_sequence && base->tp_as_sequence)) {
1822 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1823 if (!type->tp_as_number && !type->tp_as_sequence) {
1824 type->tp_flags |= base->tp_flags &
1825 Py_TPFLAGS_HAVE_INPLACEOPS;
1826 }
1827 }
1828 /* Wow */
1829 }
1830 if (!type->tp_as_number && base->tp_as_number) {
1831 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1832 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1833 }
1834
1835 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001836 oldsize = base->tp_basicsize;
1837 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1838 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1839 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001840 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1841 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001842 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001843 if (type->tp_traverse == NULL)
1844 type->tp_traverse = base->tp_traverse;
1845 if (type->tp_clear == NULL)
1846 type->tp_clear = base->tp_clear;
1847 }
1848 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001849 /* The condition below could use some explanation.
1850 It appears that tp_new is not inherited for static types
1851 whose base class is 'object'; this seems to be a precaution
1852 so that old extension types don't suddenly become
1853 callable (object.__new__ wouldn't insure the invariants
1854 that the extension type's own factory function ensures).
1855 Heap types, of course, are under our control, so they do
1856 inherit tp_new; static extension types that specify some
1857 other built-in type as the default are considered
1858 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001859 if (base != &PyBaseObject_Type ||
1860 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1861 if (type->tp_new == NULL)
1862 type->tp_new = base->tp_new;
1863 }
1864 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001865 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001866
1867 /* Copy other non-function slots */
1868
1869#undef COPYVAL
1870#define COPYVAL(SLOT) \
1871 if (type->SLOT == 0) type->SLOT = base->SLOT
1872
1873 COPYVAL(tp_itemsize);
1874 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1875 COPYVAL(tp_weaklistoffset);
1876 }
1877 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1878 COPYVAL(tp_dictoffset);
1879 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001880}
1881
1882static void
1883inherit_slots(PyTypeObject *type, PyTypeObject *base)
1884{
1885 PyTypeObject *basebase;
1886
1887#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888#undef COPYSLOT
1889#undef COPYNUM
1890#undef COPYSEQ
1891#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001892#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001893
1894#define SLOTDEFINED(SLOT) \
1895 (base->SLOT != 0 && \
1896 (basebase == NULL || base->SLOT != basebase->SLOT))
1897
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001899 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001900
1901#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1902#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1903#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001904#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905
Guido van Rossum13d52f02001-08-10 21:24:08 +00001906 /* This won't inherit indirect slots (from tp_as_number etc.)
1907 if type doesn't provide the space. */
1908
1909 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1910 basebase = base->tp_base;
1911 if (basebase->tp_as_number == NULL)
1912 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001913 COPYNUM(nb_add);
1914 COPYNUM(nb_subtract);
1915 COPYNUM(nb_multiply);
1916 COPYNUM(nb_divide);
1917 COPYNUM(nb_remainder);
1918 COPYNUM(nb_divmod);
1919 COPYNUM(nb_power);
1920 COPYNUM(nb_negative);
1921 COPYNUM(nb_positive);
1922 COPYNUM(nb_absolute);
1923 COPYNUM(nb_nonzero);
1924 COPYNUM(nb_invert);
1925 COPYNUM(nb_lshift);
1926 COPYNUM(nb_rshift);
1927 COPYNUM(nb_and);
1928 COPYNUM(nb_xor);
1929 COPYNUM(nb_or);
1930 COPYNUM(nb_coerce);
1931 COPYNUM(nb_int);
1932 COPYNUM(nb_long);
1933 COPYNUM(nb_float);
1934 COPYNUM(nb_oct);
1935 COPYNUM(nb_hex);
1936 COPYNUM(nb_inplace_add);
1937 COPYNUM(nb_inplace_subtract);
1938 COPYNUM(nb_inplace_multiply);
1939 COPYNUM(nb_inplace_divide);
1940 COPYNUM(nb_inplace_remainder);
1941 COPYNUM(nb_inplace_power);
1942 COPYNUM(nb_inplace_lshift);
1943 COPYNUM(nb_inplace_rshift);
1944 COPYNUM(nb_inplace_and);
1945 COPYNUM(nb_inplace_xor);
1946 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001947 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1948 COPYNUM(nb_true_divide);
1949 COPYNUM(nb_floor_divide);
1950 COPYNUM(nb_inplace_true_divide);
1951 COPYNUM(nb_inplace_floor_divide);
1952 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 }
1954
Guido van Rossum13d52f02001-08-10 21:24:08 +00001955 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1956 basebase = base->tp_base;
1957 if (basebase->tp_as_sequence == NULL)
1958 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 COPYSEQ(sq_length);
1960 COPYSEQ(sq_concat);
1961 COPYSEQ(sq_repeat);
1962 COPYSEQ(sq_item);
1963 COPYSEQ(sq_slice);
1964 COPYSEQ(sq_ass_item);
1965 COPYSEQ(sq_ass_slice);
1966 COPYSEQ(sq_contains);
1967 COPYSEQ(sq_inplace_concat);
1968 COPYSEQ(sq_inplace_repeat);
1969 }
1970
Guido van Rossum13d52f02001-08-10 21:24:08 +00001971 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1972 basebase = base->tp_base;
1973 if (basebase->tp_as_mapping == NULL)
1974 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001975 COPYMAP(mp_length);
1976 COPYMAP(mp_subscript);
1977 COPYMAP(mp_ass_subscript);
1978 }
1979
Tim Petersfc57ccb2001-10-12 02:38:24 +00001980 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1981 basebase = base->tp_base;
1982 if (basebase->tp_as_buffer == NULL)
1983 basebase = NULL;
1984 COPYBUF(bf_getreadbuffer);
1985 COPYBUF(bf_getwritebuffer);
1986 COPYBUF(bf_getsegcount);
1987 COPYBUF(bf_getcharbuffer);
1988 }
1989
Guido van Rossum13d52f02001-08-10 21:24:08 +00001990 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 COPYSLOT(tp_dealloc);
1993 COPYSLOT(tp_print);
1994 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1995 type->tp_getattr = base->tp_getattr;
1996 type->tp_getattro = base->tp_getattro;
1997 }
1998 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1999 type->tp_setattr = base->tp_setattr;
2000 type->tp_setattro = base->tp_setattro;
2001 }
2002 /* tp_compare see tp_richcompare */
2003 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002004 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002005 COPYSLOT(tp_call);
2006 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002008 if (type->tp_compare == NULL &&
2009 type->tp_richcompare == NULL &&
2010 type->tp_hash == NULL)
2011 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 type->tp_compare = base->tp_compare;
2013 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002014 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015 }
2016 }
2017 else {
2018 COPYSLOT(tp_compare);
2019 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2021 COPYSLOT(tp_iter);
2022 COPYSLOT(tp_iternext);
2023 }
2024 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2025 COPYSLOT(tp_descr_get);
2026 COPYSLOT(tp_descr_set);
2027 COPYSLOT(tp_dictoffset);
2028 COPYSLOT(tp_init);
2029 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002031 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033}
2034
Guido van Rossum13d52f02001-08-10 21:24:08 +00002035staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002036staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002037
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002039PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002041 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042 PyTypeObject *base;
2043 int i, n;
2044
Guido van Rossumd614f972001-08-10 17:39:49 +00002045 if (type->tp_flags & Py_TPFLAGS_READY) {
2046 assert(type->tp_dict != NULL);
2047 return 0;
2048 }
2049 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002050
2051 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052
Guido van Rossumf884b742001-12-17 17:14:22 +00002053 /* Initialize ob_type if NULL. This means extensions that want to be
2054 compilable separately on Windows can call PyType_Ready() instead of
2055 initializing the ob_type field of their type objects. */
2056 if (type->ob_type == NULL)
2057 type->ob_type = &PyType_Type;
2058
Tim Peters6d6c1a32001-08-02 04:15:00 +00002059 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2060 base = type->tp_base;
2061 if (base == NULL && type != &PyBaseObject_Type)
2062 base = type->tp_base = &PyBaseObject_Type;
2063
2064 /* Initialize tp_bases */
2065 bases = type->tp_bases;
2066 if (bases == NULL) {
2067 if (base == NULL)
2068 bases = PyTuple_New(0);
2069 else
2070 bases = Py_BuildValue("(O)", base);
2071 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002072 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002073 type->tp_bases = bases;
2074 }
2075
2076 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002077 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002078 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002079 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002080 }
2081
Guido van Rossum687ae002001-10-15 22:03:32 +00002082 /* Initialize tp_dict */
2083 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084 if (dict == NULL) {
2085 dict = PyDict_New();
2086 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002087 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002088 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 }
2090
Guido van Rossum687ae002001-10-15 22:03:32 +00002091 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002093 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 if (type->tp_methods != NULL) {
2095 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002096 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 }
2098 if (type->tp_members != NULL) {
2099 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002100 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 }
2102 if (type->tp_getset != NULL) {
2103 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002104 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002105 }
2106
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 /* Calculate method resolution order */
2108 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002109 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110 }
2111
Guido van Rossum13d52f02001-08-10 21:24:08 +00002112 /* Inherit special flags from dominant base */
2113 if (type->tp_base != NULL)
2114 inherit_special(type, type->tp_base);
2115
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002117 bases = type->tp_mro;
2118 assert(bases != NULL);
2119 assert(PyTuple_Check(bases));
2120 n = PyTuple_GET_SIZE(bases);
2121 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002122 PyObject *b = PyTuple_GET_ITEM(bases, i);
2123 if (PyType_Check(b))
2124 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002125 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002127 /* if the type dictionary doesn't contain a __doc__, set it from
2128 the tp_doc slot.
2129 */
2130 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2131 if (type->tp_doc != NULL) {
2132 PyObject *doc = PyString_FromString(type->tp_doc);
2133 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2134 Py_DECREF(doc);
2135 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002136 PyDict_SetItemString(type->tp_dict,
2137 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002138 }
2139 }
2140
Guido van Rossum13d52f02001-08-10 21:24:08 +00002141 /* Some more special stuff */
2142 base = type->tp_base;
2143 if (base != NULL) {
2144 if (type->tp_as_number == NULL)
2145 type->tp_as_number = base->tp_as_number;
2146 if (type->tp_as_sequence == NULL)
2147 type->tp_as_sequence = base->tp_as_sequence;
2148 if (type->tp_as_mapping == NULL)
2149 type->tp_as_mapping = base->tp_as_mapping;
2150 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002151
Guido van Rossum1c450732001-10-08 15:18:27 +00002152 /* Link into each base class's list of subclasses */
2153 bases = type->tp_bases;
2154 n = PyTuple_GET_SIZE(bases);
2155 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002156 PyObject *b = PyTuple_GET_ITEM(bases, i);
2157 if (PyType_Check(b) &&
2158 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002159 goto error;
2160 }
2161
Guido van Rossum13d52f02001-08-10 21:24:08 +00002162 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002163 assert(type->tp_dict != NULL);
2164 type->tp_flags =
2165 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002167
2168 error:
2169 type->tp_flags &= ~Py_TPFLAGS_READYING;
2170 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002171}
2172
Guido van Rossum1c450732001-10-08 15:18:27 +00002173static int
2174add_subclass(PyTypeObject *base, PyTypeObject *type)
2175{
2176 int i;
2177 PyObject *list, *ref, *new;
2178
2179 list = base->tp_subclasses;
2180 if (list == NULL) {
2181 base->tp_subclasses = list = PyList_New(0);
2182 if (list == NULL)
2183 return -1;
2184 }
2185 assert(PyList_Check(list));
2186 new = PyWeakref_NewRef((PyObject *)type, NULL);
2187 i = PyList_GET_SIZE(list);
2188 while (--i >= 0) {
2189 ref = PyList_GET_ITEM(list, i);
2190 assert(PyWeakref_CheckRef(ref));
2191 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2192 return PyList_SetItem(list, i, new);
2193 }
2194 i = PyList_Append(list, new);
2195 Py_DECREF(new);
2196 return i;
2197}
2198
Tim Peters6d6c1a32001-08-02 04:15:00 +00002199
2200/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2201
2202/* There's a wrapper *function* for each distinct function typedef used
2203 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2204 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2205 Most tables have only one entry; the tables for binary operators have two
2206 entries, one regular and one with reversed arguments. */
2207
2208static PyObject *
2209wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2210{
2211 inquiry func = (inquiry)wrapped;
2212 int res;
2213
2214 if (!PyArg_ParseTuple(args, ""))
2215 return NULL;
2216 res = (*func)(self);
2217 if (res == -1 && PyErr_Occurred())
2218 return NULL;
2219 return PyInt_FromLong((long)res);
2220}
2221
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222static PyObject *
2223wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2224{
2225 binaryfunc func = (binaryfunc)wrapped;
2226 PyObject *other;
2227
2228 if (!PyArg_ParseTuple(args, "O", &other))
2229 return NULL;
2230 return (*func)(self, other);
2231}
2232
2233static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002234wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2235{
2236 binaryfunc func = (binaryfunc)wrapped;
2237 PyObject *other;
2238
2239 if (!PyArg_ParseTuple(args, "O", &other))
2240 return NULL;
2241 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002242 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002243 Py_INCREF(Py_NotImplemented);
2244 return Py_NotImplemented;
2245 }
2246 return (*func)(self, other);
2247}
2248
2249static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2251{
2252 binaryfunc func = (binaryfunc)wrapped;
2253 PyObject *other;
2254
2255 if (!PyArg_ParseTuple(args, "O", &other))
2256 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002257 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002258 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002259 Py_INCREF(Py_NotImplemented);
2260 return Py_NotImplemented;
2261 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262 return (*func)(other, self);
2263}
2264
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002265static PyObject *
2266wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2267{
2268 coercion func = (coercion)wrapped;
2269 PyObject *other, *res;
2270 int ok;
2271
2272 if (!PyArg_ParseTuple(args, "O", &other))
2273 return NULL;
2274 ok = func(&self, &other);
2275 if (ok < 0)
2276 return NULL;
2277 if (ok > 0) {
2278 Py_INCREF(Py_NotImplemented);
2279 return Py_NotImplemented;
2280 }
2281 res = PyTuple_New(2);
2282 if (res == NULL) {
2283 Py_DECREF(self);
2284 Py_DECREF(other);
2285 return NULL;
2286 }
2287 PyTuple_SET_ITEM(res, 0, self);
2288 PyTuple_SET_ITEM(res, 1, other);
2289 return res;
2290}
2291
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292static PyObject *
2293wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2294{
2295 ternaryfunc func = (ternaryfunc)wrapped;
2296 PyObject *other;
2297 PyObject *third = Py_None;
2298
2299 /* Note: This wrapper only works for __pow__() */
2300
2301 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2302 return NULL;
2303 return (*func)(self, other, third);
2304}
2305
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002306static PyObject *
2307wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2308{
2309 ternaryfunc func = (ternaryfunc)wrapped;
2310 PyObject *other;
2311 PyObject *third = Py_None;
2312
2313 /* Note: This wrapper only works for __pow__() */
2314
2315 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2316 return NULL;
2317 return (*func)(other, self, third);
2318}
2319
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320static PyObject *
2321wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2322{
2323 unaryfunc func = (unaryfunc)wrapped;
2324
2325 if (!PyArg_ParseTuple(args, ""))
2326 return NULL;
2327 return (*func)(self);
2328}
2329
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330static PyObject *
2331wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2332{
2333 intargfunc func = (intargfunc)wrapped;
2334 int i;
2335
2336 if (!PyArg_ParseTuple(args, "i", &i))
2337 return NULL;
2338 return (*func)(self, i);
2339}
2340
Guido van Rossum5d815f32001-08-17 21:57:47 +00002341static int
2342getindex(PyObject *self, PyObject *arg)
2343{
2344 int i;
2345
2346 i = PyInt_AsLong(arg);
2347 if (i == -1 && PyErr_Occurred())
2348 return -1;
2349 if (i < 0) {
2350 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2351 if (sq && sq->sq_length) {
2352 int n = (*sq->sq_length)(self);
2353 if (n < 0)
2354 return -1;
2355 i += n;
2356 }
2357 }
2358 return i;
2359}
2360
2361static PyObject *
2362wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2363{
2364 intargfunc func = (intargfunc)wrapped;
2365 PyObject *arg;
2366 int i;
2367
Guido van Rossumf4593e02001-10-03 12:09:30 +00002368 if (PyTuple_GET_SIZE(args) == 1) {
2369 arg = PyTuple_GET_ITEM(args, 0);
2370 i = getindex(self, arg);
2371 if (i == -1 && PyErr_Occurred())
2372 return NULL;
2373 return (*func)(self, i);
2374 }
2375 PyArg_ParseTuple(args, "O", &arg);
2376 assert(PyErr_Occurred());
2377 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002378}
2379
Tim Peters6d6c1a32001-08-02 04:15:00 +00002380static PyObject *
2381wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2382{
2383 intintargfunc func = (intintargfunc)wrapped;
2384 int i, j;
2385
2386 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2387 return NULL;
2388 return (*func)(self, i, j);
2389}
2390
Tim Peters6d6c1a32001-08-02 04:15:00 +00002391static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002392wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393{
2394 intobjargproc func = (intobjargproc)wrapped;
2395 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002396 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397
Guido van Rossum5d815f32001-08-17 21:57:47 +00002398 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2399 return NULL;
2400 i = getindex(self, arg);
2401 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402 return NULL;
2403 res = (*func)(self, i, value);
2404 if (res == -1 && PyErr_Occurred())
2405 return NULL;
2406 Py_INCREF(Py_None);
2407 return Py_None;
2408}
2409
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002410static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002411wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002412{
2413 intobjargproc func = (intobjargproc)wrapped;
2414 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002415 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002416
Guido van Rossum5d815f32001-08-17 21:57:47 +00002417 if (!PyArg_ParseTuple(args, "O", &arg))
2418 return NULL;
2419 i = getindex(self, arg);
2420 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002421 return NULL;
2422 res = (*func)(self, i, NULL);
2423 if (res == -1 && PyErr_Occurred())
2424 return NULL;
2425 Py_INCREF(Py_None);
2426 return Py_None;
2427}
2428
Tim Peters6d6c1a32001-08-02 04:15:00 +00002429static PyObject *
2430wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2431{
2432 intintobjargproc func = (intintobjargproc)wrapped;
2433 int i, j, res;
2434 PyObject *value;
2435
2436 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2437 return NULL;
2438 res = (*func)(self, i, j, value);
2439 if (res == -1 && PyErr_Occurred())
2440 return NULL;
2441 Py_INCREF(Py_None);
2442 return Py_None;
2443}
2444
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002445static PyObject *
2446wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2447{
2448 intintobjargproc func = (intintobjargproc)wrapped;
2449 int i, j, res;
2450
2451 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2452 return NULL;
2453 res = (*func)(self, i, j, NULL);
2454 if (res == -1 && PyErr_Occurred())
2455 return NULL;
2456 Py_INCREF(Py_None);
2457 return Py_None;
2458}
2459
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460/* XXX objobjproc is a misnomer; should be objargpred */
2461static PyObject *
2462wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2463{
2464 objobjproc func = (objobjproc)wrapped;
2465 int res;
2466 PyObject *value;
2467
2468 if (!PyArg_ParseTuple(args, "O", &value))
2469 return NULL;
2470 res = (*func)(self, value);
2471 if (res == -1 && PyErr_Occurred())
2472 return NULL;
2473 return PyInt_FromLong((long)res);
2474}
2475
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476static PyObject *
2477wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2478{
2479 objobjargproc func = (objobjargproc)wrapped;
2480 int res;
2481 PyObject *key, *value;
2482
2483 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2484 return NULL;
2485 res = (*func)(self, key, value);
2486 if (res == -1 && PyErr_Occurred())
2487 return NULL;
2488 Py_INCREF(Py_None);
2489 return Py_None;
2490}
2491
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002492static PyObject *
2493wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2494{
2495 objobjargproc func = (objobjargproc)wrapped;
2496 int res;
2497 PyObject *key;
2498
2499 if (!PyArg_ParseTuple(args, "O", &key))
2500 return NULL;
2501 res = (*func)(self, key, NULL);
2502 if (res == -1 && PyErr_Occurred())
2503 return NULL;
2504 Py_INCREF(Py_None);
2505 return Py_None;
2506}
2507
Tim Peters6d6c1a32001-08-02 04:15:00 +00002508static PyObject *
2509wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2510{
2511 cmpfunc func = (cmpfunc)wrapped;
2512 int res;
2513 PyObject *other;
2514
2515 if (!PyArg_ParseTuple(args, "O", &other))
2516 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002517 if (other->ob_type->tp_compare != func &&
2518 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002519 PyErr_Format(
2520 PyExc_TypeError,
2521 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2522 self->ob_type->tp_name,
2523 self->ob_type->tp_name,
2524 other->ob_type->tp_name);
2525 return NULL;
2526 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002527 res = (*func)(self, other);
2528 if (PyErr_Occurred())
2529 return NULL;
2530 return PyInt_FromLong((long)res);
2531}
2532
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533static PyObject *
2534wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2535{
2536 setattrofunc func = (setattrofunc)wrapped;
2537 int res;
2538 PyObject *name, *value;
2539
2540 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2541 return NULL;
2542 res = (*func)(self, name, value);
2543 if (res < 0)
2544 return NULL;
2545 Py_INCREF(Py_None);
2546 return Py_None;
2547}
2548
2549static PyObject *
2550wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2551{
2552 setattrofunc func = (setattrofunc)wrapped;
2553 int res;
2554 PyObject *name;
2555
2556 if (!PyArg_ParseTuple(args, "O", &name))
2557 return NULL;
2558 res = (*func)(self, name, NULL);
2559 if (res < 0)
2560 return NULL;
2561 Py_INCREF(Py_None);
2562 return Py_None;
2563}
2564
Tim Peters6d6c1a32001-08-02 04:15:00 +00002565static PyObject *
2566wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2567{
2568 hashfunc func = (hashfunc)wrapped;
2569 long res;
2570
2571 if (!PyArg_ParseTuple(args, ""))
2572 return NULL;
2573 res = (*func)(self);
2574 if (res == -1 && PyErr_Occurred())
2575 return NULL;
2576 return PyInt_FromLong(res);
2577}
2578
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002580wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002581{
2582 ternaryfunc func = (ternaryfunc)wrapped;
2583
Guido van Rossumc8e56452001-10-22 00:43:43 +00002584 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585}
2586
Tim Peters6d6c1a32001-08-02 04:15:00 +00002587static PyObject *
2588wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2589{
2590 richcmpfunc func = (richcmpfunc)wrapped;
2591 PyObject *other;
2592
2593 if (!PyArg_ParseTuple(args, "O", &other))
2594 return NULL;
2595 return (*func)(self, other, op);
2596}
2597
2598#undef RICHCMP_WRAPPER
2599#define RICHCMP_WRAPPER(NAME, OP) \
2600static PyObject * \
2601richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2602{ \
2603 return wrap_richcmpfunc(self, args, wrapped, OP); \
2604}
2605
Jack Jansen8e938b42001-08-08 15:29:49 +00002606RICHCMP_WRAPPER(lt, Py_LT)
2607RICHCMP_WRAPPER(le, Py_LE)
2608RICHCMP_WRAPPER(eq, Py_EQ)
2609RICHCMP_WRAPPER(ne, Py_NE)
2610RICHCMP_WRAPPER(gt, Py_GT)
2611RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002612
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613static PyObject *
2614wrap_next(PyObject *self, PyObject *args, void *wrapped)
2615{
2616 unaryfunc func = (unaryfunc)wrapped;
2617 PyObject *res;
2618
2619 if (!PyArg_ParseTuple(args, ""))
2620 return NULL;
2621 res = (*func)(self);
2622 if (res == NULL && !PyErr_Occurred())
2623 PyErr_SetNone(PyExc_StopIteration);
2624 return res;
2625}
2626
Tim Peters6d6c1a32001-08-02 04:15:00 +00002627static PyObject *
2628wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2629{
2630 descrgetfunc func = (descrgetfunc)wrapped;
2631 PyObject *obj;
2632 PyObject *type = NULL;
2633
2634 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2635 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636 return (*func)(self, obj, type);
2637}
2638
Tim Peters6d6c1a32001-08-02 04:15:00 +00002639static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002640wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002641{
2642 descrsetfunc func = (descrsetfunc)wrapped;
2643 PyObject *obj, *value;
2644 int ret;
2645
2646 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2647 return NULL;
2648 ret = (*func)(self, obj, value);
2649 if (ret < 0)
2650 return NULL;
2651 Py_INCREF(Py_None);
2652 return Py_None;
2653}
2654
Tim Peters6d6c1a32001-08-02 04:15:00 +00002655static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002656wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657{
2658 initproc func = (initproc)wrapped;
2659
Guido van Rossumc8e56452001-10-22 00:43:43 +00002660 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002661 return NULL;
2662 Py_INCREF(Py_None);
2663 return Py_None;
2664}
2665
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002667tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002668{
Barry Warsaw60f01882001-08-22 19:24:42 +00002669 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002670 PyObject *arg0, *res;
2671
2672 if (self == NULL || !PyType_Check(self))
2673 Py_FatalError("__new__() called with non-type 'self'");
2674 type = (PyTypeObject *)self;
2675 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002676 PyErr_Format(PyExc_TypeError,
2677 "%s.__new__(): not enough arguments",
2678 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002679 return NULL;
2680 }
2681 arg0 = PyTuple_GET_ITEM(args, 0);
2682 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002683 PyErr_Format(PyExc_TypeError,
2684 "%s.__new__(X): X is not a type object (%s)",
2685 type->tp_name,
2686 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002687 return NULL;
2688 }
2689 subtype = (PyTypeObject *)arg0;
2690 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002691 PyErr_Format(PyExc_TypeError,
2692 "%s.__new__(%s): %s is not a subtype of %s",
2693 type->tp_name,
2694 subtype->tp_name,
2695 subtype->tp_name,
2696 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002697 return NULL;
2698 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002699
2700 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002701 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002702 most derived base that's not a heap type is this type. */
2703 staticbase = subtype;
2704 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2705 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002706 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002707 PyErr_Format(PyExc_TypeError,
2708 "%s.__new__(%s) is not safe, use %s.__new__()",
2709 type->tp_name,
2710 subtype->tp_name,
2711 staticbase == NULL ? "?" : staticbase->tp_name);
2712 return NULL;
2713 }
2714
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002715 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2716 if (args == NULL)
2717 return NULL;
2718 res = type->tp_new(subtype, args, kwds);
2719 Py_DECREF(args);
2720 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721}
2722
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002723static struct PyMethodDef tp_new_methoddef[] = {
2724 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2725 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 {0}
2727};
2728
2729static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002730add_tp_new_wrapper(PyTypeObject *type)
2731{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002732 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002733
Guido van Rossum687ae002001-10-15 22:03:32 +00002734 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002735 return 0;
2736 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002737 if (func == NULL)
2738 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002739 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002740}
2741
Guido van Rossumf040ede2001-08-07 16:40:56 +00002742/* Slot wrappers that call the corresponding __foo__ slot. See comments
2743 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744
Guido van Rossumdc91b992001-08-08 22:26:22 +00002745#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002747FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002749 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002750 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751}
2752
Guido van Rossumdc91b992001-08-08 22:26:22 +00002753#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002754static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002755FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002757 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002758 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759}
2760
Guido van Rossumdc91b992001-08-08 22:26:22 +00002761
2762#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002764FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002766 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002767 int do_other = self->ob_type != other->ob_type && \
2768 other->ob_type->tp_as_number != NULL && \
2769 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002770 if (self->ob_type->tp_as_number != NULL && \
2771 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2772 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002773 if (do_other && \
2774 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2775 r = call_maybe( \
2776 other, ROPSTR, &rcache_str, "(O)", self); \
2777 if (r != Py_NotImplemented) \
2778 return r; \
2779 Py_DECREF(r); \
2780 do_other = 0; \
2781 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002782 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002783 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002784 if (r != Py_NotImplemented || \
2785 other->ob_type == self->ob_type) \
2786 return r; \
2787 Py_DECREF(r); \
2788 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002789 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002790 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002791 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002792 } \
2793 Py_INCREF(Py_NotImplemented); \
2794 return Py_NotImplemented; \
2795}
2796
2797#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2798 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2799
2800#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2801static PyObject * \
2802FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2803{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002804 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002805 return call_method(self, OPSTR, &cache_str, \
2806 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002807}
2808
2809static int
2810slot_sq_length(PyObject *self)
2811{
Guido van Rossum2730b132001-08-28 18:22:14 +00002812 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002813 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002814 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002815
2816 if (res == NULL)
2817 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002818 len = (int)PyInt_AsLong(res);
2819 Py_DECREF(res);
2820 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821}
2822
Guido van Rossumdc91b992001-08-08 22:26:22 +00002823SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2824SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002825
2826/* Super-optimized version of slot_sq_item.
2827 Other slots could do the same... */
2828static PyObject *
2829slot_sq_item(PyObject *self, int i)
2830{
2831 static PyObject *getitem_str;
2832 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2833 descrgetfunc f;
2834
2835 if (getitem_str == NULL) {
2836 getitem_str = PyString_InternFromString("__getitem__");
2837 if (getitem_str == NULL)
2838 return NULL;
2839 }
2840 func = _PyType_Lookup(self->ob_type, getitem_str);
2841 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002842 if ((f = func->ob_type->tp_descr_get) == NULL)
2843 Py_INCREF(func);
2844 else
2845 func = f(func, self, (PyObject *)(self->ob_type));
2846 ival = PyInt_FromLong(i);
2847 if (ival != NULL) {
2848 args = PyTuple_New(1);
2849 if (args != NULL) {
2850 PyTuple_SET_ITEM(args, 0, ival);
2851 retval = PyObject_Call(func, args, NULL);
2852 Py_XDECREF(args);
2853 Py_XDECREF(func);
2854 return retval;
2855 }
2856 }
2857 }
2858 else {
2859 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2860 }
2861 Py_XDECREF(args);
2862 Py_XDECREF(ival);
2863 Py_XDECREF(func);
2864 return NULL;
2865}
2866
Guido van Rossumdc91b992001-08-08 22:26:22 +00002867SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002868
2869static int
2870slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2871{
2872 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002873 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002874
2875 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002876 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002877 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002878 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002879 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002880 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002881 if (res == NULL)
2882 return -1;
2883 Py_DECREF(res);
2884 return 0;
2885}
2886
2887static int
2888slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2889{
2890 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002891 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002892
2893 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002894 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002895 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002896 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002897 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002898 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899 if (res == NULL)
2900 return -1;
2901 Py_DECREF(res);
2902 return 0;
2903}
2904
2905static int
2906slot_sq_contains(PyObject *self, PyObject *value)
2907{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002908 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002909 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910
Guido van Rossum55f20992001-10-01 17:18:22 +00002911 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002912
2913 if (func != NULL) {
2914 args = Py_BuildValue("(O)", value);
2915 if (args == NULL)
2916 res = NULL;
2917 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002918 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002919 Py_DECREF(args);
2920 }
2921 Py_DECREF(func);
2922 if (res == NULL)
2923 return -1;
2924 return PyObject_IsTrue(res);
2925 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002926 else if (PyErr_Occurred())
2927 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002928 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002929 return _PySequence_IterSearch(self, value,
2930 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002931 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932}
2933
Guido van Rossumdc91b992001-08-08 22:26:22 +00002934SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2935SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002936
2937#define slot_mp_length slot_sq_length
2938
Guido van Rossumdc91b992001-08-08 22:26:22 +00002939SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940
2941static int
2942slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2943{
2944 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002945 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946
2947 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002948 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002949 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002951 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002952 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953 if (res == NULL)
2954 return -1;
2955 Py_DECREF(res);
2956 return 0;
2957}
2958
Guido van Rossumdc91b992001-08-08 22:26:22 +00002959SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2960SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2961SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2962SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2963SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2964SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2965
2966staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2967
2968SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2969 nb_power, "__pow__", "__rpow__")
2970
2971static PyObject *
2972slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2973{
Guido van Rossum2730b132001-08-28 18:22:14 +00002974 static PyObject *pow_str;
2975
Guido van Rossumdc91b992001-08-08 22:26:22 +00002976 if (modulus == Py_None)
2977 return slot_nb_power_binary(self, other);
2978 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002979 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002980 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002981}
2982
2983SLOT0(slot_nb_negative, "__neg__")
2984SLOT0(slot_nb_positive, "__pos__")
2985SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002986
2987static int
2988slot_nb_nonzero(PyObject *self)
2989{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002990 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002991 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992
Guido van Rossum55f20992001-10-01 17:18:22 +00002993 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002994 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002995 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002996 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002997 func = lookup_maybe(self, "__len__", &len_str);
2998 if (func == NULL) {
2999 if (PyErr_Occurred())
3000 return -1;
3001 else
3002 return 1;
3003 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003004 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003005 res = PyObject_CallObject(func, NULL);
3006 Py_DECREF(func);
3007 if (res == NULL)
3008 return -1;
3009 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010}
3011
Guido van Rossumdc91b992001-08-08 22:26:22 +00003012SLOT0(slot_nb_invert, "__invert__")
3013SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3014SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3015SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3016SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3017SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003018
3019static int
3020slot_nb_coerce(PyObject **a, PyObject **b)
3021{
3022 static PyObject *coerce_str;
3023 PyObject *self = *a, *other = *b;
3024
3025 if (self->ob_type->tp_as_number != NULL &&
3026 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3027 PyObject *r;
3028 r = call_maybe(
3029 self, "__coerce__", &coerce_str, "(O)", other);
3030 if (r == NULL)
3031 return -1;
3032 if (r == Py_NotImplemented) {
3033 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003034 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003035 else {
3036 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3037 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003038 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003039 Py_DECREF(r);
3040 return -1;
3041 }
3042 *a = PyTuple_GET_ITEM(r, 0);
3043 Py_INCREF(*a);
3044 *b = PyTuple_GET_ITEM(r, 1);
3045 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003046 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003047 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003048 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003049 }
3050 if (other->ob_type->tp_as_number != NULL &&
3051 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3052 PyObject *r;
3053 r = call_maybe(
3054 other, "__coerce__", &coerce_str, "(O)", self);
3055 if (r == NULL)
3056 return -1;
3057 if (r == Py_NotImplemented) {
3058 Py_DECREF(r);
3059 return 1;
3060 }
3061 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3062 PyErr_SetString(PyExc_TypeError,
3063 "__coerce__ didn't return a 2-tuple");
3064 Py_DECREF(r);
3065 return -1;
3066 }
3067 *a = PyTuple_GET_ITEM(r, 1);
3068 Py_INCREF(*a);
3069 *b = PyTuple_GET_ITEM(r, 0);
3070 Py_INCREF(*b);
3071 Py_DECREF(r);
3072 return 0;
3073 }
3074 return 1;
3075}
3076
Guido van Rossumdc91b992001-08-08 22:26:22 +00003077SLOT0(slot_nb_int, "__int__")
3078SLOT0(slot_nb_long, "__long__")
3079SLOT0(slot_nb_float, "__float__")
3080SLOT0(slot_nb_oct, "__oct__")
3081SLOT0(slot_nb_hex, "__hex__")
3082SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3083SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3084SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3085SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3086SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3087SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3088SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3089SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3090SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3091SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3092SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3093SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3094 "__floordiv__", "__rfloordiv__")
3095SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3096SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3097SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098
3099static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003100half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003101{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003102 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003103 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003104 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105
Guido van Rossum60718732001-08-28 17:47:51 +00003106 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003107 if (func == NULL) {
3108 PyErr_Clear();
3109 }
3110 else {
3111 args = Py_BuildValue("(O)", other);
3112 if (args == NULL)
3113 res = NULL;
3114 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003115 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003116 Py_DECREF(args);
3117 }
3118 if (res != Py_NotImplemented) {
3119 if (res == NULL)
3120 return -2;
3121 c = PyInt_AsLong(res);
3122 Py_DECREF(res);
3123 if (c == -1 && PyErr_Occurred())
3124 return -2;
3125 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3126 }
3127 Py_DECREF(res);
3128 }
3129 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130}
3131
Guido van Rossumab3b0342001-09-18 20:38:53 +00003132/* This slot is published for the benefit of try_3way_compare in object.c */
3133int
3134_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003135{
3136 int c;
3137
Guido van Rossumab3b0342001-09-18 20:38:53 +00003138 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003139 c = half_compare(self, other);
3140 if (c <= 1)
3141 return c;
3142 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003143 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003144 c = half_compare(other, self);
3145 if (c < -1)
3146 return -2;
3147 if (c <= 1)
3148 return -c;
3149 }
3150 return (void *)self < (void *)other ? -1 :
3151 (void *)self > (void *)other ? 1 : 0;
3152}
3153
3154static PyObject *
3155slot_tp_repr(PyObject *self)
3156{
3157 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003158 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003159
Guido van Rossum60718732001-08-28 17:47:51 +00003160 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003161 if (func != NULL) {
3162 res = PyEval_CallObject(func, NULL);
3163 Py_DECREF(func);
3164 return res;
3165 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003166 PyErr_Clear();
3167 return PyString_FromFormat("<%s object at %p>",
3168 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003169}
3170
3171static PyObject *
3172slot_tp_str(PyObject *self)
3173{
3174 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003175 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003176
Guido van Rossum60718732001-08-28 17:47:51 +00003177 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003178 if (func != NULL) {
3179 res = PyEval_CallObject(func, NULL);
3180 Py_DECREF(func);
3181 return res;
3182 }
3183 else {
3184 PyErr_Clear();
3185 return slot_tp_repr(self);
3186 }
3187}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188
3189static long
3190slot_tp_hash(PyObject *self)
3191{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003192 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003193 static PyObject *hash_str, *eq_str, *cmp_str;
3194
Tim Peters6d6c1a32001-08-02 04:15:00 +00003195 long h;
3196
Guido van Rossum60718732001-08-28 17:47:51 +00003197 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003198
3199 if (func != NULL) {
3200 res = PyEval_CallObject(func, NULL);
3201 Py_DECREF(func);
3202 if (res == NULL)
3203 return -1;
3204 h = PyInt_AsLong(res);
3205 }
3206 else {
3207 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003208 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003209 if (func == NULL) {
3210 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003211 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003212 }
3213 if (func != NULL) {
3214 Py_DECREF(func);
3215 PyErr_SetString(PyExc_TypeError, "unhashable type");
3216 return -1;
3217 }
3218 PyErr_Clear();
3219 h = _Py_HashPointer((void *)self);
3220 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003221 if (h == -1 && !PyErr_Occurred())
3222 h = -2;
3223 return h;
3224}
3225
3226static PyObject *
3227slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3228{
Guido van Rossum60718732001-08-28 17:47:51 +00003229 static PyObject *call_str;
3230 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231 PyObject *res;
3232
3233 if (meth == NULL)
3234 return NULL;
3235 res = PyObject_Call(meth, args, kwds);
3236 Py_DECREF(meth);
3237 return res;
3238}
3239
Guido van Rossum14a6f832001-10-17 13:59:09 +00003240/* There are two slot dispatch functions for tp_getattro.
3241
3242 - slot_tp_getattro() is used when __getattribute__ is overridden
3243 but no __getattr__ hook is present;
3244
3245 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3246
Guido van Rossumc334df52002-04-04 23:44:47 +00003247 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3248 detects the absence of __getattr__ and then installs the simpler slot if
3249 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003250
Tim Peters6d6c1a32001-08-02 04:15:00 +00003251static PyObject *
3252slot_tp_getattro(PyObject *self, PyObject *name)
3253{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003254 static PyObject *getattribute_str = NULL;
3255 return call_method(self, "__getattribute__", &getattribute_str,
3256 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257}
3258
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003259static PyObject *
3260slot_tp_getattr_hook(PyObject *self, PyObject *name)
3261{
3262 PyTypeObject *tp = self->ob_type;
3263 PyObject *getattr, *getattribute, *res;
3264 static PyObject *getattribute_str = NULL;
3265 static PyObject *getattr_str = NULL;
3266
3267 if (getattr_str == NULL) {
3268 getattr_str = PyString_InternFromString("__getattr__");
3269 if (getattr_str == NULL)
3270 return NULL;
3271 }
3272 if (getattribute_str == NULL) {
3273 getattribute_str =
3274 PyString_InternFromString("__getattribute__");
3275 if (getattribute_str == NULL)
3276 return NULL;
3277 }
3278 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003279 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003280 /* No __getattr__ hook: use a simpler dispatcher */
3281 tp->tp_getattro = slot_tp_getattro;
3282 return slot_tp_getattro(self, name);
3283 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003284 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003285 if (getattribute == NULL ||
3286 (getattribute->ob_type == &PyWrapperDescr_Type &&
3287 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3288 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003289 res = PyObject_GenericGetAttr(self, name);
3290 else
3291 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003292 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003293 PyErr_Clear();
3294 res = PyObject_CallFunction(getattr, "OO", self, name);
3295 }
3296 return res;
3297}
3298
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299static int
3300slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3301{
3302 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003303 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304
3305 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003306 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003307 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003309 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003310 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003311 if (res == NULL)
3312 return -1;
3313 Py_DECREF(res);
3314 return 0;
3315}
3316
3317/* Map rich comparison operators to their __xx__ namesakes */
3318static char *name_op[] = {
3319 "__lt__",
3320 "__le__",
3321 "__eq__",
3322 "__ne__",
3323 "__gt__",
3324 "__ge__",
3325};
3326
3327static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003328half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003330 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003331 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003332
Guido van Rossum60718732001-08-28 17:47:51 +00003333 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003334 if (func == NULL) {
3335 PyErr_Clear();
3336 Py_INCREF(Py_NotImplemented);
3337 return Py_NotImplemented;
3338 }
3339 args = Py_BuildValue("(O)", other);
3340 if (args == NULL)
3341 res = NULL;
3342 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003343 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003344 Py_DECREF(args);
3345 }
3346 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347 return res;
3348}
3349
Guido van Rossumb8f63662001-08-15 23:57:02 +00003350/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3351static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3352
3353static PyObject *
3354slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3355{
3356 PyObject *res;
3357
3358 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3359 res = half_richcompare(self, other, op);
3360 if (res != Py_NotImplemented)
3361 return res;
3362 Py_DECREF(res);
3363 }
3364 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3365 res = half_richcompare(other, self, swapped_op[op]);
3366 if (res != Py_NotImplemented) {
3367 return res;
3368 }
3369 Py_DECREF(res);
3370 }
3371 Py_INCREF(Py_NotImplemented);
3372 return Py_NotImplemented;
3373}
3374
3375static PyObject *
3376slot_tp_iter(PyObject *self)
3377{
3378 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003379 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003380
Guido van Rossum60718732001-08-28 17:47:51 +00003381 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003382 if (func != NULL) {
3383 res = PyObject_CallObject(func, NULL);
3384 Py_DECREF(func);
3385 return res;
3386 }
3387 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003388 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003389 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003390 PyErr_SetString(PyExc_TypeError,
3391 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003392 return NULL;
3393 }
3394 Py_DECREF(func);
3395 return PySeqIter_New(self);
3396}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003397
3398static PyObject *
3399slot_tp_iternext(PyObject *self)
3400{
Guido van Rossum2730b132001-08-28 18:22:14 +00003401 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003402 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403}
3404
Guido van Rossum1a493502001-08-17 16:47:50 +00003405static PyObject *
3406slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3407{
3408 PyTypeObject *tp = self->ob_type;
3409 PyObject *get;
3410 static PyObject *get_str = NULL;
3411
3412 if (get_str == NULL) {
3413 get_str = PyString_InternFromString("__get__");
3414 if (get_str == NULL)
3415 return NULL;
3416 }
3417 get = _PyType_Lookup(tp, get_str);
3418 if (get == NULL) {
3419 /* Avoid further slowdowns */
3420 if (tp->tp_descr_get == slot_tp_descr_get)
3421 tp->tp_descr_get = NULL;
3422 Py_INCREF(self);
3423 return self;
3424 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003425 if (obj == NULL)
3426 obj = Py_None;
3427 if (type == NULL)
3428 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003429 return PyObject_CallFunction(get, "OOO", self, obj, type);
3430}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431
3432static int
3433slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3434{
Guido van Rossum2c252392001-08-24 10:13:31 +00003435 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003436 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003437
3438 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003439 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003440 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003441 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003442 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003443 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444 if (res == NULL)
3445 return -1;
3446 Py_DECREF(res);
3447 return 0;
3448}
3449
3450static int
3451slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3452{
Guido van Rossum60718732001-08-28 17:47:51 +00003453 static PyObject *init_str;
3454 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455 PyObject *res;
3456
3457 if (meth == NULL)
3458 return -1;
3459 res = PyObject_Call(meth, args, kwds);
3460 Py_DECREF(meth);
3461 if (res == NULL)
3462 return -1;
3463 Py_DECREF(res);
3464 return 0;
3465}
3466
3467static PyObject *
3468slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3469{
3470 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3471 PyObject *newargs, *x;
3472 int i, n;
3473
3474 if (func == NULL)
3475 return NULL;
3476 assert(PyTuple_Check(args));
3477 n = PyTuple_GET_SIZE(args);
3478 newargs = PyTuple_New(n+1);
3479 if (newargs == NULL)
3480 return NULL;
3481 Py_INCREF(type);
3482 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3483 for (i = 0; i < n; i++) {
3484 x = PyTuple_GET_ITEM(args, i);
3485 Py_INCREF(x);
3486 PyTuple_SET_ITEM(newargs, i+1, x);
3487 }
3488 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003489 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003490 Py_DECREF(func);
3491 return x;
3492}
3493
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003494
3495/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3496 functions. The offsets here are relative to the 'etype' structure, which
3497 incorporates the additional structures used for numbers, sequences and
3498 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3499 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003500 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3501 terminated with an all-zero entry. (This table is further initialized and
3502 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003503
Guido van Rossum6d204072001-10-21 00:44:31 +00003504typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003505
3506#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003507#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003508#undef ETSLOT
3509#undef SQSLOT
3510#undef MPSLOT
3511#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003512#undef UNSLOT
3513#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003514#undef BINSLOT
3515#undef RBINSLOT
3516
Guido van Rossum6d204072001-10-21 00:44:31 +00003517#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3518 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003519#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3520 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3521 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003522#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3523 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3524#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3525 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3526#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3527 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3528#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3529 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3530#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3531 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3532 "x." NAME "() <==> " DOC)
3533#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3534 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3535 "x." NAME "(y) <==> x" DOC "y")
3536#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3537 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3538 "x." NAME "(y) <==> x" DOC "y")
3539#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3540 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3541 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003542
3543static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003544 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3545 "x.__len__() <==> len(x)"),
3546 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3547 "x.__add__(y) <==> x+y"),
3548 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3549 "x.__mul__(n) <==> x*n"),
3550 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3551 "x.__rmul__(n) <==> n*x"),
3552 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3553 "x.__getitem__(y) <==> x[y]"),
3554 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3555 "x.__getslice__(i, j) <==> x[i:j]"),
3556 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3557 "x.__setitem__(i, y) <==> x[i]=y"),
3558 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3559 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003560 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003561 wrap_intintobjargproc,
3562 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3563 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3564 "x.__delslice__(i, j) <==> del x[i:j]"),
3565 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3566 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003567 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003568 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003569 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003570 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003571
Guido van Rossum6d204072001-10-21 00:44:31 +00003572 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3573 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003574 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003575 wrap_binaryfunc,
3576 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003577 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003578 wrap_objobjargproc,
3579 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003580 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003581 wrap_delitem,
3582 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003583
Guido van Rossum6d204072001-10-21 00:44:31 +00003584 BINSLOT("__add__", nb_add, slot_nb_add,
3585 "+"),
3586 RBINSLOT("__radd__", nb_add, slot_nb_add,
3587 "+"),
3588 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3589 "-"),
3590 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3591 "-"),
3592 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3593 "*"),
3594 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3595 "*"),
3596 BINSLOT("__div__", nb_divide, slot_nb_divide,
3597 "/"),
3598 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3599 "/"),
3600 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3601 "%"),
3602 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3603 "%"),
3604 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3605 "divmod(x, y)"),
3606 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3607 "divmod(y, x)"),
3608 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3609 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3610 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3611 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3612 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3613 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3614 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3615 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003616 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003617 "x != 0"),
3618 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3619 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3620 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3621 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3622 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3623 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3624 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3625 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3626 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3627 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3628 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3629 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3630 "x.__coerce__(y) <==> coerce(x, y)"),
3631 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3632 "int(x)"),
3633 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3634 "long(x)"),
3635 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3636 "float(x)"),
3637 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3638 "oct(x)"),
3639 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3640 "hex(x)"),
3641 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3642 wrap_binaryfunc, "+"),
3643 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3644 wrap_binaryfunc, "-"),
3645 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3646 wrap_binaryfunc, "*"),
3647 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3648 wrap_binaryfunc, "/"),
3649 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3650 wrap_binaryfunc, "%"),
3651 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3652 wrap_ternaryfunc, "**"),
3653 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3654 wrap_binaryfunc, "<<"),
3655 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3656 wrap_binaryfunc, ">>"),
3657 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3658 wrap_binaryfunc, "&"),
3659 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3660 wrap_binaryfunc, "^"),
3661 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3662 wrap_binaryfunc, "|"),
3663 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3664 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3665 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3666 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3667 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3668 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3669 IBSLOT("__itruediv__", nb_inplace_true_divide,
3670 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003671
Guido van Rossum6d204072001-10-21 00:44:31 +00003672 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3673 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003674 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003675 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3676 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003677 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003678 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3679 "x.__cmp__(y) <==> cmp(x,y)"),
3680 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3681 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003682 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3683 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003684 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003685 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3686 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3687 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3688 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3689 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3690 "x.__setattr__('name', value) <==> x.name = value"),
3691 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3692 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3693 "x.__delattr__('name') <==> del x.name"),
3694 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3695 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3696 "x.__lt__(y) <==> x<y"),
3697 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3698 "x.__le__(y) <==> x<=y"),
3699 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3700 "x.__eq__(y) <==> x==y"),
3701 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3702 "x.__ne__(y) <==> x!=y"),
3703 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3704 "x.__gt__(y) <==> x>y"),
3705 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3706 "x.__ge__(y) <==> x>=y"),
3707 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3708 "x.__iter__() <==> iter(x)"),
3709 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3710 "x.next() -> the next value, or raise StopIteration"),
3711 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3712 "descr.__get__(obj[, type]) -> value"),
3713 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3714 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003715 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003716 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003717 "see x.__class__.__doc__ for signature",
3718 PyWrapperFlag_KEYWORDS),
3719 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003720 {NULL}
3721};
3722
Guido van Rossumc334df52002-04-04 23:44:47 +00003723/* Given a type pointer and an offset gotten from a slotdef entry, return a
3724 pointer to the actual slot. This is not quite the same as simply adding
3725 the offset to the type pointer, since it takes care to indirect through the
3726 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3727 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003728static void **
3729slotptr(PyTypeObject *type, int offset)
3730{
3731 char *ptr;
3732
3733 assert(offset >= 0);
3734 assert(offset < offsetof(etype, as_buffer));
3735 if (offset >= offsetof(etype, as_mapping)) {
3736 ptr = (void *)type->tp_as_mapping;
3737 offset -= offsetof(etype, as_mapping);
3738 }
3739 else if (offset >= offsetof(etype, as_sequence)) {
3740 ptr = (void *)type->tp_as_sequence;
3741 offset -= offsetof(etype, as_sequence);
3742 }
3743 else if (offset >= offsetof(etype, as_number)) {
3744 ptr = (void *)type->tp_as_number;
3745 offset -= offsetof(etype, as_number);
3746 }
3747 else {
3748 ptr = (void *)type;
3749 }
3750 if (ptr != NULL)
3751 ptr += offset;
3752 return (void **)ptr;
3753}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003754
Guido van Rossumc334df52002-04-04 23:44:47 +00003755/* Length of array of slotdef pointers used to store slots with the
3756 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3757 the same __name__, for any __name__. Since that's a static property, it is
3758 appropriate to declare fixed-size arrays for this. */
3759#define MAX_EQUIV 10
3760
3761/* Return a slot pointer for a given name, but ONLY if the attribute has
3762 exactly one slot function. The name must be an interned string. */
3763static void **
3764resolve_slotdups(PyTypeObject *type, PyObject *name)
3765{
3766 /* XXX Maybe this could be optimized more -- but is it worth it? */
3767
3768 /* pname and ptrs act as a little cache */
3769 static PyObject *pname;
3770 static slotdef *ptrs[MAX_EQUIV];
3771 slotdef *p, **pp;
3772 void **res, **ptr;
3773
3774 if (pname != name) {
3775 /* Collect all slotdefs that match name into ptrs. */
3776 pname = name;
3777 pp = ptrs;
3778 for (p = slotdefs; p->name_strobj; p++) {
3779 if (p->name_strobj == name)
3780 *pp++ = p;
3781 }
3782 *pp = NULL;
3783 }
3784
3785 /* Look in all matching slots of the type; if exactly one of these has
3786 a filled-in slot, return its value. Otherwise return NULL. */
3787 res = NULL;
3788 for (pp = ptrs; *pp; pp++) {
3789 ptr = slotptr(type, (*pp)->offset);
3790 if (ptr == NULL || *ptr == NULL)
3791 continue;
3792 if (res != NULL)
3793 return NULL;
3794 res = ptr;
3795 }
3796 return res;
3797}
3798
3799/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3800 does some incredibly complex thinking and then sticks something into the
3801 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3802 interests, and then stores a generic wrapper or a specific function into
3803 the slot.) Return a pointer to the next slotdef with a different offset,
3804 because that's convenient for fixup_slot_dispatchers(). */
3805static slotdef *
3806update_one_slot(PyTypeObject *type, slotdef *p)
3807{
3808 PyObject *descr;
3809 PyWrapperDescrObject *d;
3810 void *generic = NULL, *specific = NULL;
3811 int use_generic = 0;
3812 int offset = p->offset;
3813 void **ptr = slotptr(type, offset);
3814
3815 if (ptr == NULL) {
3816 do {
3817 ++p;
3818 } while (p->offset == offset);
3819 return p;
3820 }
3821 do {
3822 descr = _PyType_Lookup(type, p->name_strobj);
3823 if (descr == NULL)
3824 continue;
3825 if (descr->ob_type == &PyWrapperDescr_Type) {
3826 void **tptr = resolve_slotdups(type, p->name_strobj);
3827 if (tptr == NULL || tptr == ptr)
3828 generic = p->function;
3829 d = (PyWrapperDescrObject *)descr;
3830 if (d->d_base->wrapper == p->wrapper &&
3831 PyType_IsSubtype(type, d->d_type))
3832 {
3833 if (specific == NULL ||
3834 specific == d->d_wrapped)
3835 specific = d->d_wrapped;
3836 else
3837 use_generic = 1;
3838 }
3839 }
3840 else {
3841 use_generic = 1;
3842 generic = p->function;
3843 }
3844 } while ((++p)->offset == offset);
3845 if (specific && !use_generic)
3846 *ptr = specific;
3847 else
3848 *ptr = generic;
3849 return p;
3850}
3851
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003852staticforward int recurse_down_subclasses(PyTypeObject *type,
3853 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003854
Guido van Rossumc334df52002-04-04 23:44:47 +00003855/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3856 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003857static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003858update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003859{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003860 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003861
Guido van Rossumc334df52002-04-04 23:44:47 +00003862 for (pp = pp0; *pp; pp++)
3863 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003864 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003865}
3866
Guido van Rossumc334df52002-04-04 23:44:47 +00003867/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3868 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003869static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003870recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003871{
3872 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003873 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003874 int i, n;
3875
3876 subclasses = type->tp_subclasses;
3877 if (subclasses == NULL)
3878 return 0;
3879 assert(PyList_Check(subclasses));
3880 n = PyList_GET_SIZE(subclasses);
3881 for (i = 0; i < n; i++) {
3882 ref = PyList_GET_ITEM(subclasses, i);
3883 assert(PyWeakref_CheckRef(ref));
3884 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3885 if (subclass == NULL)
3886 continue;
3887 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003888 /* Avoid recursing down into unaffected classes */
3889 dict = subclass->tp_dict;
3890 if (dict != NULL && PyDict_Check(dict) &&
3891 PyDict_GetItem(dict, name) != NULL)
3892 continue;
3893 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003894 return -1;
3895 }
3896 return 0;
3897}
3898
Guido van Rossumc334df52002-04-04 23:44:47 +00003899/* Comparison function for qsort() to compare slotdefs by their offset, and
3900 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003901static int
3902slotdef_cmp(const void *aa, const void *bb)
3903{
3904 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3905 int c = a->offset - b->offset;
3906 if (c != 0)
3907 return c;
3908 else
3909 return a - b;
3910}
3911
Guido van Rossumc334df52002-04-04 23:44:47 +00003912/* Initialize the slotdefs table by adding interned string objects for the
3913 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003914static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003915init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003916{
3917 slotdef *p;
3918 static int initialized = 0;
3919
3920 if (initialized)
3921 return;
3922 for (p = slotdefs; p->name; p++) {
3923 p->name_strobj = PyString_InternFromString(p->name);
3924 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00003925 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003926 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003927 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3928 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003929 initialized = 1;
3930}
3931
Guido van Rossumc334df52002-04-04 23:44:47 +00003932/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003933static int
3934update_slot(PyTypeObject *type, PyObject *name)
3935{
Guido van Rossumc334df52002-04-04 23:44:47 +00003936 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003937 slotdef *p;
3938 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003939 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003940
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003941 init_slotdefs();
3942 pp = ptrs;
3943 for (p = slotdefs; p->name; p++) {
3944 /* XXX assume name is interned! */
3945 if (p->name_strobj == name)
3946 *pp++ = p;
3947 }
3948 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003949 for (pp = ptrs; *pp; pp++) {
3950 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003951 offset = p->offset;
3952 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003953 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003954 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003955 }
Guido van Rossumc334df52002-04-04 23:44:47 +00003956 if (ptrs[0] == NULL)
3957 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003958 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003959}
3960
Guido van Rossumc334df52002-04-04 23:44:47 +00003961/* Store the proper functions in the slot dispatches at class (type)
3962 definition time, based upon which operations the class overrides in its
3963 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003965fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003967 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003968
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003969 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00003970 for (p = slotdefs; p->name; )
3971 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003973
Guido van Rossum6d204072001-10-21 00:44:31 +00003974/* This function is called by PyType_Ready() to populate the type's
3975 dictionary with method descriptors for function slots. For each
3976 function slot (like tp_repr) that's defined in the type, one or
3977 more corresponding descriptors are added in the type's tp_dict
3978 dictionary under the appropriate name (like __repr__). Some
3979 function slots cause more than one descriptor to be added (for
3980 example, the nb_add slot adds both __add__ and __radd__
3981 descriptors) and some function slots compete for the same
3982 descriptor (for example both sq_item and mp_subscript generate a
3983 __getitem__ descriptor). This only adds new descriptors and
3984 doesn't overwrite entries in tp_dict that were previously
3985 defined. The descriptors contain a reference to the C function
3986 they must call, so that it's safe if they are copied into a
3987 subtype's __dict__ and the subtype has a different C function in
3988 its slot -- calling the method defined by the descriptor will call
3989 the C function that was used to create it, rather than the C
3990 function present in the slot when it is called. (This is important
3991 because a subtype may have a C function in the slot that calls the
3992 method from the dictionary, and we want to avoid infinite recursion
3993 here.) */
3994
3995static int
3996add_operators(PyTypeObject *type)
3997{
3998 PyObject *dict = type->tp_dict;
3999 slotdef *p;
4000 PyObject *descr;
4001 void **ptr;
4002
4003 init_slotdefs();
4004 for (p = slotdefs; p->name; p++) {
4005 if (p->wrapper == NULL)
4006 continue;
4007 ptr = slotptr(type, p->offset);
4008 if (!ptr || !*ptr)
4009 continue;
4010 if (PyDict_GetItem(dict, p->name_strobj))
4011 continue;
4012 descr = PyDescr_NewWrapper(type, p, *ptr);
4013 if (descr == NULL)
4014 return -1;
4015 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4016 return -1;
4017 Py_DECREF(descr);
4018 }
4019 if (type->tp_new != NULL) {
4020 if (add_tp_new_wrapper(type) < 0)
4021 return -1;
4022 }
4023 return 0;
4024}
4025
Guido van Rossum705f0f52001-08-24 16:47:00 +00004026
4027/* Cooperative 'super' */
4028
4029typedef struct {
4030 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004031 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004032 PyObject *obj;
4033} superobject;
4034
Guido van Rossum6f799372001-09-20 20:46:19 +00004035static PyMemberDef super_members[] = {
4036 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4037 "the class invoking super()"},
4038 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4039 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004040 {0}
4041};
4042
Guido van Rossum705f0f52001-08-24 16:47:00 +00004043static void
4044super_dealloc(PyObject *self)
4045{
4046 superobject *su = (superobject *)self;
4047
Guido van Rossum048eb752001-10-02 21:24:57 +00004048 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004049 Py_XDECREF(su->obj);
4050 Py_XDECREF(su->type);
4051 self->ob_type->tp_free(self);
4052}
4053
4054static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004055super_repr(PyObject *self)
4056{
4057 superobject *su = (superobject *)self;
4058
4059 if (su->obj)
4060 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004061 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004062 su->type ? su->type->tp_name : "NULL",
4063 su->obj->ob_type->tp_name);
4064 else
4065 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004066 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004067 su->type ? su->type->tp_name : "NULL");
4068}
4069
4070static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004071super_getattro(PyObject *self, PyObject *name)
4072{
4073 superobject *su = (superobject *)self;
4074
4075 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004076 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004077 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004078 descrgetfunc f;
4079 int i, n;
4080
Guido van Rossum155db9a2002-04-02 17:53:47 +00004081 starttype = su->obj->ob_type;
4082 mro = starttype->tp_mro;
4083
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004084 if (mro == NULL)
4085 n = 0;
4086 else {
4087 assert(PyTuple_Check(mro));
4088 n = PyTuple_GET_SIZE(mro);
4089 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004090 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004091 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004092 break;
4093 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004094 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004095 starttype = (PyTypeObject *)(su->obj);
4096 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004097 if (mro == NULL)
4098 n = 0;
4099 else {
4100 assert(PyTuple_Check(mro));
4101 n = PyTuple_GET_SIZE(mro);
4102 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004103 for (i = 0; i < n; i++) {
4104 if ((PyObject *)(su->type) ==
4105 PyTuple_GET_ITEM(mro, i))
4106 break;
4107 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004108 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004109 i++;
4110 res = NULL;
4111 for (; i < n; i++) {
4112 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004113 if (PyType_Check(tmp))
4114 dict = ((PyTypeObject *)tmp)->tp_dict;
4115 else if (PyClass_Check(tmp))
4116 dict = ((PyClassObject *)tmp)->cl_dict;
4117 else
4118 continue;
4119 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004120 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004121 Py_INCREF(res);
4122 f = res->ob_type->tp_descr_get;
4123 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004124 tmp = f(res, su->obj,
4125 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004126 Py_DECREF(res);
4127 res = tmp;
4128 }
4129 return res;
4130 }
4131 }
4132 }
4133 return PyObject_GenericGetAttr(self, name);
4134}
4135
Guido van Rossum5b443c62001-12-03 15:38:28 +00004136static int
4137supercheck(PyTypeObject *type, PyObject *obj)
4138{
4139 if (!PyType_IsSubtype(obj->ob_type, type) &&
4140 !(PyType_Check(obj) &&
4141 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4142 PyErr_SetString(PyExc_TypeError,
4143 "super(type, obj): "
4144 "obj must be an instance or subtype of type");
4145 return -1;
4146 }
4147 else
4148 return 0;
4149}
4150
Guido van Rossum705f0f52001-08-24 16:47:00 +00004151static PyObject *
4152super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4153{
4154 superobject *su = (superobject *)self;
4155 superobject *new;
4156
4157 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4158 /* Not binding to an object, or already bound */
4159 Py_INCREF(self);
4160 return self;
4161 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004162 if (su->ob_type != &PySuper_Type)
4163 /* If su is an instance of a subclass of super,
4164 call its type */
4165 return PyObject_CallFunction((PyObject *)su->ob_type,
4166 "OO", su->type, obj);
4167 else {
4168 /* Inline the common case */
4169 if (supercheck(su->type, obj) < 0)
4170 return NULL;
4171 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4172 NULL, NULL);
4173 if (new == NULL)
4174 return NULL;
4175 Py_INCREF(su->type);
4176 Py_INCREF(obj);
4177 new->type = su->type;
4178 new->obj = obj;
4179 return (PyObject *)new;
4180 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004181}
4182
4183static int
4184super_init(PyObject *self, PyObject *args, PyObject *kwds)
4185{
4186 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004187 PyTypeObject *type;
4188 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004189
4190 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4191 return -1;
4192 if (obj == Py_None)
4193 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004194 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004195 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004196 Py_INCREF(type);
4197 Py_XINCREF(obj);
4198 su->type = type;
4199 su->obj = obj;
4200 return 0;
4201}
4202
4203static char super_doc[] =
4204"super(type) -> unbound super object\n"
4205"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004206"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004207"Typical use to call a cooperative superclass method:\n"
4208"class C(B):\n"
4209" def meth(self, arg):\n"
4210" super(C, self).meth(arg)";
4211
Guido van Rossum048eb752001-10-02 21:24:57 +00004212static int
4213super_traverse(PyObject *self, visitproc visit, void *arg)
4214{
4215 superobject *su = (superobject *)self;
4216 int err;
4217
4218#define VISIT(SLOT) \
4219 if (SLOT) { \
4220 err = visit((PyObject *)(SLOT), arg); \
4221 if (err) \
4222 return err; \
4223 }
4224
4225 VISIT(su->obj);
4226 VISIT(su->type);
4227
4228#undef VISIT
4229
4230 return 0;
4231}
4232
Guido van Rossum705f0f52001-08-24 16:47:00 +00004233PyTypeObject PySuper_Type = {
4234 PyObject_HEAD_INIT(&PyType_Type)
4235 0, /* ob_size */
4236 "super", /* tp_name */
4237 sizeof(superobject), /* tp_basicsize */
4238 0, /* tp_itemsize */
4239 /* methods */
4240 super_dealloc, /* tp_dealloc */
4241 0, /* tp_print */
4242 0, /* tp_getattr */
4243 0, /* tp_setattr */
4244 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004245 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004246 0, /* tp_as_number */
4247 0, /* tp_as_sequence */
4248 0, /* tp_as_mapping */
4249 0, /* tp_hash */
4250 0, /* tp_call */
4251 0, /* tp_str */
4252 super_getattro, /* tp_getattro */
4253 0, /* tp_setattro */
4254 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004255 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4256 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004257 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004258 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004259 0, /* tp_clear */
4260 0, /* tp_richcompare */
4261 0, /* tp_weaklistoffset */
4262 0, /* tp_iter */
4263 0, /* tp_iternext */
4264 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004265 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004266 0, /* tp_getset */
4267 0, /* tp_base */
4268 0, /* tp_dict */
4269 super_descr_get, /* tp_descr_get */
4270 0, /* tp_descr_set */
4271 0, /* tp_dictoffset */
4272 super_init, /* tp_init */
4273 PyType_GenericAlloc, /* tp_alloc */
4274 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004275 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004276};