blob: f0e8c8333120de30d68c4954190ab6db619349d5 [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;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000172 type = obj->ob_type;
173 if (type->tp_init != NULL &&
174 type->tp_init(obj, args, kwds) < 0) {
175 Py_DECREF(obj);
176 obj = NULL;
177 }
178 }
179 return obj;
180}
181
182PyObject *
183PyType_GenericAlloc(PyTypeObject *type, int nitems)
184{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000185 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000186 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000187
188 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000189 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000190 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000191 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000192
Neil Schemenauerc806c882001-08-29 23:54:54 +0000193 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000194 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000195
Neil Schemenauerc806c882001-08-29 23:54:54 +0000196 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000197
Tim Peters6d6c1a32001-08-02 04:15:00 +0000198 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
199 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000200
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201 if (type->tp_itemsize == 0)
202 PyObject_INIT(obj, type);
203 else
204 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000205
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000207 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000208 return obj;
209}
210
211PyObject *
212PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
213{
214 return type->tp_alloc(type, 0);
215}
216
Guido van Rossum9475a232001-10-05 20:51:39 +0000217/* Helpers for subtyping */
218
219static int
220subtype_traverse(PyObject *self, visitproc visit, void *arg)
221{
222 PyTypeObject *type, *base;
223 traverseproc f;
224 int err;
225
226 /* Find the nearest base with a different tp_traverse */
227 type = self->ob_type;
228 base = type->tp_base;
229 while ((f = base->tp_traverse) == subtype_traverse) {
230 base = base->tp_base;
231 assert(base);
232 }
233
234 if (type->tp_dictoffset != base->tp_dictoffset) {
235 PyObject **dictptr = _PyObject_GetDictPtr(self);
236 if (dictptr && *dictptr) {
237 err = visit(*dictptr, arg);
238 if (err)
239 return err;
240 }
241 }
242
243 if (f)
244 return f(self, visit, arg);
245 return 0;
246}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000247
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000248staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
249
250static int
251call_finalizer(PyObject *self)
252{
253 static PyObject *del_str = NULL;
254 PyObject *del, *res;
255 PyObject *error_type, *error_value, *error_traceback;
256
257 /* Temporarily resurrect the object. */
258#ifdef Py_TRACE_REFS
259#ifndef Py_REF_DEBUG
260# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
261#endif
262 /* much too complicated if Py_TRACE_REFS defined */
263 _Py_NewReference((PyObject *)self);
264#ifdef COUNT_ALLOCS
265 /* compensate for boost in _Py_NewReference; note that
266 * _Py_RefTotal was also boosted; we'll knock that down later.
267 */
268 self->ob_type->tp_allocs--;
269#endif
270#else /* !Py_TRACE_REFS */
271 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
272 Py_INCREF(self);
273#endif /* !Py_TRACE_REFS */
274
275 /* Save the current exception, if any. */
276 PyErr_Fetch(&error_type, &error_value, &error_traceback);
277
278 /* Execute __del__ method, if any. */
279 del = lookup_maybe(self, "__del__", &del_str);
280 if (del != NULL) {
281 res = PyEval_CallObject(del, NULL);
282 if (res == NULL)
283 PyErr_WriteUnraisable(del);
284 else
285 Py_DECREF(res);
286 Py_DECREF(del);
287 }
288
289 /* Restore the saved exception. */
290 PyErr_Restore(error_type, error_value, error_traceback);
291
292 /* Undo the temporary resurrection; can't use DECREF here, it would
293 * cause a recursive call.
294 */
295#ifdef Py_REF_DEBUG
296 /* _Py_RefTotal was boosted either by _Py_NewReference or
297 * Py_INCREF above.
298 */
299 _Py_RefTotal--;
300#endif
301 if (--self->ob_refcnt > 0) {
302#ifdef COUNT_ALLOCS
303 self->ob_type->tp_frees--;
304#endif
305 _PyObject_GC_TRACK(self);
306 return -1; /* __del__ added a reference; don't delete now */
307 }
308#ifdef Py_TRACE_REFS
309 _Py_ForgetReference((PyObject *)self);
310#ifdef COUNT_ALLOCS
311 /* compensate for increment in _Py_ForgetReference */
312 self->ob_type->tp_frees--;
313#endif
314#endif
315
316 return 0;
317}
318
Tim Peters6d6c1a32001-08-02 04:15:00 +0000319static void
320subtype_dealloc(PyObject *self)
321{
Guido van Rossum14227b42001-12-06 02:35:58 +0000322 PyTypeObject *type, *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000323 destructor f;
324
325 /* This exists so we can DECREF self->ob_type */
326
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000327 if (call_finalizer(self) < 0)
328 return;
329
Tim Peters6d6c1a32001-08-02 04:15:00 +0000330 /* Find the nearest base with a different tp_dealloc */
331 type = self->ob_type;
Guido van Rossum14227b42001-12-06 02:35:58 +0000332 base = type->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000333 while ((f = base->tp_dealloc) == subtype_dealloc) {
334 base = base->tp_base;
335 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000336 }
337
338 /* Clear __slots__ variables */
339 if (type->tp_basicsize != base->tp_basicsize &&
340 type->tp_itemsize == 0)
341 {
342 char *addr = ((char *)self);
343 char *p = addr + base->tp_basicsize;
344 char *q = addr + type->tp_basicsize;
345 for (; p < q; p += sizeof(PyObject *)) {
346 PyObject **pp;
347 if (p == addr + type->tp_dictoffset ||
348 p == addr + type->tp_weaklistoffset)
349 continue;
350 pp = (PyObject **)p;
351 if (*pp != NULL) {
352 Py_DECREF(*pp);
353 *pp = NULL;
Guido van Rossum33bab012001-12-05 22:45:48 +0000354 }
355 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000356 }
357
358 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000359 if (type->tp_dictoffset && !base->tp_dictoffset) {
360 PyObject **dictptr = _PyObject_GetDictPtr(self);
361 if (dictptr != NULL) {
362 PyObject *dict = *dictptr;
363 if (dict != NULL) {
364 Py_DECREF(dict);
365 *dictptr = NULL;
366 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000367 }
368 }
369
Guido van Rossum9676b222001-08-17 20:32:36 +0000370 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000371 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000372 PyObject_ClearWeakRefs(self);
373
Tim Peters6d6c1a32001-08-02 04:15:00 +0000374 /* Finalize GC if the base doesn't do GC and we do */
375 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000376 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000377
378 /* Call the base tp_dealloc() */
379 assert(f);
380 f(self);
381
382 /* Can't reference self beyond this point */
383 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
384 Py_DECREF(type);
385 }
386}
387
Tim Peters6d6c1a32001-08-02 04:15:00 +0000388staticforward PyTypeObject *solid_base(PyTypeObject *type);
389
390typedef struct {
391 PyTypeObject type;
392 PyNumberMethods as_number;
393 PySequenceMethods as_sequence;
394 PyMappingMethods as_mapping;
395 PyBufferProcs as_buffer;
396 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000397 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000398} etype;
399
400/* type test with subclassing support */
401
402int
403PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
404{
405 PyObject *mro;
406
Guido van Rossum9478d072001-09-07 18:52:13 +0000407 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
408 return b == a || b == &PyBaseObject_Type;
409
Tim Peters6d6c1a32001-08-02 04:15:00 +0000410 mro = a->tp_mro;
411 if (mro != NULL) {
412 /* Deal with multiple inheritance without recursion
413 by walking the MRO tuple */
414 int i, n;
415 assert(PyTuple_Check(mro));
416 n = PyTuple_GET_SIZE(mro);
417 for (i = 0; i < n; i++) {
418 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
419 return 1;
420 }
421 return 0;
422 }
423 else {
424 /* a is not completely initilized yet; follow tp_base */
425 do {
426 if (a == b)
427 return 1;
428 a = a->tp_base;
429 } while (a != NULL);
430 return b == &PyBaseObject_Type;
431 }
432}
433
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000434/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000435 without looking in the instance dictionary
436 (so we can't use PyObject_GetAttr) but still binding
437 it to the instance. The arguments are the object,
438 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000439 static variable used to cache the interned Python string.
440
441 Two variants:
442
443 - lookup_maybe() returns NULL without raising an exception
444 when the _PyType_Lookup() call fails;
445
446 - lookup_method() always raises an exception upon errors.
447*/
Guido van Rossum60718732001-08-28 17:47:51 +0000448
449static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000450lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000451{
452 PyObject *res;
453
454 if (*attrobj == NULL) {
455 *attrobj = PyString_InternFromString(attrstr);
456 if (*attrobj == NULL)
457 return NULL;
458 }
459 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000460 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000461 descrgetfunc f;
462 if ((f = res->ob_type->tp_descr_get) == NULL)
463 Py_INCREF(res);
464 else
465 res = f(res, self, (PyObject *)(self->ob_type));
466 }
467 return res;
468}
469
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000470static PyObject *
471lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
472{
473 PyObject *res = lookup_maybe(self, attrstr, attrobj);
474 if (res == NULL && !PyErr_Occurred())
475 PyErr_SetObject(PyExc_AttributeError, *attrobj);
476 return res;
477}
478
Guido van Rossum2730b132001-08-28 18:22:14 +0000479/* A variation of PyObject_CallMethod that uses lookup_method()
480 instead of PyObject_GetAttrString(). This uses the same convention
481 as lookup_method to cache the interned name string object. */
482
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000483static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000484call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
485{
486 va_list va;
487 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000488 va_start(va, format);
489
Guido van Rossumda21c012001-10-03 00:50:18 +0000490 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000491 if (func == NULL) {
492 va_end(va);
493 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000494 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000495 return NULL;
496 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000497
498 if (format && *format)
499 args = Py_VaBuildValue(format, va);
500 else
501 args = PyTuple_New(0);
502
503 va_end(va);
504
505 if (args == NULL)
506 return NULL;
507
508 assert(PyTuple_Check(args));
509 retval = PyObject_Call(func, args, NULL);
510
511 Py_DECREF(args);
512 Py_DECREF(func);
513
514 return retval;
515}
516
517/* Clone of call_method() that returns NotImplemented when the lookup fails. */
518
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000519static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000520call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
521{
522 va_list va;
523 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000524 va_start(va, format);
525
Guido van Rossumda21c012001-10-03 00:50:18 +0000526 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000527 if (func == NULL) {
528 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000529 if (!PyErr_Occurred()) {
530 Py_INCREF(Py_NotImplemented);
531 return Py_NotImplemented;
532 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000533 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000534 }
535
536 if (format && *format)
537 args = Py_VaBuildValue(format, va);
538 else
539 args = PyTuple_New(0);
540
541 va_end(va);
542
Guido van Rossum717ce002001-09-14 16:58:08 +0000543 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000544 return NULL;
545
Guido van Rossum717ce002001-09-14 16:58:08 +0000546 assert(PyTuple_Check(args));
547 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000548
549 Py_DECREF(args);
550 Py_DECREF(func);
551
552 return retval;
553}
554
Tim Peters6d6c1a32001-08-02 04:15:00 +0000555/* Method resolution order algorithm from "Putting Metaclasses to Work"
556 by Forman and Danforth (Addison-Wesley 1999). */
557
558static int
559conservative_merge(PyObject *left, PyObject *right)
560{
561 int left_size;
562 int right_size;
563 int i, j, r, ok;
564 PyObject *temp, *rr;
565
566 assert(PyList_Check(left));
567 assert(PyList_Check(right));
568
569 again:
570 left_size = PyList_GET_SIZE(left);
571 right_size = PyList_GET_SIZE(right);
572 for (i = 0; i < left_size; i++) {
573 for (j = 0; j < right_size; j++) {
574 if (PyList_GET_ITEM(left, i) ==
575 PyList_GET_ITEM(right, j)) {
576 /* found a merge point */
577 temp = PyList_New(0);
578 if (temp == NULL)
579 return -1;
580 for (r = 0; r < j; r++) {
581 rr = PyList_GET_ITEM(right, r);
582 ok = PySequence_Contains(left, rr);
583 if (ok < 0) {
584 Py_DECREF(temp);
585 return -1;
586 }
587 if (!ok) {
588 ok = PyList_Append(temp, rr);
589 if (ok < 0) {
590 Py_DECREF(temp);
591 return -1;
592 }
593 }
594 }
595 ok = PyList_SetSlice(left, i, i, temp);
596 Py_DECREF(temp);
597 if (ok < 0)
598 return -1;
599 ok = PyList_SetSlice(right, 0, j+1, NULL);
600 if (ok < 0)
601 return -1;
602 goto again;
603 }
604 }
605 }
606 return PyList_SetSlice(left, left_size, left_size, right);
607}
608
609static int
610serious_order_disagreements(PyObject *left, PyObject *right)
611{
612 return 0; /* XXX later -- for now, we cheat: "don't do that" */
613}
614
Tim Petersa91e9642001-11-14 23:32:33 +0000615static int
616fill_classic_mro(PyObject *mro, PyObject *cls)
617{
618 PyObject *bases, *base;
619 int i, n;
620
621 assert(PyList_Check(mro));
622 assert(PyClass_Check(cls));
623 i = PySequence_Contains(mro, cls);
624 if (i < 0)
625 return -1;
626 if (!i) {
627 if (PyList_Append(mro, cls) < 0)
628 return -1;
629 }
630 bases = ((PyClassObject *)cls)->cl_bases;
631 assert(bases && PyTuple_Check(bases));
632 n = PyTuple_GET_SIZE(bases);
633 for (i = 0; i < n; i++) {
634 base = PyTuple_GET_ITEM(bases, i);
635 if (fill_classic_mro(mro, base) < 0)
636 return -1;
637 }
638 return 0;
639}
640
641static PyObject *
642classic_mro(PyObject *cls)
643{
644 PyObject *mro;
645
646 assert(PyClass_Check(cls));
647 mro = PyList_New(0);
648 if (mro != NULL) {
649 if (fill_classic_mro(mro, cls) == 0)
650 return mro;
651 Py_DECREF(mro);
652 }
653 return NULL;
654}
655
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656static PyObject *
657mro_implementation(PyTypeObject *type)
658{
659 int i, n, ok;
660 PyObject *bases, *result;
661
662 bases = type->tp_bases;
663 n = PyTuple_GET_SIZE(bases);
664 result = Py_BuildValue("[O]", (PyObject *)type);
665 if (result == NULL)
666 return NULL;
667 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000668 PyObject *base = PyTuple_GET_ITEM(bases, i);
669 PyObject *parentMRO;
670 if (PyType_Check(base))
671 parentMRO = PySequence_List(
672 ((PyTypeObject*)base)->tp_mro);
673 else
674 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675 if (parentMRO == NULL) {
676 Py_DECREF(result);
677 return NULL;
678 }
679 if (serious_order_disagreements(result, parentMRO)) {
680 Py_DECREF(result);
681 return NULL;
682 }
683 ok = conservative_merge(result, parentMRO);
684 Py_DECREF(parentMRO);
685 if (ok < 0) {
686 Py_DECREF(result);
687 return NULL;
688 }
689 }
690 return result;
691}
692
693static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000694mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695{
696 PyTypeObject *type = (PyTypeObject *)self;
697
Tim Peters6d6c1a32001-08-02 04:15:00 +0000698 return mro_implementation(type);
699}
700
701static int
702mro_internal(PyTypeObject *type)
703{
704 PyObject *mro, *result, *tuple;
705
706 if (type->ob_type == &PyType_Type) {
707 result = mro_implementation(type);
708 }
709 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000710 static PyObject *mro_str;
711 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000712 if (mro == NULL)
713 return -1;
714 result = PyObject_CallObject(mro, NULL);
715 Py_DECREF(mro);
716 }
717 if (result == NULL)
718 return -1;
719 tuple = PySequence_Tuple(result);
720 Py_DECREF(result);
721 type->tp_mro = tuple;
722 return 0;
723}
724
725
726/* Calculate the best base amongst multiple base classes.
727 This is the first one that's on the path to the "solid base". */
728
729static PyTypeObject *
730best_base(PyObject *bases)
731{
732 int i, n;
733 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000734 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000735
736 assert(PyTuple_Check(bases));
737 n = PyTuple_GET_SIZE(bases);
738 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000739 base = NULL;
740 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000742 base_proto = PyTuple_GET_ITEM(bases, i);
743 if (PyClass_Check(base_proto))
744 continue;
745 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000746 PyErr_SetString(
747 PyExc_TypeError,
748 "bases must be types");
749 return NULL;
750 }
Tim Petersa91e9642001-11-14 23:32:33 +0000751 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000752 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000753 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000754 return NULL;
755 }
756 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000757 if (winner == NULL) {
758 winner = candidate;
759 base = base_i;
760 }
761 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762 ;
763 else if (PyType_IsSubtype(candidate, winner)) {
764 winner = candidate;
765 base = base_i;
766 }
767 else {
768 PyErr_SetString(
769 PyExc_TypeError,
770 "multiple bases have "
771 "instance lay-out conflict");
772 return NULL;
773 }
774 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000775 if (base == NULL)
776 PyErr_SetString(PyExc_TypeError,
777 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 return base;
779}
780
781static int
782extra_ivars(PyTypeObject *type, PyTypeObject *base)
783{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000784 size_t t_size = type->tp_basicsize;
785 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786
Guido van Rossum9676b222001-08-17 20:32:36 +0000787 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000788 if (type->tp_itemsize || base->tp_itemsize) {
789 /* If itemsize is involved, stricter rules */
790 return t_size != b_size ||
791 type->tp_itemsize != base->tp_itemsize;
792 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000793 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
794 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
795 t_size -= sizeof(PyObject *);
796 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
797 type->tp_dictoffset + sizeof(PyObject *) == t_size)
798 t_size -= sizeof(PyObject *);
799
800 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000801}
802
803static PyTypeObject *
804solid_base(PyTypeObject *type)
805{
806 PyTypeObject *base;
807
808 if (type->tp_base)
809 base = solid_base(type->tp_base);
810 else
811 base = &PyBaseObject_Type;
812 if (extra_ivars(type, base))
813 return type;
814 else
815 return base;
816}
817
818staticforward void object_dealloc(PyObject *);
819staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000820staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000821staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000822
823static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000824subtype_dict(PyObject *obj, void *context)
825{
826 PyObject **dictptr = _PyObject_GetDictPtr(obj);
827 PyObject *dict;
828
829 if (dictptr == NULL) {
830 PyErr_SetString(PyExc_AttributeError,
831 "This object has no __dict__");
832 return NULL;
833 }
834 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000835 if (dict == NULL)
836 *dictptr = dict = PyDict_New();
837 Py_XINCREF(dict);
838 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000839}
840
Guido van Rossum6661be32001-10-26 04:26:12 +0000841static int
842subtype_setdict(PyObject *obj, PyObject *value, void *context)
843{
844 PyObject **dictptr = _PyObject_GetDictPtr(obj);
845 PyObject *dict;
846
847 if (dictptr == NULL) {
848 PyErr_SetString(PyExc_AttributeError,
849 "This object has no __dict__");
850 return -1;
851 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000852 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000853 PyErr_SetString(PyExc_TypeError,
854 "__dict__ must be set to a dictionary");
855 return -1;
856 }
857 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000858 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000859 *dictptr = value;
860 Py_XDECREF(dict);
861 return 0;
862}
863
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000864static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000865 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000866 {0},
867};
868
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000869/* bozo: __getstate__ that raises TypeError */
870
871static PyObject *
872bozo_func(PyObject *self, PyObject *args)
873{
874 PyErr_SetString(PyExc_TypeError,
875 "a class that defines __slots__ without "
876 "defining __getstate__ cannot be pickled");
877 return NULL;
878}
879
Neal Norwitz93c1e232002-03-31 16:06:11 +0000880static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000881
882static PyObject *bozo_obj = NULL;
883
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000884static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000885type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
886{
887 PyObject *name, *bases, *dict;
888 static char *kwlist[] = {"name", "bases", "dict", 0};
889 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000890 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000891 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000892 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000893 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000894
Tim Peters3abca122001-10-27 19:37:48 +0000895 assert(args != NULL && PyTuple_Check(args));
896 assert(kwds == NULL || PyDict_Check(kwds));
897
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000898 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000899 {
900 const int nargs = PyTuple_GET_SIZE(args);
901 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
902
903 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
904 PyObject *x = PyTuple_GET_ITEM(args, 0);
905 Py_INCREF(x->ob_type);
906 return (PyObject *) x->ob_type;
907 }
908
909 /* SF bug 475327 -- if that didn't trigger, we need 3
910 arguments. but PyArg_ParseTupleAndKeywords below may give
911 a msg saying type() needs exactly 3. */
912 if (nargs + nkwds != 3) {
913 PyErr_SetString(PyExc_TypeError,
914 "type() takes 1 or 3 arguments");
915 return NULL;
916 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917 }
918
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000919 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000920 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
921 &name,
922 &PyTuple_Type, &bases,
923 &PyDict_Type, &dict))
924 return NULL;
925
926 /* Determine the proper metatype to deal with this,
927 and check for metatype conflicts while we're at it.
928 Note that if some other metatype wins to contract,
929 it's possible that its instances are not types. */
930 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000931 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932 for (i = 0; i < nbases; i++) {
933 tmp = PyTuple_GET_ITEM(bases, i);
934 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000935 if (tmptype == &PyClass_Type)
936 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000937 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000938 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000939 if (PyType_IsSubtype(tmptype, winner)) {
940 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000941 continue;
942 }
943 PyErr_SetString(PyExc_TypeError,
944 "metatype conflict among bases");
945 return NULL;
946 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000947 if (winner != metatype) {
948 if (winner->tp_new != type_new) /* Pass it to the winner */
949 return winner->tp_new(winner, args, kwds);
950 metatype = winner;
951 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000952
953 /* Adjust for empty tuple bases */
954 if (nbases == 0) {
955 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
956 if (bases == NULL)
957 return NULL;
958 nbases = 1;
959 }
960 else
961 Py_INCREF(bases);
962
963 /* XXX From here until type is allocated, "return NULL" leaks bases! */
964
965 /* Calculate best base, and check that all bases are type objects */
966 base = best_base(bases);
967 if (base == NULL)
968 return NULL;
969 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
970 PyErr_Format(PyExc_TypeError,
971 "type '%.100s' is not an acceptable base type",
972 base->tp_name);
973 return NULL;
974 }
975
Tim Peters6d6c1a32001-08-02 04:15:00 +0000976 /* Check for a __slots__ sequence variable in dict, and count it */
977 slots = PyDict_GetItemString(dict, "__slots__");
978 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000979 add_dict = 0;
980 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981 if (slots != NULL) {
982 /* Make it into a tuple */
983 if (PyString_Check(slots))
984 slots = Py_BuildValue("(O)", slots);
985 else
986 slots = PySequence_Tuple(slots);
987 if (slots == NULL)
988 return NULL;
989 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000990 if (nslots > 0 && base->tp_itemsize != 0) {
991 PyErr_Format(PyExc_TypeError,
992 "nonempty __slots__ "
993 "not supported for subtype of '%s'",
994 base->tp_name);
995 return NULL;
996 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997 for (i = 0; i < nslots; i++) {
998 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
999 PyErr_SetString(PyExc_TypeError,
1000 "__slots__ must be a sequence of strings");
1001 Py_DECREF(slots);
1002 return NULL;
1003 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001004 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 }
1006 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001007 if (slots != NULL) {
1008 /* See if *this* class defines __getstate__ */
1009 PyObject *getstate = PyDict_GetItemString(dict,
1010 "__getstate__");
1011 if (getstate == NULL) {
1012 /* If not, provide a bozo that raises TypeError */
1013 if (bozo_obj == NULL) {
1014 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1015 if (bozo_obj == NULL) {
1016 /* XXX decref various things */
1017 return NULL;
1018 }
1019 }
1020 if (PyDict_SetItemString(dict,
1021 "__getstate__",
1022 bozo_obj) < 0) {
1023 /* XXX decref various things */
1024 return NULL;
1025 }
1026 }
1027 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001028 if (slots == NULL && base->tp_dictoffset == 0 &&
1029 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001030 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001031 add_dict++;
1032 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001033 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1034 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001035 nslots++;
1036 add_weak++;
1037 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038
1039 /* XXX From here until type is safely allocated,
1040 "return NULL" may leak slots! */
1041
1042 /* Allocate the type object */
1043 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1044 if (type == NULL)
1045 return NULL;
1046
1047 /* Keep name and slots alive in the extended type object */
1048 et = (etype *)type;
1049 Py_INCREF(name);
1050 et->name = name;
1051 et->slots = slots;
1052
Guido van Rossumdc91b992001-08-08 22:26:22 +00001053 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1055 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001056 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1057 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001058
1059 /* It's a new-style number unless it specifically inherits any
1060 old-style numeric behavior */
1061 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1062 (base->tp_as_number == NULL))
1063 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1064
1065 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 type->tp_as_number = &et->as_number;
1067 type->tp_as_sequence = &et->as_sequence;
1068 type->tp_as_mapping = &et->as_mapping;
1069 type->tp_as_buffer = &et->as_buffer;
1070 type->tp_name = PyString_AS_STRING(name);
1071
1072 /* Set tp_base and tp_bases */
1073 type->tp_bases = bases;
1074 Py_INCREF(base);
1075 type->tp_base = base;
1076
Guido van Rossum687ae002001-10-15 22:03:32 +00001077 /* Initialize tp_dict from passed-in dict */
1078 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079 if (dict == NULL) {
1080 Py_DECREF(type);
1081 return NULL;
1082 }
1083
Guido van Rossumc3542212001-08-16 09:18:56 +00001084 /* Set __module__ in the dict */
1085 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1086 tmp = PyEval_GetGlobals();
1087 if (tmp != NULL) {
1088 tmp = PyDict_GetItemString(tmp, "__name__");
1089 if (tmp != NULL) {
1090 if (PyDict_SetItemString(dict, "__module__",
1091 tmp) < 0)
1092 return NULL;
1093 }
1094 }
1095 }
1096
Tim Peters2f93e282001-10-04 05:27:00 +00001097 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001098 and is a string. The __doc__ accessor will first look for tp_doc;
1099 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001100 */
1101 {
1102 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1103 if (doc != NULL && PyString_Check(doc)) {
1104 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001105 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001106 if (type->tp_doc == NULL) {
1107 Py_DECREF(type);
1108 return NULL;
1109 }
1110 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1111 }
1112 }
1113
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114 /* Special-case __new__: if it's a plain function,
1115 make it a static function */
1116 tmp = PyDict_GetItemString(dict, "__new__");
1117 if (tmp != NULL && PyFunction_Check(tmp)) {
1118 tmp = PyStaticMethod_New(tmp);
1119 if (tmp == NULL) {
1120 Py_DECREF(type);
1121 return NULL;
1122 }
1123 PyDict_SetItemString(dict, "__new__", tmp);
1124 Py_DECREF(tmp);
1125 }
1126
1127 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1128 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001129 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130 if (slots != NULL) {
1131 for (i = 0; i < nslots; i++, mp++) {
1132 mp->name = PyString_AS_STRING(
1133 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001134 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001136 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001137 strcmp(mp->name, "__weakref__") == 0) {
1138 mp->type = T_OBJECT;
Guido van Rossum9676b222001-08-17 20:32:36 +00001139 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001140 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001141 slotoffset += sizeof(PyObject *);
1142 }
1143 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001144 else {
1145 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001146 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001147 type->tp_dictoffset =
1148 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001149 else
1150 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001151 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001152 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001153 }
1154 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001155 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001156 type->tp_weaklistoffset = slotoffset;
1157 mp->name = "__weakref__";
1158 mp->type = T_OBJECT;
1159 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001160 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001161 mp++;
1162 slotoffset += sizeof(PyObject *);
1163 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164 }
1165 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001166 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001167 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168
1169 /* Special case some slots */
1170 if (type->tp_dictoffset != 0 || nslots > 0) {
1171 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1172 type->tp_getattro = PyObject_GenericGetAttr;
1173 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1174 type->tp_setattro = PyObject_GenericSetAttr;
1175 }
1176 type->tp_dealloc = subtype_dealloc;
1177
Guido van Rossum9475a232001-10-05 20:51:39 +00001178 /* Enable GC unless there are really no instance variables possible */
1179 if (!(type->tp_basicsize == sizeof(PyObject) &&
1180 type->tp_itemsize == 0))
1181 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1182
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 /* Always override allocation strategy to use regular heap */
1184 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001185 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1186 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001187 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001188 type->tp_clear = base->tp_clear;
1189 }
1190 else
1191 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192
1193 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001194 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 Py_DECREF(type);
1196 return NULL;
1197 }
1198
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001199 /* Put the proper slots in place */
1200 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001201
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 return (PyObject *)type;
1203}
1204
1205/* Internal API to look for a name through the MRO.
1206 This returns a borrowed reference, and doesn't set an exception! */
1207PyObject *
1208_PyType_Lookup(PyTypeObject *type, PyObject *name)
1209{
1210 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001211 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212
Guido van Rossum687ae002001-10-15 22:03:32 +00001213 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214 mro = type->tp_mro;
1215 assert(PyTuple_Check(mro));
1216 n = PyTuple_GET_SIZE(mro);
1217 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001218 base = PyTuple_GET_ITEM(mro, i);
1219 if (PyClass_Check(base))
1220 dict = ((PyClassObject *)base)->cl_dict;
1221 else {
1222 assert(PyType_Check(base));
1223 dict = ((PyTypeObject *)base)->tp_dict;
1224 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225 assert(dict && PyDict_Check(dict));
1226 res = PyDict_GetItem(dict, name);
1227 if (res != NULL)
1228 return res;
1229 }
1230 return NULL;
1231}
1232
1233/* This is similar to PyObject_GenericGetAttr(),
1234 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1235static PyObject *
1236type_getattro(PyTypeObject *type, PyObject *name)
1237{
1238 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001239 PyObject *meta_attribute, *attribute;
1240 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241
1242 /* Initialize this type (we'll assume the metatype is initialized) */
1243 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001244 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 return NULL;
1246 }
1247
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001248 /* No readable descriptor found yet */
1249 meta_get = NULL;
1250
1251 /* Look for the attribute in the metatype */
1252 meta_attribute = _PyType_Lookup(metatype, name);
1253
1254 if (meta_attribute != NULL) {
1255 meta_get = meta_attribute->ob_type->tp_descr_get;
1256
1257 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1258 /* Data descriptors implement tp_descr_set to intercept
1259 * writes. Assume the attribute is not overridden in
1260 * type's tp_dict (and bases): call the descriptor now.
1261 */
1262 return meta_get(meta_attribute, (PyObject *)type,
1263 (PyObject *)metatype);
1264 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 }
1266
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001267 /* No data descriptor found on metatype. Look in tp_dict of this
1268 * type and its bases */
1269 attribute = _PyType_Lookup(type, name);
1270 if (attribute != NULL) {
1271 /* Implement descriptor functionality, if any */
1272 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1273 if (local_get != NULL) {
1274 /* NULL 2nd argument indicates the descriptor was
1275 * found on the target object itself (or a base) */
1276 return local_get(attribute, (PyObject *)NULL,
1277 (PyObject *)type);
1278 }
1279
1280 Py_INCREF(attribute);
1281 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282 }
1283
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001284 /* No attribute found in local __dict__ (or bases): use the
1285 * descriptor from the metatype, if any */
1286 if (meta_get != NULL)
1287 return meta_get(meta_attribute, (PyObject *)type,
1288 (PyObject *)metatype);
1289
1290 /* If an ordinary attribute was found on the metatype, return it now */
1291 if (meta_attribute != NULL) {
1292 Py_INCREF(meta_attribute);
1293 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 }
1295
1296 /* Give up */
1297 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001298 "type object '%.50s' has no attribute '%.400s'",
1299 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300 return NULL;
1301}
1302
1303static int
1304type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1305{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001306 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1307 PyErr_Format(
1308 PyExc_TypeError,
1309 "can't set attributes of built-in/extension type '%s'",
1310 type->tp_name);
1311 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001312 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001313 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1314 return -1;
1315 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316}
1317
1318static void
1319type_dealloc(PyTypeObject *type)
1320{
1321 etype *et;
1322
1323 /* Assert this is a heap-allocated type object */
1324 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001325 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001326 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 et = (etype *)type;
1328 Py_XDECREF(type->tp_base);
1329 Py_XDECREF(type->tp_dict);
1330 Py_XDECREF(type->tp_bases);
1331 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001332 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001333 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334 Py_XDECREF(et->name);
1335 Py_XDECREF(et->slots);
1336 type->ob_type->tp_free((PyObject *)type);
1337}
1338
Guido van Rossum1c450732001-10-08 15:18:27 +00001339static PyObject *
1340type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1341{
1342 PyObject *list, *raw, *ref;
1343 int i, n;
1344
1345 list = PyList_New(0);
1346 if (list == NULL)
1347 return NULL;
1348 raw = type->tp_subclasses;
1349 if (raw == NULL)
1350 return list;
1351 assert(PyList_Check(raw));
1352 n = PyList_GET_SIZE(raw);
1353 for (i = 0; i < n; i++) {
1354 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001355 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001356 ref = PyWeakref_GET_OBJECT(ref);
1357 if (ref != Py_None) {
1358 if (PyList_Append(list, ref) < 0) {
1359 Py_DECREF(list);
1360 return NULL;
1361 }
1362 }
1363 }
1364 return list;
1365}
1366
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001368 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001370 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1371 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 {0}
1373};
1374
1375static char type_doc[] =
1376"type(object) -> the object's type\n"
1377"type(name, bases, dict) -> a new type";
1378
Guido van Rossum048eb752001-10-02 21:24:57 +00001379static int
1380type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1381{
1382 etype *et;
1383 int err;
1384
1385 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1386 return 0;
1387
1388 et = (etype *)type;
1389
1390#define VISIT(SLOT) \
1391 if (SLOT) { \
1392 err = visit((PyObject *)(SLOT), arg); \
1393 if (err) \
1394 return err; \
1395 }
1396
1397 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001398 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001399 VISIT(type->tp_mro);
1400 VISIT(type->tp_bases);
1401 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001402 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001403 VISIT(et->slots);
1404
1405#undef VISIT
1406
1407 return 0;
1408}
1409
1410static int
1411type_clear(PyTypeObject *type)
1412{
1413 etype *et;
1414 PyObject *tmp;
1415
1416 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1417 return 0;
1418
1419 et = (etype *)type;
1420
1421#define CLEAR(SLOT) \
1422 if (SLOT) { \
1423 tmp = (PyObject *)(SLOT); \
1424 SLOT = NULL; \
1425 Py_DECREF(tmp); \
1426 }
1427
1428 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001429 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001430 CLEAR(type->tp_mro);
1431 CLEAR(type->tp_bases);
1432 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001433 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001434 CLEAR(et->slots);
1435
Tim Peters2f93e282001-10-04 05:27:00 +00001436 if (type->tp_doc != NULL) {
1437 PyObject_FREE(type->tp_doc);
1438 type->tp_doc = NULL;
1439 }
1440
Guido van Rossum048eb752001-10-02 21:24:57 +00001441#undef CLEAR
1442
1443 return 0;
1444}
1445
1446static int
1447type_is_gc(PyTypeObject *type)
1448{
1449 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1450}
1451
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001452PyTypeObject PyType_Type = {
1453 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454 0, /* ob_size */
1455 "type", /* tp_name */
1456 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001457 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 (destructor)type_dealloc, /* tp_dealloc */
1459 0, /* tp_print */
1460 0, /* tp_getattr */
1461 0, /* tp_setattr */
1462 type_compare, /* tp_compare */
1463 (reprfunc)type_repr, /* tp_repr */
1464 0, /* tp_as_number */
1465 0, /* tp_as_sequence */
1466 0, /* tp_as_mapping */
1467 (hashfunc)_Py_HashPointer, /* tp_hash */
1468 (ternaryfunc)type_call, /* tp_call */
1469 0, /* tp_str */
1470 (getattrofunc)type_getattro, /* tp_getattro */
1471 (setattrofunc)type_setattro, /* tp_setattro */
1472 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001473 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1474 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001476 (traverseproc)type_traverse, /* tp_traverse */
1477 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001479 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480 0, /* tp_iter */
1481 0, /* tp_iternext */
1482 type_methods, /* tp_methods */
1483 type_members, /* tp_members */
1484 type_getsets, /* tp_getset */
1485 0, /* tp_base */
1486 0, /* tp_dict */
1487 0, /* tp_descr_get */
1488 0, /* tp_descr_set */
1489 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1490 0, /* tp_init */
1491 0, /* tp_alloc */
1492 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001493 _PyObject_GC_Del, /* tp_free */
1494 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001495};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496
1497
1498/* The base type of all types (eventually)... except itself. */
1499
1500static int
1501object_init(PyObject *self, PyObject *args, PyObject *kwds)
1502{
1503 return 0;
1504}
1505
1506static void
1507object_dealloc(PyObject *self)
1508{
1509 self->ob_type->tp_free(self);
1510}
1511
Guido van Rossum8e248182001-08-12 05:17:56 +00001512static PyObject *
1513object_repr(PyObject *self)
1514{
Guido van Rossum76e69632001-08-16 18:52:43 +00001515 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001516 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001517
Guido van Rossum76e69632001-08-16 18:52:43 +00001518 type = self->ob_type;
1519 mod = type_module(type, NULL);
1520 if (mod == NULL)
1521 PyErr_Clear();
1522 else if (!PyString_Check(mod)) {
1523 Py_DECREF(mod);
1524 mod = NULL;
1525 }
1526 name = type_name(type, NULL);
1527 if (name == NULL)
1528 return NULL;
1529 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001530 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001531 PyString_AS_STRING(mod),
1532 PyString_AS_STRING(name),
1533 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001534 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001535 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001536 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001537 Py_XDECREF(mod);
1538 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001539 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001540}
1541
Guido van Rossumb8f63662001-08-15 23:57:02 +00001542static PyObject *
1543object_str(PyObject *self)
1544{
1545 unaryfunc f;
1546
1547 f = self->ob_type->tp_repr;
1548 if (f == NULL)
1549 f = object_repr;
1550 return f(self);
1551}
1552
Guido van Rossum8e248182001-08-12 05:17:56 +00001553static long
1554object_hash(PyObject *self)
1555{
1556 return _Py_HashPointer(self);
1557}
Guido van Rossum8e248182001-08-12 05:17:56 +00001558
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001559static PyObject *
1560object_get_class(PyObject *self, void *closure)
1561{
1562 Py_INCREF(self->ob_type);
1563 return (PyObject *)(self->ob_type);
1564}
1565
1566static int
1567equiv_structs(PyTypeObject *a, PyTypeObject *b)
1568{
1569 return a == b ||
1570 (a != NULL &&
1571 b != NULL &&
1572 a->tp_basicsize == b->tp_basicsize &&
1573 a->tp_itemsize == b->tp_itemsize &&
1574 a->tp_dictoffset == b->tp_dictoffset &&
1575 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1576 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1577 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1578}
1579
1580static int
1581same_slots_added(PyTypeObject *a, PyTypeObject *b)
1582{
1583 PyTypeObject *base = a->tp_base;
1584 int size;
1585
1586 if (base != b->tp_base)
1587 return 0;
1588 if (equiv_structs(a, base) && equiv_structs(b, base))
1589 return 1;
1590 size = base->tp_basicsize;
1591 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1592 size += sizeof(PyObject *);
1593 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1594 size += sizeof(PyObject *);
1595 return size == a->tp_basicsize && size == b->tp_basicsize;
1596}
1597
1598static int
1599object_set_class(PyObject *self, PyObject *value, void *closure)
1600{
1601 PyTypeObject *old = self->ob_type;
1602 PyTypeObject *new, *newbase, *oldbase;
1603
1604 if (!PyType_Check(value)) {
1605 PyErr_Format(PyExc_TypeError,
1606 "__class__ must be set to new-style class, not '%s' object",
1607 value->ob_type->tp_name);
1608 return -1;
1609 }
1610 new = (PyTypeObject *)value;
1611 newbase = new;
1612 oldbase = old;
1613 while (equiv_structs(newbase, newbase->tp_base))
1614 newbase = newbase->tp_base;
1615 while (equiv_structs(oldbase, oldbase->tp_base))
1616 oldbase = oldbase->tp_base;
1617 if (newbase != oldbase &&
1618 (newbase->tp_base != oldbase->tp_base ||
1619 !same_slots_added(newbase, oldbase))) {
1620 PyErr_Format(PyExc_TypeError,
1621 "__class__ assignment: "
1622 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001623 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001624 old->tp_name);
1625 return -1;
1626 }
1627 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1628 Py_INCREF(new);
1629 }
1630 self->ob_type = new;
1631 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1632 Py_DECREF(old);
1633 }
1634 return 0;
1635}
1636
1637static PyGetSetDef object_getsets[] = {
1638 {"__class__", object_get_class, object_set_class,
1639 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 {0}
1641};
1642
Guido van Rossum3926a632001-09-25 16:25:58 +00001643static PyObject *
1644object_reduce(PyObject *self, PyObject *args)
1645{
1646 /* Call copy_reg._reduce(self) */
1647 static PyObject *copy_reg_str;
1648 PyObject *copy_reg, *res;
1649
1650 if (!copy_reg_str) {
1651 copy_reg_str = PyString_InternFromString("copy_reg");
1652 if (copy_reg_str == NULL)
1653 return NULL;
1654 }
1655 copy_reg = PyImport_Import(copy_reg_str);
1656 if (!copy_reg)
1657 return NULL;
1658 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1659 Py_DECREF(copy_reg);
1660 return res;
1661}
1662
1663static PyMethodDef object_methods[] = {
1664 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1665 {0}
1666};
1667
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668PyTypeObject PyBaseObject_Type = {
1669 PyObject_HEAD_INIT(&PyType_Type)
1670 0, /* ob_size */
1671 "object", /* tp_name */
1672 sizeof(PyObject), /* tp_basicsize */
1673 0, /* tp_itemsize */
1674 (destructor)object_dealloc, /* tp_dealloc */
1675 0, /* tp_print */
1676 0, /* tp_getattr */
1677 0, /* tp_setattr */
1678 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001679 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680 0, /* tp_as_number */
1681 0, /* tp_as_sequence */
1682 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001683 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001685 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001687 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 0, /* tp_as_buffer */
1689 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1690 "The most base type", /* tp_doc */
1691 0, /* tp_traverse */
1692 0, /* tp_clear */
1693 0, /* tp_richcompare */
1694 0, /* tp_weaklistoffset */
1695 0, /* tp_iter */
1696 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001697 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001698 0, /* tp_members */
1699 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700 0, /* tp_base */
1701 0, /* tp_dict */
1702 0, /* tp_descr_get */
1703 0, /* tp_descr_set */
1704 0, /* tp_dictoffset */
1705 object_init, /* tp_init */
1706 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001707 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001708 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709};
1710
1711
1712/* Initialize the __dict__ in a type object */
1713
Fred Drake7bf97152002-03-28 05:33:33 +00001714static PyObject *
1715create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1716{
1717 PyObject *cfunc;
1718 PyObject *result;
1719
1720 cfunc = PyCFunction_New(meth, NULL);
1721 if (cfunc == NULL)
1722 return NULL;
1723 result = func(cfunc);
1724 Py_DECREF(cfunc);
1725 return result;
1726}
1727
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728static int
1729add_methods(PyTypeObject *type, PyMethodDef *meth)
1730{
Guido van Rossum687ae002001-10-15 22:03:32 +00001731 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732
1733 for (; meth->ml_name != NULL; meth++) {
1734 PyObject *descr;
1735 if (PyDict_GetItemString(dict, meth->ml_name))
1736 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001737 if (meth->ml_flags & METH_CLASS) {
1738 if (meth->ml_flags & METH_STATIC) {
1739 PyErr_SetString(PyExc_ValueError,
1740 "method cannot be both class and static");
1741 return -1;
1742 }
1743 descr = create_specialmethod(meth, PyClassMethod_New);
1744 }
1745 else if (meth->ml_flags & METH_STATIC) {
1746 descr = create_specialmethod(meth, PyStaticMethod_New);
1747 }
1748 else {
1749 descr = PyDescr_NewMethod(type, meth);
1750 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001751 if (descr == NULL)
1752 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001753 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001754 return -1;
1755 Py_DECREF(descr);
1756 }
1757 return 0;
1758}
1759
1760static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001761add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762{
Guido van Rossum687ae002001-10-15 22:03:32 +00001763 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764
1765 for (; memb->name != NULL; memb++) {
1766 PyObject *descr;
1767 if (PyDict_GetItemString(dict, memb->name))
1768 continue;
1769 descr = PyDescr_NewMember(type, memb);
1770 if (descr == NULL)
1771 return -1;
1772 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1773 return -1;
1774 Py_DECREF(descr);
1775 }
1776 return 0;
1777}
1778
1779static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001780add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781{
Guido van Rossum687ae002001-10-15 22:03:32 +00001782 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783
1784 for (; gsp->name != NULL; gsp++) {
1785 PyObject *descr;
1786 if (PyDict_GetItemString(dict, gsp->name))
1787 continue;
1788 descr = PyDescr_NewGetSet(type, gsp);
1789
1790 if (descr == NULL)
1791 return -1;
1792 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1793 return -1;
1794 Py_DECREF(descr);
1795 }
1796 return 0;
1797}
1798
Guido van Rossum13d52f02001-08-10 21:24:08 +00001799static void
1800inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801{
1802 int oldsize, newsize;
1803
Guido van Rossum13d52f02001-08-10 21:24:08 +00001804 /* Special flag magic */
1805 if (!type->tp_as_buffer && base->tp_as_buffer) {
1806 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1807 type->tp_flags |=
1808 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1809 }
1810 if (!type->tp_as_sequence && base->tp_as_sequence) {
1811 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1812 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1813 }
1814 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1815 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1816 if ((!type->tp_as_number && base->tp_as_number) ||
1817 (!type->tp_as_sequence && base->tp_as_sequence)) {
1818 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1819 if (!type->tp_as_number && !type->tp_as_sequence) {
1820 type->tp_flags |= base->tp_flags &
1821 Py_TPFLAGS_HAVE_INPLACEOPS;
1822 }
1823 }
1824 /* Wow */
1825 }
1826 if (!type->tp_as_number && base->tp_as_number) {
1827 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1828 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1829 }
1830
1831 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001832 oldsize = base->tp_basicsize;
1833 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1834 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1835 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001836 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1837 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001838 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001839 if (type->tp_traverse == NULL)
1840 type->tp_traverse = base->tp_traverse;
1841 if (type->tp_clear == NULL)
1842 type->tp_clear = base->tp_clear;
1843 }
1844 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001845 /* The condition below could use some explanation.
1846 It appears that tp_new is not inherited for static types
1847 whose base class is 'object'; this seems to be a precaution
1848 so that old extension types don't suddenly become
1849 callable (object.__new__ wouldn't insure the invariants
1850 that the extension type's own factory function ensures).
1851 Heap types, of course, are under our control, so they do
1852 inherit tp_new; static extension types that specify some
1853 other built-in type as the default are considered
1854 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001855 if (base != &PyBaseObject_Type ||
1856 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1857 if (type->tp_new == NULL)
1858 type->tp_new = base->tp_new;
1859 }
1860 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001861 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001862
1863 /* Copy other non-function slots */
1864
1865#undef COPYVAL
1866#define COPYVAL(SLOT) \
1867 if (type->SLOT == 0) type->SLOT = base->SLOT
1868
1869 COPYVAL(tp_itemsize);
1870 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1871 COPYVAL(tp_weaklistoffset);
1872 }
1873 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1874 COPYVAL(tp_dictoffset);
1875 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001876}
1877
1878static void
1879inherit_slots(PyTypeObject *type, PyTypeObject *base)
1880{
1881 PyTypeObject *basebase;
1882
1883#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884#undef COPYSLOT
1885#undef COPYNUM
1886#undef COPYSEQ
1887#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001888#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001889
1890#define SLOTDEFINED(SLOT) \
1891 (base->SLOT != 0 && \
1892 (basebase == NULL || base->SLOT != basebase->SLOT))
1893
Tim Peters6d6c1a32001-08-02 04:15:00 +00001894#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001895 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001896
1897#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1898#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1899#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001900#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901
Guido van Rossum13d52f02001-08-10 21:24:08 +00001902 /* This won't inherit indirect slots (from tp_as_number etc.)
1903 if type doesn't provide the space. */
1904
1905 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1906 basebase = base->tp_base;
1907 if (basebase->tp_as_number == NULL)
1908 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909 COPYNUM(nb_add);
1910 COPYNUM(nb_subtract);
1911 COPYNUM(nb_multiply);
1912 COPYNUM(nb_divide);
1913 COPYNUM(nb_remainder);
1914 COPYNUM(nb_divmod);
1915 COPYNUM(nb_power);
1916 COPYNUM(nb_negative);
1917 COPYNUM(nb_positive);
1918 COPYNUM(nb_absolute);
1919 COPYNUM(nb_nonzero);
1920 COPYNUM(nb_invert);
1921 COPYNUM(nb_lshift);
1922 COPYNUM(nb_rshift);
1923 COPYNUM(nb_and);
1924 COPYNUM(nb_xor);
1925 COPYNUM(nb_or);
1926 COPYNUM(nb_coerce);
1927 COPYNUM(nb_int);
1928 COPYNUM(nb_long);
1929 COPYNUM(nb_float);
1930 COPYNUM(nb_oct);
1931 COPYNUM(nb_hex);
1932 COPYNUM(nb_inplace_add);
1933 COPYNUM(nb_inplace_subtract);
1934 COPYNUM(nb_inplace_multiply);
1935 COPYNUM(nb_inplace_divide);
1936 COPYNUM(nb_inplace_remainder);
1937 COPYNUM(nb_inplace_power);
1938 COPYNUM(nb_inplace_lshift);
1939 COPYNUM(nb_inplace_rshift);
1940 COPYNUM(nb_inplace_and);
1941 COPYNUM(nb_inplace_xor);
1942 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001943 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1944 COPYNUM(nb_true_divide);
1945 COPYNUM(nb_floor_divide);
1946 COPYNUM(nb_inplace_true_divide);
1947 COPYNUM(nb_inplace_floor_divide);
1948 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949 }
1950
Guido van Rossum13d52f02001-08-10 21:24:08 +00001951 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1952 basebase = base->tp_base;
1953 if (basebase->tp_as_sequence == NULL)
1954 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955 COPYSEQ(sq_length);
1956 COPYSEQ(sq_concat);
1957 COPYSEQ(sq_repeat);
1958 COPYSEQ(sq_item);
1959 COPYSEQ(sq_slice);
1960 COPYSEQ(sq_ass_item);
1961 COPYSEQ(sq_ass_slice);
1962 COPYSEQ(sq_contains);
1963 COPYSEQ(sq_inplace_concat);
1964 COPYSEQ(sq_inplace_repeat);
1965 }
1966
Guido van Rossum13d52f02001-08-10 21:24:08 +00001967 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1968 basebase = base->tp_base;
1969 if (basebase->tp_as_mapping == NULL)
1970 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001971 COPYMAP(mp_length);
1972 COPYMAP(mp_subscript);
1973 COPYMAP(mp_ass_subscript);
1974 }
1975
Tim Petersfc57ccb2001-10-12 02:38:24 +00001976 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1977 basebase = base->tp_base;
1978 if (basebase->tp_as_buffer == NULL)
1979 basebase = NULL;
1980 COPYBUF(bf_getreadbuffer);
1981 COPYBUF(bf_getwritebuffer);
1982 COPYBUF(bf_getsegcount);
1983 COPYBUF(bf_getcharbuffer);
1984 }
1985
Guido van Rossum13d52f02001-08-10 21:24:08 +00001986 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988 COPYSLOT(tp_dealloc);
1989 COPYSLOT(tp_print);
1990 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1991 type->tp_getattr = base->tp_getattr;
1992 type->tp_getattro = base->tp_getattro;
1993 }
1994 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1995 type->tp_setattr = base->tp_setattr;
1996 type->tp_setattro = base->tp_setattro;
1997 }
1998 /* tp_compare see tp_richcompare */
1999 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002000 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002001 COPYSLOT(tp_call);
2002 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002004 if (type->tp_compare == NULL &&
2005 type->tp_richcompare == NULL &&
2006 type->tp_hash == NULL)
2007 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008 type->tp_compare = base->tp_compare;
2009 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002010 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011 }
2012 }
2013 else {
2014 COPYSLOT(tp_compare);
2015 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2017 COPYSLOT(tp_iter);
2018 COPYSLOT(tp_iternext);
2019 }
2020 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2021 COPYSLOT(tp_descr_get);
2022 COPYSLOT(tp_descr_set);
2023 COPYSLOT(tp_dictoffset);
2024 COPYSLOT(tp_init);
2025 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 COPYSLOT(tp_free);
2027 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002028}
2029
Guido van Rossum13d52f02001-08-10 21:24:08 +00002030staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002031staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002032
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002034PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002036 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037 PyTypeObject *base;
2038 int i, n;
2039
Guido van Rossumd614f972001-08-10 17:39:49 +00002040 if (type->tp_flags & Py_TPFLAGS_READY) {
2041 assert(type->tp_dict != NULL);
2042 return 0;
2043 }
2044 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002045
2046 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047
Guido van Rossumf884b742001-12-17 17:14:22 +00002048 /* Initialize ob_type if NULL. This means extensions that want to be
2049 compilable separately on Windows can call PyType_Ready() instead of
2050 initializing the ob_type field of their type objects. */
2051 if (type->ob_type == NULL)
2052 type->ob_type = &PyType_Type;
2053
Tim Peters6d6c1a32001-08-02 04:15:00 +00002054 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2055 base = type->tp_base;
2056 if (base == NULL && type != &PyBaseObject_Type)
2057 base = type->tp_base = &PyBaseObject_Type;
2058
2059 /* Initialize tp_bases */
2060 bases = type->tp_bases;
2061 if (bases == NULL) {
2062 if (base == NULL)
2063 bases = PyTuple_New(0);
2064 else
2065 bases = Py_BuildValue("(O)", base);
2066 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002067 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002068 type->tp_bases = bases;
2069 }
2070
2071 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002072 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002073 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002074 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002075 }
2076
Guido van Rossum687ae002001-10-15 22:03:32 +00002077 /* Initialize tp_dict */
2078 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079 if (dict == NULL) {
2080 dict = PyDict_New();
2081 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002082 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002083 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084 }
2085
Guido van Rossum687ae002001-10-15 22:03:32 +00002086 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002087 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002088 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 if (type->tp_methods != NULL) {
2090 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002091 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092 }
2093 if (type->tp_members != NULL) {
2094 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002095 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002096 }
2097 if (type->tp_getset != NULL) {
2098 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002099 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002100 }
2101
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 /* Calculate method resolution order */
2103 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002104 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002105 }
2106
Guido van Rossum13d52f02001-08-10 21:24:08 +00002107 /* Inherit special flags from dominant base */
2108 if (type->tp_base != NULL)
2109 inherit_special(type, type->tp_base);
2110
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002112 bases = type->tp_mro;
2113 assert(bases != NULL);
2114 assert(PyTuple_Check(bases));
2115 n = PyTuple_GET_SIZE(bases);
2116 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002117 PyObject *b = PyTuple_GET_ITEM(bases, i);
2118 if (PyType_Check(b))
2119 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002120 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002122 /* if the type dictionary doesn't contain a __doc__, set it from
2123 the tp_doc slot.
2124 */
2125 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2126 if (type->tp_doc != NULL) {
2127 PyObject *doc = PyString_FromString(type->tp_doc);
2128 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2129 Py_DECREF(doc);
2130 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002131 PyDict_SetItemString(type->tp_dict,
2132 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002133 }
2134 }
2135
Guido van Rossum13d52f02001-08-10 21:24:08 +00002136 /* Some more special stuff */
2137 base = type->tp_base;
2138 if (base != NULL) {
2139 if (type->tp_as_number == NULL)
2140 type->tp_as_number = base->tp_as_number;
2141 if (type->tp_as_sequence == NULL)
2142 type->tp_as_sequence = base->tp_as_sequence;
2143 if (type->tp_as_mapping == NULL)
2144 type->tp_as_mapping = base->tp_as_mapping;
2145 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146
Guido van Rossum1c450732001-10-08 15:18:27 +00002147 /* Link into each base class's list of subclasses */
2148 bases = type->tp_bases;
2149 n = PyTuple_GET_SIZE(bases);
2150 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002151 PyObject *b = PyTuple_GET_ITEM(bases, i);
2152 if (PyType_Check(b) &&
2153 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002154 goto error;
2155 }
2156
Guido van Rossum13d52f02001-08-10 21:24:08 +00002157 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002158 assert(type->tp_dict != NULL);
2159 type->tp_flags =
2160 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002162
2163 error:
2164 type->tp_flags &= ~Py_TPFLAGS_READYING;
2165 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166}
2167
Guido van Rossum1c450732001-10-08 15:18:27 +00002168static int
2169add_subclass(PyTypeObject *base, PyTypeObject *type)
2170{
2171 int i;
2172 PyObject *list, *ref, *new;
2173
2174 list = base->tp_subclasses;
2175 if (list == NULL) {
2176 base->tp_subclasses = list = PyList_New(0);
2177 if (list == NULL)
2178 return -1;
2179 }
2180 assert(PyList_Check(list));
2181 new = PyWeakref_NewRef((PyObject *)type, NULL);
2182 i = PyList_GET_SIZE(list);
2183 while (--i >= 0) {
2184 ref = PyList_GET_ITEM(list, i);
2185 assert(PyWeakref_CheckRef(ref));
2186 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2187 return PyList_SetItem(list, i, new);
2188 }
2189 i = PyList_Append(list, new);
2190 Py_DECREF(new);
2191 return i;
2192}
2193
Tim Peters6d6c1a32001-08-02 04:15:00 +00002194
2195/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2196
2197/* There's a wrapper *function* for each distinct function typedef used
2198 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2199 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2200 Most tables have only one entry; the tables for binary operators have two
2201 entries, one regular and one with reversed arguments. */
2202
2203static PyObject *
2204wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2205{
2206 inquiry func = (inquiry)wrapped;
2207 int res;
2208
2209 if (!PyArg_ParseTuple(args, ""))
2210 return NULL;
2211 res = (*func)(self);
2212 if (res == -1 && PyErr_Occurred())
2213 return NULL;
2214 return PyInt_FromLong((long)res);
2215}
2216
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217static PyObject *
2218wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2219{
2220 binaryfunc func = (binaryfunc)wrapped;
2221 PyObject *other;
2222
2223 if (!PyArg_ParseTuple(args, "O", &other))
2224 return NULL;
2225 return (*func)(self, other);
2226}
2227
2228static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002229wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2230{
2231 binaryfunc func = (binaryfunc)wrapped;
2232 PyObject *other;
2233
2234 if (!PyArg_ParseTuple(args, "O", &other))
2235 return NULL;
2236 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002237 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002238 Py_INCREF(Py_NotImplemented);
2239 return Py_NotImplemented;
2240 }
2241 return (*func)(self, other);
2242}
2243
2244static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2246{
2247 binaryfunc func = (binaryfunc)wrapped;
2248 PyObject *other;
2249
2250 if (!PyArg_ParseTuple(args, "O", &other))
2251 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002252 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002253 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002254 Py_INCREF(Py_NotImplemented);
2255 return Py_NotImplemented;
2256 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002257 return (*func)(other, self);
2258}
2259
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002260static PyObject *
2261wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2262{
2263 coercion func = (coercion)wrapped;
2264 PyObject *other, *res;
2265 int ok;
2266
2267 if (!PyArg_ParseTuple(args, "O", &other))
2268 return NULL;
2269 ok = func(&self, &other);
2270 if (ok < 0)
2271 return NULL;
2272 if (ok > 0) {
2273 Py_INCREF(Py_NotImplemented);
2274 return Py_NotImplemented;
2275 }
2276 res = PyTuple_New(2);
2277 if (res == NULL) {
2278 Py_DECREF(self);
2279 Py_DECREF(other);
2280 return NULL;
2281 }
2282 PyTuple_SET_ITEM(res, 0, self);
2283 PyTuple_SET_ITEM(res, 1, other);
2284 return res;
2285}
2286
Tim Peters6d6c1a32001-08-02 04:15:00 +00002287static PyObject *
2288wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2289{
2290 ternaryfunc func = (ternaryfunc)wrapped;
2291 PyObject *other;
2292 PyObject *third = Py_None;
2293
2294 /* Note: This wrapper only works for __pow__() */
2295
2296 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2297 return NULL;
2298 return (*func)(self, other, third);
2299}
2300
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002301static PyObject *
2302wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2303{
2304 ternaryfunc func = (ternaryfunc)wrapped;
2305 PyObject *other;
2306 PyObject *third = Py_None;
2307
2308 /* Note: This wrapper only works for __pow__() */
2309
2310 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2311 return NULL;
2312 return (*func)(other, self, third);
2313}
2314
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315static PyObject *
2316wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2317{
2318 unaryfunc func = (unaryfunc)wrapped;
2319
2320 if (!PyArg_ParseTuple(args, ""))
2321 return NULL;
2322 return (*func)(self);
2323}
2324
Tim Peters6d6c1a32001-08-02 04:15:00 +00002325static PyObject *
2326wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2327{
2328 intargfunc func = (intargfunc)wrapped;
2329 int i;
2330
2331 if (!PyArg_ParseTuple(args, "i", &i))
2332 return NULL;
2333 return (*func)(self, i);
2334}
2335
Guido van Rossum5d815f32001-08-17 21:57:47 +00002336static int
2337getindex(PyObject *self, PyObject *arg)
2338{
2339 int i;
2340
2341 i = PyInt_AsLong(arg);
2342 if (i == -1 && PyErr_Occurred())
2343 return -1;
2344 if (i < 0) {
2345 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2346 if (sq && sq->sq_length) {
2347 int n = (*sq->sq_length)(self);
2348 if (n < 0)
2349 return -1;
2350 i += n;
2351 }
2352 }
2353 return i;
2354}
2355
2356static PyObject *
2357wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2358{
2359 intargfunc func = (intargfunc)wrapped;
2360 PyObject *arg;
2361 int i;
2362
Guido van Rossumf4593e02001-10-03 12:09:30 +00002363 if (PyTuple_GET_SIZE(args) == 1) {
2364 arg = PyTuple_GET_ITEM(args, 0);
2365 i = getindex(self, arg);
2366 if (i == -1 && PyErr_Occurred())
2367 return NULL;
2368 return (*func)(self, i);
2369 }
2370 PyArg_ParseTuple(args, "O", &arg);
2371 assert(PyErr_Occurred());
2372 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002373}
2374
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375static PyObject *
2376wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2377{
2378 intintargfunc func = (intintargfunc)wrapped;
2379 int i, j;
2380
2381 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2382 return NULL;
2383 return (*func)(self, i, j);
2384}
2385
Tim Peters6d6c1a32001-08-02 04:15:00 +00002386static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002387wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002388{
2389 intobjargproc func = (intobjargproc)wrapped;
2390 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002391 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392
Guido van Rossum5d815f32001-08-17 21:57:47 +00002393 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2394 return NULL;
2395 i = getindex(self, arg);
2396 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397 return NULL;
2398 res = (*func)(self, i, value);
2399 if (res == -1 && PyErr_Occurred())
2400 return NULL;
2401 Py_INCREF(Py_None);
2402 return Py_None;
2403}
2404
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002405static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002406wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002407{
2408 intobjargproc func = (intobjargproc)wrapped;
2409 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002410 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002411
Guido van Rossum5d815f32001-08-17 21:57:47 +00002412 if (!PyArg_ParseTuple(args, "O", &arg))
2413 return NULL;
2414 i = getindex(self, arg);
2415 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002416 return NULL;
2417 res = (*func)(self, i, NULL);
2418 if (res == -1 && PyErr_Occurred())
2419 return NULL;
2420 Py_INCREF(Py_None);
2421 return Py_None;
2422}
2423
Tim Peters6d6c1a32001-08-02 04:15:00 +00002424static PyObject *
2425wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2426{
2427 intintobjargproc func = (intintobjargproc)wrapped;
2428 int i, j, res;
2429 PyObject *value;
2430
2431 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2432 return NULL;
2433 res = (*func)(self, i, j, value);
2434 if (res == -1 && PyErr_Occurred())
2435 return NULL;
2436 Py_INCREF(Py_None);
2437 return Py_None;
2438}
2439
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002440static PyObject *
2441wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2442{
2443 intintobjargproc func = (intintobjargproc)wrapped;
2444 int i, j, res;
2445
2446 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2447 return NULL;
2448 res = (*func)(self, i, j, NULL);
2449 if (res == -1 && PyErr_Occurred())
2450 return NULL;
2451 Py_INCREF(Py_None);
2452 return Py_None;
2453}
2454
Tim Peters6d6c1a32001-08-02 04:15:00 +00002455/* XXX objobjproc is a misnomer; should be objargpred */
2456static PyObject *
2457wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2458{
2459 objobjproc func = (objobjproc)wrapped;
2460 int res;
2461 PyObject *value;
2462
2463 if (!PyArg_ParseTuple(args, "O", &value))
2464 return NULL;
2465 res = (*func)(self, value);
2466 if (res == -1 && PyErr_Occurred())
2467 return NULL;
2468 return PyInt_FromLong((long)res);
2469}
2470
Tim Peters6d6c1a32001-08-02 04:15:00 +00002471static PyObject *
2472wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2473{
2474 objobjargproc func = (objobjargproc)wrapped;
2475 int res;
2476 PyObject *key, *value;
2477
2478 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2479 return NULL;
2480 res = (*func)(self, key, value);
2481 if (res == -1 && PyErr_Occurred())
2482 return NULL;
2483 Py_INCREF(Py_None);
2484 return Py_None;
2485}
2486
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002487static PyObject *
2488wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2489{
2490 objobjargproc func = (objobjargproc)wrapped;
2491 int res;
2492 PyObject *key;
2493
2494 if (!PyArg_ParseTuple(args, "O", &key))
2495 return NULL;
2496 res = (*func)(self, key, NULL);
2497 if (res == -1 && PyErr_Occurred())
2498 return NULL;
2499 Py_INCREF(Py_None);
2500 return Py_None;
2501}
2502
Tim Peters6d6c1a32001-08-02 04:15:00 +00002503static PyObject *
2504wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2505{
2506 cmpfunc func = (cmpfunc)wrapped;
2507 int res;
2508 PyObject *other;
2509
2510 if (!PyArg_ParseTuple(args, "O", &other))
2511 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002512 if (other->ob_type->tp_compare != func &&
2513 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002514 PyErr_Format(
2515 PyExc_TypeError,
2516 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2517 self->ob_type->tp_name,
2518 self->ob_type->tp_name,
2519 other->ob_type->tp_name);
2520 return NULL;
2521 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002522 res = (*func)(self, other);
2523 if (PyErr_Occurred())
2524 return NULL;
2525 return PyInt_FromLong((long)res);
2526}
2527
Tim Peters6d6c1a32001-08-02 04:15:00 +00002528static PyObject *
2529wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2530{
2531 setattrofunc func = (setattrofunc)wrapped;
2532 int res;
2533 PyObject *name, *value;
2534
2535 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2536 return NULL;
2537 res = (*func)(self, name, value);
2538 if (res < 0)
2539 return NULL;
2540 Py_INCREF(Py_None);
2541 return Py_None;
2542}
2543
2544static PyObject *
2545wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2546{
2547 setattrofunc func = (setattrofunc)wrapped;
2548 int res;
2549 PyObject *name;
2550
2551 if (!PyArg_ParseTuple(args, "O", &name))
2552 return NULL;
2553 res = (*func)(self, name, NULL);
2554 if (res < 0)
2555 return NULL;
2556 Py_INCREF(Py_None);
2557 return Py_None;
2558}
2559
Tim Peters6d6c1a32001-08-02 04:15:00 +00002560static PyObject *
2561wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2562{
2563 hashfunc func = (hashfunc)wrapped;
2564 long res;
2565
2566 if (!PyArg_ParseTuple(args, ""))
2567 return NULL;
2568 res = (*func)(self);
2569 if (res == -1 && PyErr_Occurred())
2570 return NULL;
2571 return PyInt_FromLong(res);
2572}
2573
Tim Peters6d6c1a32001-08-02 04:15:00 +00002574static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002575wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002576{
2577 ternaryfunc func = (ternaryfunc)wrapped;
2578
Guido van Rossumc8e56452001-10-22 00:43:43 +00002579 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580}
2581
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582static PyObject *
2583wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2584{
2585 richcmpfunc func = (richcmpfunc)wrapped;
2586 PyObject *other;
2587
2588 if (!PyArg_ParseTuple(args, "O", &other))
2589 return NULL;
2590 return (*func)(self, other, op);
2591}
2592
2593#undef RICHCMP_WRAPPER
2594#define RICHCMP_WRAPPER(NAME, OP) \
2595static PyObject * \
2596richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2597{ \
2598 return wrap_richcmpfunc(self, args, wrapped, OP); \
2599}
2600
Jack Jansen8e938b42001-08-08 15:29:49 +00002601RICHCMP_WRAPPER(lt, Py_LT)
2602RICHCMP_WRAPPER(le, Py_LE)
2603RICHCMP_WRAPPER(eq, Py_EQ)
2604RICHCMP_WRAPPER(ne, Py_NE)
2605RICHCMP_WRAPPER(gt, Py_GT)
2606RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607
Tim Peters6d6c1a32001-08-02 04:15:00 +00002608static PyObject *
2609wrap_next(PyObject *self, PyObject *args, void *wrapped)
2610{
2611 unaryfunc func = (unaryfunc)wrapped;
2612 PyObject *res;
2613
2614 if (!PyArg_ParseTuple(args, ""))
2615 return NULL;
2616 res = (*func)(self);
2617 if (res == NULL && !PyErr_Occurred())
2618 PyErr_SetNone(PyExc_StopIteration);
2619 return res;
2620}
2621
Tim Peters6d6c1a32001-08-02 04:15:00 +00002622static PyObject *
2623wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2624{
2625 descrgetfunc func = (descrgetfunc)wrapped;
2626 PyObject *obj;
2627 PyObject *type = NULL;
2628
2629 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2630 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002631 return (*func)(self, obj, type);
2632}
2633
Tim Peters6d6c1a32001-08-02 04:15:00 +00002634static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002635wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636{
2637 descrsetfunc func = (descrsetfunc)wrapped;
2638 PyObject *obj, *value;
2639 int ret;
2640
2641 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2642 return NULL;
2643 ret = (*func)(self, obj, value);
2644 if (ret < 0)
2645 return NULL;
2646 Py_INCREF(Py_None);
2647 return Py_None;
2648}
2649
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002651wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652{
2653 initproc func = (initproc)wrapped;
2654
Guido van Rossumc8e56452001-10-22 00:43:43 +00002655 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002656 return NULL;
2657 Py_INCREF(Py_None);
2658 return Py_None;
2659}
2660
Tim Peters6d6c1a32001-08-02 04:15:00 +00002661static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002662tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002663{
Barry Warsaw60f01882001-08-22 19:24:42 +00002664 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002665 PyObject *arg0, *res;
2666
2667 if (self == NULL || !PyType_Check(self))
2668 Py_FatalError("__new__() called with non-type 'self'");
2669 type = (PyTypeObject *)self;
2670 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002671 PyErr_Format(PyExc_TypeError,
2672 "%s.__new__(): not enough arguments",
2673 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002674 return NULL;
2675 }
2676 arg0 = PyTuple_GET_ITEM(args, 0);
2677 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002678 PyErr_Format(PyExc_TypeError,
2679 "%s.__new__(X): X is not a type object (%s)",
2680 type->tp_name,
2681 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002682 return NULL;
2683 }
2684 subtype = (PyTypeObject *)arg0;
2685 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002686 PyErr_Format(PyExc_TypeError,
2687 "%s.__new__(%s): %s is not a subtype of %s",
2688 type->tp_name,
2689 subtype->tp_name,
2690 subtype->tp_name,
2691 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002692 return NULL;
2693 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002694
2695 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002696 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002697 most derived base that's not a heap type is this type. */
2698 staticbase = subtype;
2699 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2700 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002701 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002702 PyErr_Format(PyExc_TypeError,
2703 "%s.__new__(%s) is not safe, use %s.__new__()",
2704 type->tp_name,
2705 subtype->tp_name,
2706 staticbase == NULL ? "?" : staticbase->tp_name);
2707 return NULL;
2708 }
2709
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002710 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2711 if (args == NULL)
2712 return NULL;
2713 res = type->tp_new(subtype, args, kwds);
2714 Py_DECREF(args);
2715 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716}
2717
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002718static struct PyMethodDef tp_new_methoddef[] = {
2719 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2720 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721 {0}
2722};
2723
2724static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002725add_tp_new_wrapper(PyTypeObject *type)
2726{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002727 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002728
Guido van Rossum687ae002001-10-15 22:03:32 +00002729 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002730 return 0;
2731 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002732 if (func == NULL)
2733 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002734 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002735}
2736
Guido van Rossumf040ede2001-08-07 16:40:56 +00002737/* Slot wrappers that call the corresponding __foo__ slot. See comments
2738 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002739
Guido van Rossumdc91b992001-08-08 22:26:22 +00002740#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002742FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002744 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002745 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746}
2747
Guido van Rossumdc91b992001-08-08 22:26:22 +00002748#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002749static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002750FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002752 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002753 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002754}
2755
Guido van Rossumdc91b992001-08-08 22:26:22 +00002756
2757#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002759FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002761 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002762 int do_other = self->ob_type != other->ob_type && \
2763 other->ob_type->tp_as_number != NULL && \
2764 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002765 if (self->ob_type->tp_as_number != NULL && \
2766 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2767 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002768 if (do_other && \
2769 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2770 r = call_maybe( \
2771 other, ROPSTR, &rcache_str, "(O)", self); \
2772 if (r != Py_NotImplemented) \
2773 return r; \
2774 Py_DECREF(r); \
2775 do_other = 0; \
2776 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002777 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002778 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002779 if (r != Py_NotImplemented || \
2780 other->ob_type == self->ob_type) \
2781 return r; \
2782 Py_DECREF(r); \
2783 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002784 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002785 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002786 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002787 } \
2788 Py_INCREF(Py_NotImplemented); \
2789 return Py_NotImplemented; \
2790}
2791
2792#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2793 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2794
2795#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2796static PyObject * \
2797FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2798{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002799 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002800 return call_method(self, OPSTR, &cache_str, \
2801 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002802}
2803
2804static int
2805slot_sq_length(PyObject *self)
2806{
Guido van Rossum2730b132001-08-28 18:22:14 +00002807 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002808 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002809 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810
2811 if (res == NULL)
2812 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002813 len = (int)PyInt_AsLong(res);
2814 Py_DECREF(res);
2815 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816}
2817
Guido van Rossumdc91b992001-08-08 22:26:22 +00002818SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2819SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002820
2821/* Super-optimized version of slot_sq_item.
2822 Other slots could do the same... */
2823static PyObject *
2824slot_sq_item(PyObject *self, int i)
2825{
2826 static PyObject *getitem_str;
2827 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2828 descrgetfunc f;
2829
2830 if (getitem_str == NULL) {
2831 getitem_str = PyString_InternFromString("__getitem__");
2832 if (getitem_str == NULL)
2833 return NULL;
2834 }
2835 func = _PyType_Lookup(self->ob_type, getitem_str);
2836 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002837 if ((f = func->ob_type->tp_descr_get) == NULL)
2838 Py_INCREF(func);
2839 else
2840 func = f(func, self, (PyObject *)(self->ob_type));
2841 ival = PyInt_FromLong(i);
2842 if (ival != NULL) {
2843 args = PyTuple_New(1);
2844 if (args != NULL) {
2845 PyTuple_SET_ITEM(args, 0, ival);
2846 retval = PyObject_Call(func, args, NULL);
2847 Py_XDECREF(args);
2848 Py_XDECREF(func);
2849 return retval;
2850 }
2851 }
2852 }
2853 else {
2854 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2855 }
2856 Py_XDECREF(args);
2857 Py_XDECREF(ival);
2858 Py_XDECREF(func);
2859 return NULL;
2860}
2861
Guido van Rossumdc91b992001-08-08 22:26:22 +00002862SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002863
2864static int
2865slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2866{
2867 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002868 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869
2870 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002871 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002872 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002873 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002874 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002875 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002876 if (res == NULL)
2877 return -1;
2878 Py_DECREF(res);
2879 return 0;
2880}
2881
2882static int
2883slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2884{
2885 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002886 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887
2888 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002889 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002890 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002892 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002893 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894 if (res == NULL)
2895 return -1;
2896 Py_DECREF(res);
2897 return 0;
2898}
2899
2900static int
2901slot_sq_contains(PyObject *self, PyObject *value)
2902{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002903 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002904 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002905
Guido van Rossum55f20992001-10-01 17:18:22 +00002906 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002907
2908 if (func != NULL) {
2909 args = Py_BuildValue("(O)", value);
2910 if (args == NULL)
2911 res = NULL;
2912 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002913 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002914 Py_DECREF(args);
2915 }
2916 Py_DECREF(func);
2917 if (res == NULL)
2918 return -1;
2919 return PyObject_IsTrue(res);
2920 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002921 else if (PyErr_Occurred())
2922 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002923 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002924 return _PySequence_IterSearch(self, value,
2925 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002926 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927}
2928
Guido van Rossumdc91b992001-08-08 22:26:22 +00002929SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2930SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002931
2932#define slot_mp_length slot_sq_length
2933
Guido van Rossumdc91b992001-08-08 22:26:22 +00002934SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002935
2936static int
2937slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2938{
2939 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002940 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941
2942 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002943 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002944 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002946 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002947 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002948 if (res == NULL)
2949 return -1;
2950 Py_DECREF(res);
2951 return 0;
2952}
2953
Guido van Rossumdc91b992001-08-08 22:26:22 +00002954SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2955SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2956SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2957SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2958SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2959SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2960
2961staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2962
2963SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2964 nb_power, "__pow__", "__rpow__")
2965
2966static PyObject *
2967slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2968{
Guido van Rossum2730b132001-08-28 18:22:14 +00002969 static PyObject *pow_str;
2970
Guido van Rossumdc91b992001-08-08 22:26:22 +00002971 if (modulus == Py_None)
2972 return slot_nb_power_binary(self, other);
2973 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002974 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002975 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002976}
2977
2978SLOT0(slot_nb_negative, "__neg__")
2979SLOT0(slot_nb_positive, "__pos__")
2980SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981
2982static int
2983slot_nb_nonzero(PyObject *self)
2984{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002985 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002986 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987
Guido van Rossum55f20992001-10-01 17:18:22 +00002988 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002989 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002990 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002991 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002992 func = lookup_maybe(self, "__len__", &len_str);
2993 if (func == NULL) {
2994 if (PyErr_Occurred())
2995 return -1;
2996 else
2997 return 1;
2998 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002999 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003000 res = PyObject_CallObject(func, NULL);
3001 Py_DECREF(func);
3002 if (res == NULL)
3003 return -1;
3004 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005}
3006
Guido van Rossumdc91b992001-08-08 22:26:22 +00003007SLOT0(slot_nb_invert, "__invert__")
3008SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3009SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3010SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3011SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3012SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003013
3014static int
3015slot_nb_coerce(PyObject **a, PyObject **b)
3016{
3017 static PyObject *coerce_str;
3018 PyObject *self = *a, *other = *b;
3019
3020 if (self->ob_type->tp_as_number != NULL &&
3021 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3022 PyObject *r;
3023 r = call_maybe(
3024 self, "__coerce__", &coerce_str, "(O)", other);
3025 if (r == NULL)
3026 return -1;
3027 if (r == Py_NotImplemented) {
3028 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003029 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003030 else {
3031 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3032 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003033 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003034 Py_DECREF(r);
3035 return -1;
3036 }
3037 *a = PyTuple_GET_ITEM(r, 0);
3038 Py_INCREF(*a);
3039 *b = PyTuple_GET_ITEM(r, 1);
3040 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003041 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003042 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003043 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003044 }
3045 if (other->ob_type->tp_as_number != NULL &&
3046 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3047 PyObject *r;
3048 r = call_maybe(
3049 other, "__coerce__", &coerce_str, "(O)", self);
3050 if (r == NULL)
3051 return -1;
3052 if (r == Py_NotImplemented) {
3053 Py_DECREF(r);
3054 return 1;
3055 }
3056 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3057 PyErr_SetString(PyExc_TypeError,
3058 "__coerce__ didn't return a 2-tuple");
3059 Py_DECREF(r);
3060 return -1;
3061 }
3062 *a = PyTuple_GET_ITEM(r, 1);
3063 Py_INCREF(*a);
3064 *b = PyTuple_GET_ITEM(r, 0);
3065 Py_INCREF(*b);
3066 Py_DECREF(r);
3067 return 0;
3068 }
3069 return 1;
3070}
3071
Guido van Rossumdc91b992001-08-08 22:26:22 +00003072SLOT0(slot_nb_int, "__int__")
3073SLOT0(slot_nb_long, "__long__")
3074SLOT0(slot_nb_float, "__float__")
3075SLOT0(slot_nb_oct, "__oct__")
3076SLOT0(slot_nb_hex, "__hex__")
3077SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3078SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3079SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3080SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3081SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3082SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3083SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3084SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3085SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3086SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3087SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3088SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3089 "__floordiv__", "__rfloordiv__")
3090SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3091SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3092SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003093
3094static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003095half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003097 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003098 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003099 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003100
Guido van Rossum60718732001-08-28 17:47:51 +00003101 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003102 if (func == NULL) {
3103 PyErr_Clear();
3104 }
3105 else {
3106 args = Py_BuildValue("(O)", other);
3107 if (args == NULL)
3108 res = NULL;
3109 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003110 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003111 Py_DECREF(args);
3112 }
3113 if (res != Py_NotImplemented) {
3114 if (res == NULL)
3115 return -2;
3116 c = PyInt_AsLong(res);
3117 Py_DECREF(res);
3118 if (c == -1 && PyErr_Occurred())
3119 return -2;
3120 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3121 }
3122 Py_DECREF(res);
3123 }
3124 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125}
3126
Guido van Rossumab3b0342001-09-18 20:38:53 +00003127/* This slot is published for the benefit of try_3way_compare in object.c */
3128int
3129_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003130{
3131 int c;
3132
Guido van Rossumab3b0342001-09-18 20:38:53 +00003133 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003134 c = half_compare(self, other);
3135 if (c <= 1)
3136 return c;
3137 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003138 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003139 c = half_compare(other, self);
3140 if (c < -1)
3141 return -2;
3142 if (c <= 1)
3143 return -c;
3144 }
3145 return (void *)self < (void *)other ? -1 :
3146 (void *)self > (void *)other ? 1 : 0;
3147}
3148
3149static PyObject *
3150slot_tp_repr(PyObject *self)
3151{
3152 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003153 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003154
Guido van Rossum60718732001-08-28 17:47:51 +00003155 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003156 if (func != NULL) {
3157 res = PyEval_CallObject(func, NULL);
3158 Py_DECREF(func);
3159 return res;
3160 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003161 PyErr_Clear();
3162 return PyString_FromFormat("<%s object at %p>",
3163 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003164}
3165
3166static PyObject *
3167slot_tp_str(PyObject *self)
3168{
3169 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003170 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003171
Guido van Rossum60718732001-08-28 17:47:51 +00003172 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003173 if (func != NULL) {
3174 res = PyEval_CallObject(func, NULL);
3175 Py_DECREF(func);
3176 return res;
3177 }
3178 else {
3179 PyErr_Clear();
3180 return slot_tp_repr(self);
3181 }
3182}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183
3184static long
3185slot_tp_hash(PyObject *self)
3186{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003187 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003188 static PyObject *hash_str, *eq_str, *cmp_str;
3189
Tim Peters6d6c1a32001-08-02 04:15:00 +00003190 long h;
3191
Guido van Rossum60718732001-08-28 17:47:51 +00003192 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003193
3194 if (func != NULL) {
3195 res = PyEval_CallObject(func, NULL);
3196 Py_DECREF(func);
3197 if (res == NULL)
3198 return -1;
3199 h = PyInt_AsLong(res);
3200 }
3201 else {
3202 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003203 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003204 if (func == NULL) {
3205 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003206 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003207 }
3208 if (func != NULL) {
3209 Py_DECREF(func);
3210 PyErr_SetString(PyExc_TypeError, "unhashable type");
3211 return -1;
3212 }
3213 PyErr_Clear();
3214 h = _Py_HashPointer((void *)self);
3215 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003216 if (h == -1 && !PyErr_Occurred())
3217 h = -2;
3218 return h;
3219}
3220
3221static PyObject *
3222slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3223{
Guido van Rossum60718732001-08-28 17:47:51 +00003224 static PyObject *call_str;
3225 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003226 PyObject *res;
3227
3228 if (meth == NULL)
3229 return NULL;
3230 res = PyObject_Call(meth, args, kwds);
3231 Py_DECREF(meth);
3232 return res;
3233}
3234
Guido van Rossum14a6f832001-10-17 13:59:09 +00003235/* There are two slot dispatch functions for tp_getattro.
3236
3237 - slot_tp_getattro() is used when __getattribute__ is overridden
3238 but no __getattr__ hook is present;
3239
3240 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3241
Guido van Rossumc334df52002-04-04 23:44:47 +00003242 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3243 detects the absence of __getattr__ and then installs the simpler slot if
3244 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003245
Tim Peters6d6c1a32001-08-02 04:15:00 +00003246static PyObject *
3247slot_tp_getattro(PyObject *self, PyObject *name)
3248{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003249 static PyObject *getattribute_str = NULL;
3250 return call_method(self, "__getattribute__", &getattribute_str,
3251 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003252}
3253
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003254static PyObject *
3255slot_tp_getattr_hook(PyObject *self, PyObject *name)
3256{
3257 PyTypeObject *tp = self->ob_type;
3258 PyObject *getattr, *getattribute, *res;
3259 static PyObject *getattribute_str = NULL;
3260 static PyObject *getattr_str = NULL;
3261
3262 if (getattr_str == NULL) {
3263 getattr_str = PyString_InternFromString("__getattr__");
3264 if (getattr_str == NULL)
3265 return NULL;
3266 }
3267 if (getattribute_str == NULL) {
3268 getattribute_str =
3269 PyString_InternFromString("__getattribute__");
3270 if (getattribute_str == NULL)
3271 return NULL;
3272 }
3273 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003274 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003275 /* No __getattr__ hook: use a simpler dispatcher */
3276 tp->tp_getattro = slot_tp_getattro;
3277 return slot_tp_getattro(self, name);
3278 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003279 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003280 if (getattribute == NULL ||
3281 (getattribute->ob_type == &PyWrapperDescr_Type &&
3282 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3283 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003284 res = PyObject_GenericGetAttr(self, name);
3285 else
3286 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003287 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003288 PyErr_Clear();
3289 res = PyObject_CallFunction(getattr, "OO", self, name);
3290 }
3291 return res;
3292}
3293
Tim Peters6d6c1a32001-08-02 04:15:00 +00003294static int
3295slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3296{
3297 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003298 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299
3300 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003301 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003302 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003303 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003304 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003305 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306 if (res == NULL)
3307 return -1;
3308 Py_DECREF(res);
3309 return 0;
3310}
3311
3312/* Map rich comparison operators to their __xx__ namesakes */
3313static char *name_op[] = {
3314 "__lt__",
3315 "__le__",
3316 "__eq__",
3317 "__ne__",
3318 "__gt__",
3319 "__ge__",
3320};
3321
3322static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003323half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003325 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003326 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327
Guido van Rossum60718732001-08-28 17:47:51 +00003328 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003329 if (func == NULL) {
3330 PyErr_Clear();
3331 Py_INCREF(Py_NotImplemented);
3332 return Py_NotImplemented;
3333 }
3334 args = Py_BuildValue("(O)", other);
3335 if (args == NULL)
3336 res = NULL;
3337 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003338 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003339 Py_DECREF(args);
3340 }
3341 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003342 return res;
3343}
3344
Guido van Rossumb8f63662001-08-15 23:57:02 +00003345/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3346static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3347
3348static PyObject *
3349slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3350{
3351 PyObject *res;
3352
3353 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3354 res = half_richcompare(self, other, op);
3355 if (res != Py_NotImplemented)
3356 return res;
3357 Py_DECREF(res);
3358 }
3359 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3360 res = half_richcompare(other, self, swapped_op[op]);
3361 if (res != Py_NotImplemented) {
3362 return res;
3363 }
3364 Py_DECREF(res);
3365 }
3366 Py_INCREF(Py_NotImplemented);
3367 return Py_NotImplemented;
3368}
3369
3370static PyObject *
3371slot_tp_iter(PyObject *self)
3372{
3373 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003374 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003375
Guido van Rossum60718732001-08-28 17:47:51 +00003376 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003377 if (func != NULL) {
3378 res = PyObject_CallObject(func, NULL);
3379 Py_DECREF(func);
3380 return res;
3381 }
3382 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003383 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003384 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003385 PyErr_SetString(PyExc_TypeError,
3386 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003387 return NULL;
3388 }
3389 Py_DECREF(func);
3390 return PySeqIter_New(self);
3391}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003392
3393static PyObject *
3394slot_tp_iternext(PyObject *self)
3395{
Guido van Rossum2730b132001-08-28 18:22:14 +00003396 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003397 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003398}
3399
Guido van Rossum1a493502001-08-17 16:47:50 +00003400static PyObject *
3401slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3402{
3403 PyTypeObject *tp = self->ob_type;
3404 PyObject *get;
3405 static PyObject *get_str = NULL;
3406
3407 if (get_str == NULL) {
3408 get_str = PyString_InternFromString("__get__");
3409 if (get_str == NULL)
3410 return NULL;
3411 }
3412 get = _PyType_Lookup(tp, get_str);
3413 if (get == NULL) {
3414 /* Avoid further slowdowns */
3415 if (tp->tp_descr_get == slot_tp_descr_get)
3416 tp->tp_descr_get = NULL;
3417 Py_INCREF(self);
3418 return self;
3419 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003420 if (obj == NULL)
3421 obj = Py_None;
3422 if (type == NULL)
3423 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003424 return PyObject_CallFunction(get, "OOO", self, obj, type);
3425}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426
3427static int
3428slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3429{
Guido van Rossum2c252392001-08-24 10:13:31 +00003430 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003431 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003432
3433 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003434 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003435 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003436 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003437 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003438 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439 if (res == NULL)
3440 return -1;
3441 Py_DECREF(res);
3442 return 0;
3443}
3444
3445static int
3446slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3447{
Guido van Rossum60718732001-08-28 17:47:51 +00003448 static PyObject *init_str;
3449 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450 PyObject *res;
3451
3452 if (meth == NULL)
3453 return -1;
3454 res = PyObject_Call(meth, args, kwds);
3455 Py_DECREF(meth);
3456 if (res == NULL)
3457 return -1;
3458 Py_DECREF(res);
3459 return 0;
3460}
3461
3462static PyObject *
3463slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3464{
3465 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3466 PyObject *newargs, *x;
3467 int i, n;
3468
3469 if (func == NULL)
3470 return NULL;
3471 assert(PyTuple_Check(args));
3472 n = PyTuple_GET_SIZE(args);
3473 newargs = PyTuple_New(n+1);
3474 if (newargs == NULL)
3475 return NULL;
3476 Py_INCREF(type);
3477 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3478 for (i = 0; i < n; i++) {
3479 x = PyTuple_GET_ITEM(args, i);
3480 Py_INCREF(x);
3481 PyTuple_SET_ITEM(newargs, i+1, x);
3482 }
3483 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003484 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485 Py_DECREF(func);
3486 return x;
3487}
3488
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003489
3490/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3491 functions. The offsets here are relative to the 'etype' structure, which
3492 incorporates the additional structures used for numbers, sequences and
3493 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3494 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003495 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3496 terminated with an all-zero entry. (This table is further initialized and
3497 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003498
Guido van Rossum6d204072001-10-21 00:44:31 +00003499typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003500
3501#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003502#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003503#undef ETSLOT
3504#undef SQSLOT
3505#undef MPSLOT
3506#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003507#undef UNSLOT
3508#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003509#undef BINSLOT
3510#undef RBINSLOT
3511
Guido van Rossum6d204072001-10-21 00:44:31 +00003512#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3513 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003514#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3515 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3516 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003517#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3518 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3519#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3520 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3521#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3522 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3523#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3524 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3525#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3526 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3527 "x." NAME "() <==> " DOC)
3528#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3529 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3530 "x." NAME "(y) <==> x" DOC "y")
3531#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3532 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3533 "x." NAME "(y) <==> x" DOC "y")
3534#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3535 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3536 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003537
3538static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003539 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3540 "x.__len__() <==> len(x)"),
3541 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3542 "x.__add__(y) <==> x+y"),
3543 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3544 "x.__mul__(n) <==> x*n"),
3545 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3546 "x.__rmul__(n) <==> n*x"),
3547 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3548 "x.__getitem__(y) <==> x[y]"),
3549 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3550 "x.__getslice__(i, j) <==> x[i:j]"),
3551 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3552 "x.__setitem__(i, y) <==> x[i]=y"),
3553 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3554 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003555 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003556 wrap_intintobjargproc,
3557 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3558 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3559 "x.__delslice__(i, j) <==> del x[i:j]"),
3560 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3561 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003562 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003563 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003564 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003565 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003566
Guido van Rossum6d204072001-10-21 00:44:31 +00003567 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3568 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003569 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003570 wrap_binaryfunc,
3571 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003572 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003573 wrap_objobjargproc,
3574 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003575 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003576 wrap_delitem,
3577 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003578
Guido van Rossum6d204072001-10-21 00:44:31 +00003579 BINSLOT("__add__", nb_add, slot_nb_add,
3580 "+"),
3581 RBINSLOT("__radd__", nb_add, slot_nb_add,
3582 "+"),
3583 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3584 "-"),
3585 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3586 "-"),
3587 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3588 "*"),
3589 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3590 "*"),
3591 BINSLOT("__div__", nb_divide, slot_nb_divide,
3592 "/"),
3593 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3594 "/"),
3595 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3596 "%"),
3597 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3598 "%"),
3599 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3600 "divmod(x, y)"),
3601 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3602 "divmod(y, x)"),
3603 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3604 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3605 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3606 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3607 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3608 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3609 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3610 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003611 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003612 "x != 0"),
3613 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3614 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3615 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3616 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3617 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3618 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3619 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3620 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3621 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3622 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3623 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3624 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3625 "x.__coerce__(y) <==> coerce(x, y)"),
3626 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3627 "int(x)"),
3628 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3629 "long(x)"),
3630 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3631 "float(x)"),
3632 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3633 "oct(x)"),
3634 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3635 "hex(x)"),
3636 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3637 wrap_binaryfunc, "+"),
3638 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3639 wrap_binaryfunc, "-"),
3640 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3641 wrap_binaryfunc, "*"),
3642 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3643 wrap_binaryfunc, "/"),
3644 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3645 wrap_binaryfunc, "%"),
3646 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3647 wrap_ternaryfunc, "**"),
3648 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3649 wrap_binaryfunc, "<<"),
3650 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3651 wrap_binaryfunc, ">>"),
3652 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3653 wrap_binaryfunc, "&"),
3654 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3655 wrap_binaryfunc, "^"),
3656 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3657 wrap_binaryfunc, "|"),
3658 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3659 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3660 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3661 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3662 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3663 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3664 IBSLOT("__itruediv__", nb_inplace_true_divide,
3665 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003666
Guido van Rossum6d204072001-10-21 00:44:31 +00003667 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3668 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003669 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003670 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3671 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003672 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003673 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3674 "x.__cmp__(y) <==> cmp(x,y)"),
3675 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3676 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003677 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3678 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003679 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003680 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3681 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3682 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3683 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3684 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3685 "x.__setattr__('name', value) <==> x.name = value"),
3686 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3687 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3688 "x.__delattr__('name') <==> del x.name"),
3689 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3690 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3691 "x.__lt__(y) <==> x<y"),
3692 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3693 "x.__le__(y) <==> x<=y"),
3694 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3695 "x.__eq__(y) <==> x==y"),
3696 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3697 "x.__ne__(y) <==> x!=y"),
3698 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3699 "x.__gt__(y) <==> x>y"),
3700 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3701 "x.__ge__(y) <==> x>=y"),
3702 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3703 "x.__iter__() <==> iter(x)"),
3704 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3705 "x.next() -> the next value, or raise StopIteration"),
3706 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3707 "descr.__get__(obj[, type]) -> value"),
3708 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3709 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003710 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003711 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003712 "see x.__class__.__doc__ for signature",
3713 PyWrapperFlag_KEYWORDS),
3714 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003715 {NULL}
3716};
3717
Guido van Rossumc334df52002-04-04 23:44:47 +00003718/* Given a type pointer and an offset gotten from a slotdef entry, return a
3719 pointer to the actual slot. This is not quite the same as simply adding
3720 the offset to the type pointer, since it takes care to indirect through the
3721 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3722 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003723static void **
3724slotptr(PyTypeObject *type, int offset)
3725{
3726 char *ptr;
3727
3728 assert(offset >= 0);
3729 assert(offset < offsetof(etype, as_buffer));
3730 if (offset >= offsetof(etype, as_mapping)) {
3731 ptr = (void *)type->tp_as_mapping;
3732 offset -= offsetof(etype, as_mapping);
3733 }
3734 else if (offset >= offsetof(etype, as_sequence)) {
3735 ptr = (void *)type->tp_as_sequence;
3736 offset -= offsetof(etype, as_sequence);
3737 }
3738 else if (offset >= offsetof(etype, as_number)) {
3739 ptr = (void *)type->tp_as_number;
3740 offset -= offsetof(etype, as_number);
3741 }
3742 else {
3743 ptr = (void *)type;
3744 }
3745 if (ptr != NULL)
3746 ptr += offset;
3747 return (void **)ptr;
3748}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003749
Guido van Rossumc334df52002-04-04 23:44:47 +00003750/* Length of array of slotdef pointers used to store slots with the
3751 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3752 the same __name__, for any __name__. Since that's a static property, it is
3753 appropriate to declare fixed-size arrays for this. */
3754#define MAX_EQUIV 10
3755
3756/* Return a slot pointer for a given name, but ONLY if the attribute has
3757 exactly one slot function. The name must be an interned string. */
3758static void **
3759resolve_slotdups(PyTypeObject *type, PyObject *name)
3760{
3761 /* XXX Maybe this could be optimized more -- but is it worth it? */
3762
3763 /* pname and ptrs act as a little cache */
3764 static PyObject *pname;
3765 static slotdef *ptrs[MAX_EQUIV];
3766 slotdef *p, **pp;
3767 void **res, **ptr;
3768
3769 if (pname != name) {
3770 /* Collect all slotdefs that match name into ptrs. */
3771 pname = name;
3772 pp = ptrs;
3773 for (p = slotdefs; p->name_strobj; p++) {
3774 if (p->name_strobj == name)
3775 *pp++ = p;
3776 }
3777 *pp = NULL;
3778 }
3779
3780 /* Look in all matching slots of the type; if exactly one of these has
3781 a filled-in slot, return its value. Otherwise return NULL. */
3782 res = NULL;
3783 for (pp = ptrs; *pp; pp++) {
3784 ptr = slotptr(type, (*pp)->offset);
3785 if (ptr == NULL || *ptr == NULL)
3786 continue;
3787 if (res != NULL)
3788 return NULL;
3789 res = ptr;
3790 }
3791 return res;
3792}
3793
3794/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3795 does some incredibly complex thinking and then sticks something into the
3796 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3797 interests, and then stores a generic wrapper or a specific function into
3798 the slot.) Return a pointer to the next slotdef with a different offset,
3799 because that's convenient for fixup_slot_dispatchers(). */
3800static slotdef *
3801update_one_slot(PyTypeObject *type, slotdef *p)
3802{
3803 PyObject *descr;
3804 PyWrapperDescrObject *d;
3805 void *generic = NULL, *specific = NULL;
3806 int use_generic = 0;
3807 int offset = p->offset;
3808 void **ptr = slotptr(type, offset);
3809
3810 if (ptr == NULL) {
3811 do {
3812 ++p;
3813 } while (p->offset == offset);
3814 return p;
3815 }
3816 do {
3817 descr = _PyType_Lookup(type, p->name_strobj);
3818 if (descr == NULL)
3819 continue;
3820 if (descr->ob_type == &PyWrapperDescr_Type) {
3821 void **tptr = resolve_slotdups(type, p->name_strobj);
3822 if (tptr == NULL || tptr == ptr)
3823 generic = p->function;
3824 d = (PyWrapperDescrObject *)descr;
3825 if (d->d_base->wrapper == p->wrapper &&
3826 PyType_IsSubtype(type, d->d_type))
3827 {
3828 if (specific == NULL ||
3829 specific == d->d_wrapped)
3830 specific = d->d_wrapped;
3831 else
3832 use_generic = 1;
3833 }
3834 }
3835 else {
3836 use_generic = 1;
3837 generic = p->function;
3838 }
3839 } while ((++p)->offset == offset);
3840 if (specific && !use_generic)
3841 *ptr = specific;
3842 else
3843 *ptr = generic;
3844 return p;
3845}
3846
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003847staticforward int recurse_down_subclasses(PyTypeObject *type,
3848 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003849
Guido van Rossumc334df52002-04-04 23:44:47 +00003850/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3851 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003852static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003853update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003854{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003855 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003856
Guido van Rossumc334df52002-04-04 23:44:47 +00003857 for (pp = pp0; *pp; pp++)
3858 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003859 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003860}
3861
Guido van Rossumc334df52002-04-04 23:44:47 +00003862/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3863 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003864static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003865recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003866{
3867 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003868 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003869 int i, n;
3870
3871 subclasses = type->tp_subclasses;
3872 if (subclasses == NULL)
3873 return 0;
3874 assert(PyList_Check(subclasses));
3875 n = PyList_GET_SIZE(subclasses);
3876 for (i = 0; i < n; i++) {
3877 ref = PyList_GET_ITEM(subclasses, i);
3878 assert(PyWeakref_CheckRef(ref));
3879 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3880 if (subclass == NULL)
3881 continue;
3882 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003883 /* Avoid recursing down into unaffected classes */
3884 dict = subclass->tp_dict;
3885 if (dict != NULL && PyDict_Check(dict) &&
3886 PyDict_GetItem(dict, name) != NULL)
3887 continue;
3888 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003889 return -1;
3890 }
3891 return 0;
3892}
3893
Guido van Rossumc334df52002-04-04 23:44:47 +00003894/* Comparison function for qsort() to compare slotdefs by their offset, and
3895 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003896static int
3897slotdef_cmp(const void *aa, const void *bb)
3898{
3899 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3900 int c = a->offset - b->offset;
3901 if (c != 0)
3902 return c;
3903 else
3904 return a - b;
3905}
3906
Guido van Rossumc334df52002-04-04 23:44:47 +00003907/* Initialize the slotdefs table by adding interned string objects for the
3908 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003909static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003910init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003911{
3912 slotdef *p;
3913 static int initialized = 0;
3914
3915 if (initialized)
3916 return;
3917 for (p = slotdefs; p->name; p++) {
3918 p->name_strobj = PyString_InternFromString(p->name);
3919 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00003920 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003921 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003922 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3923 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003924 initialized = 1;
3925}
3926
Guido van Rossumc334df52002-04-04 23:44:47 +00003927/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003928static int
3929update_slot(PyTypeObject *type, PyObject *name)
3930{
Guido van Rossumc334df52002-04-04 23:44:47 +00003931 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003932 slotdef *p;
3933 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003934 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003935
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003936 init_slotdefs();
3937 pp = ptrs;
3938 for (p = slotdefs; p->name; p++) {
3939 /* XXX assume name is interned! */
3940 if (p->name_strobj == name)
3941 *pp++ = p;
3942 }
3943 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003944 for (pp = ptrs; *pp; pp++) {
3945 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003946 offset = p->offset;
3947 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003948 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003949 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003950 }
Guido van Rossumc334df52002-04-04 23:44:47 +00003951 if (ptrs[0] == NULL)
3952 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003953 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003954}
3955
Guido van Rossumc334df52002-04-04 23:44:47 +00003956/* Store the proper functions in the slot dispatches at class (type)
3957 definition time, based upon which operations the class overrides in its
3958 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003959static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003960fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003962 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003963
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003964 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00003965 for (p = slotdefs; p->name; )
3966 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003968
Guido van Rossum6d204072001-10-21 00:44:31 +00003969/* This function is called by PyType_Ready() to populate the type's
3970 dictionary with method descriptors for function slots. For each
3971 function slot (like tp_repr) that's defined in the type, one or
3972 more corresponding descriptors are added in the type's tp_dict
3973 dictionary under the appropriate name (like __repr__). Some
3974 function slots cause more than one descriptor to be added (for
3975 example, the nb_add slot adds both __add__ and __radd__
3976 descriptors) and some function slots compete for the same
3977 descriptor (for example both sq_item and mp_subscript generate a
3978 __getitem__ descriptor). This only adds new descriptors and
3979 doesn't overwrite entries in tp_dict that were previously
3980 defined. The descriptors contain a reference to the C function
3981 they must call, so that it's safe if they are copied into a
3982 subtype's __dict__ and the subtype has a different C function in
3983 its slot -- calling the method defined by the descriptor will call
3984 the C function that was used to create it, rather than the C
3985 function present in the slot when it is called. (This is important
3986 because a subtype may have a C function in the slot that calls the
3987 method from the dictionary, and we want to avoid infinite recursion
3988 here.) */
3989
3990static int
3991add_operators(PyTypeObject *type)
3992{
3993 PyObject *dict = type->tp_dict;
3994 slotdef *p;
3995 PyObject *descr;
3996 void **ptr;
3997
3998 init_slotdefs();
3999 for (p = slotdefs; p->name; p++) {
4000 if (p->wrapper == NULL)
4001 continue;
4002 ptr = slotptr(type, p->offset);
4003 if (!ptr || !*ptr)
4004 continue;
4005 if (PyDict_GetItem(dict, p->name_strobj))
4006 continue;
4007 descr = PyDescr_NewWrapper(type, p, *ptr);
4008 if (descr == NULL)
4009 return -1;
4010 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4011 return -1;
4012 Py_DECREF(descr);
4013 }
4014 if (type->tp_new != NULL) {
4015 if (add_tp_new_wrapper(type) < 0)
4016 return -1;
4017 }
4018 return 0;
4019}
4020
Guido van Rossum705f0f52001-08-24 16:47:00 +00004021
4022/* Cooperative 'super' */
4023
4024typedef struct {
4025 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004026 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004027 PyObject *obj;
4028} superobject;
4029
Guido van Rossum6f799372001-09-20 20:46:19 +00004030static PyMemberDef super_members[] = {
4031 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4032 "the class invoking super()"},
4033 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4034 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004035 {0}
4036};
4037
Guido van Rossum705f0f52001-08-24 16:47:00 +00004038static void
4039super_dealloc(PyObject *self)
4040{
4041 superobject *su = (superobject *)self;
4042
Guido van Rossum048eb752001-10-02 21:24:57 +00004043 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004044 Py_XDECREF(su->obj);
4045 Py_XDECREF(su->type);
4046 self->ob_type->tp_free(self);
4047}
4048
4049static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004050super_repr(PyObject *self)
4051{
4052 superobject *su = (superobject *)self;
4053
4054 if (su->obj)
4055 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004056 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004057 su->type ? su->type->tp_name : "NULL",
4058 su->obj->ob_type->tp_name);
4059 else
4060 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004061 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004062 su->type ? su->type->tp_name : "NULL");
4063}
4064
4065static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004066super_getattro(PyObject *self, PyObject *name)
4067{
4068 superobject *su = (superobject *)self;
4069
4070 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004071 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004072 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004073 descrgetfunc f;
4074 int i, n;
4075
Guido van Rossum155db9a2002-04-02 17:53:47 +00004076 starttype = su->obj->ob_type;
4077 mro = starttype->tp_mro;
4078
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004079 if (mro == NULL)
4080 n = 0;
4081 else {
4082 assert(PyTuple_Check(mro));
4083 n = PyTuple_GET_SIZE(mro);
4084 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004085 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004086 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004087 break;
4088 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004089 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004090 starttype = (PyTypeObject *)(su->obj);
4091 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004092 if (mro == NULL)
4093 n = 0;
4094 else {
4095 assert(PyTuple_Check(mro));
4096 n = PyTuple_GET_SIZE(mro);
4097 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004098 for (i = 0; i < n; i++) {
4099 if ((PyObject *)(su->type) ==
4100 PyTuple_GET_ITEM(mro, i))
4101 break;
4102 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004103 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004104 i++;
4105 res = NULL;
4106 for (; i < n; i++) {
4107 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004108 if (PyType_Check(tmp))
4109 dict = ((PyTypeObject *)tmp)->tp_dict;
4110 else if (PyClass_Check(tmp))
4111 dict = ((PyClassObject *)tmp)->cl_dict;
4112 else
4113 continue;
4114 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004115 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004116 Py_INCREF(res);
4117 f = res->ob_type->tp_descr_get;
4118 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004119 tmp = f(res, su->obj,
4120 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004121 Py_DECREF(res);
4122 res = tmp;
4123 }
4124 return res;
4125 }
4126 }
4127 }
4128 return PyObject_GenericGetAttr(self, name);
4129}
4130
Guido van Rossum5b443c62001-12-03 15:38:28 +00004131static int
4132supercheck(PyTypeObject *type, PyObject *obj)
4133{
4134 if (!PyType_IsSubtype(obj->ob_type, type) &&
4135 !(PyType_Check(obj) &&
4136 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4137 PyErr_SetString(PyExc_TypeError,
4138 "super(type, obj): "
4139 "obj must be an instance or subtype of type");
4140 return -1;
4141 }
4142 else
4143 return 0;
4144}
4145
Guido van Rossum705f0f52001-08-24 16:47:00 +00004146static PyObject *
4147super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4148{
4149 superobject *su = (superobject *)self;
4150 superobject *new;
4151
4152 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4153 /* Not binding to an object, or already bound */
4154 Py_INCREF(self);
4155 return self;
4156 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004157 if (su->ob_type != &PySuper_Type)
4158 /* If su is an instance of a subclass of super,
4159 call its type */
4160 return PyObject_CallFunction((PyObject *)su->ob_type,
4161 "OO", su->type, obj);
4162 else {
4163 /* Inline the common case */
4164 if (supercheck(su->type, obj) < 0)
4165 return NULL;
4166 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4167 NULL, NULL);
4168 if (new == NULL)
4169 return NULL;
4170 Py_INCREF(su->type);
4171 Py_INCREF(obj);
4172 new->type = su->type;
4173 new->obj = obj;
4174 return (PyObject *)new;
4175 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004176}
4177
4178static int
4179super_init(PyObject *self, PyObject *args, PyObject *kwds)
4180{
4181 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004182 PyTypeObject *type;
4183 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004184
4185 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4186 return -1;
4187 if (obj == Py_None)
4188 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004189 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004190 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004191 Py_INCREF(type);
4192 Py_XINCREF(obj);
4193 su->type = type;
4194 su->obj = obj;
4195 return 0;
4196}
4197
4198static char super_doc[] =
4199"super(type) -> unbound super object\n"
4200"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004201"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004202"Typical use to call a cooperative superclass method:\n"
4203"class C(B):\n"
4204" def meth(self, arg):\n"
4205" super(C, self).meth(arg)";
4206
Guido van Rossum048eb752001-10-02 21:24:57 +00004207static int
4208super_traverse(PyObject *self, visitproc visit, void *arg)
4209{
4210 superobject *su = (superobject *)self;
4211 int err;
4212
4213#define VISIT(SLOT) \
4214 if (SLOT) { \
4215 err = visit((PyObject *)(SLOT), arg); \
4216 if (err) \
4217 return err; \
4218 }
4219
4220 VISIT(su->obj);
4221 VISIT(su->type);
4222
4223#undef VISIT
4224
4225 return 0;
4226}
4227
Guido van Rossum705f0f52001-08-24 16:47:00 +00004228PyTypeObject PySuper_Type = {
4229 PyObject_HEAD_INIT(&PyType_Type)
4230 0, /* ob_size */
4231 "super", /* tp_name */
4232 sizeof(superobject), /* tp_basicsize */
4233 0, /* tp_itemsize */
4234 /* methods */
4235 super_dealloc, /* tp_dealloc */
4236 0, /* tp_print */
4237 0, /* tp_getattr */
4238 0, /* tp_setattr */
4239 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004240 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004241 0, /* tp_as_number */
4242 0, /* tp_as_sequence */
4243 0, /* tp_as_mapping */
4244 0, /* tp_hash */
4245 0, /* tp_call */
4246 0, /* tp_str */
4247 super_getattro, /* tp_getattro */
4248 0, /* tp_setattro */
4249 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004250 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4251 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004252 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004253 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004254 0, /* tp_clear */
4255 0, /* tp_richcompare */
4256 0, /* tp_weaklistoffset */
4257 0, /* tp_iter */
4258 0, /* tp_iternext */
4259 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004260 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004261 0, /* tp_getset */
4262 0, /* tp_base */
4263 0, /* tp_dict */
4264 super_descr_get, /* tp_descr_get */
4265 0, /* tp_descr_set */
4266 0, /* tp_dictoffset */
4267 super_init, /* tp_init */
4268 PyType_GenericAlloc, /* tp_alloc */
4269 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004270 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004271};