blob: 71d22f3534d1a25a1caa9ed5a683f78ae8fb765f [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);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002027 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002028 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029}
2030
Guido van Rossum13d52f02001-08-10 21:24:08 +00002031staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002032staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002033
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002035PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002037 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038 PyTypeObject *base;
2039 int i, n;
2040
Guido van Rossumd614f972001-08-10 17:39:49 +00002041 if (type->tp_flags & Py_TPFLAGS_READY) {
2042 assert(type->tp_dict != NULL);
2043 return 0;
2044 }
2045 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002046
2047 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048
Guido van Rossumf884b742001-12-17 17:14:22 +00002049 /* Initialize ob_type if NULL. This means extensions that want to be
2050 compilable separately on Windows can call PyType_Ready() instead of
2051 initializing the ob_type field of their type objects. */
2052 if (type->ob_type == NULL)
2053 type->ob_type = &PyType_Type;
2054
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2056 base = type->tp_base;
2057 if (base == NULL && type != &PyBaseObject_Type)
2058 base = type->tp_base = &PyBaseObject_Type;
2059
2060 /* Initialize tp_bases */
2061 bases = type->tp_bases;
2062 if (bases == NULL) {
2063 if (base == NULL)
2064 bases = PyTuple_New(0);
2065 else
2066 bases = Py_BuildValue("(O)", base);
2067 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002068 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002069 type->tp_bases = bases;
2070 }
2071
2072 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002073 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002074 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002075 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002076 }
2077
Guido van Rossum687ae002001-10-15 22:03:32 +00002078 /* Initialize tp_dict */
2079 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002080 if (dict == NULL) {
2081 dict = PyDict_New();
2082 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002083 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002084 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002085 }
2086
Guido van Rossum687ae002001-10-15 22:03:32 +00002087 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002088 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002089 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002090 if (type->tp_methods != NULL) {
2091 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002092 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002093 }
2094 if (type->tp_members != NULL) {
2095 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002096 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 }
2098 if (type->tp_getset != NULL) {
2099 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002100 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 }
2102
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103 /* Calculate method resolution order */
2104 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002105 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 }
2107
Guido van Rossum13d52f02001-08-10 21:24:08 +00002108 /* Inherit special flags from dominant base */
2109 if (type->tp_base != NULL)
2110 inherit_special(type, type->tp_base);
2111
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002113 bases = type->tp_mro;
2114 assert(bases != NULL);
2115 assert(PyTuple_Check(bases));
2116 n = PyTuple_GET_SIZE(bases);
2117 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002118 PyObject *b = PyTuple_GET_ITEM(bases, i);
2119 if (PyType_Check(b))
2120 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002121 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002123 /* if the type dictionary doesn't contain a __doc__, set it from
2124 the tp_doc slot.
2125 */
2126 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2127 if (type->tp_doc != NULL) {
2128 PyObject *doc = PyString_FromString(type->tp_doc);
2129 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2130 Py_DECREF(doc);
2131 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002132 PyDict_SetItemString(type->tp_dict,
2133 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002134 }
2135 }
2136
Guido van Rossum13d52f02001-08-10 21:24:08 +00002137 /* Some more special stuff */
2138 base = type->tp_base;
2139 if (base != NULL) {
2140 if (type->tp_as_number == NULL)
2141 type->tp_as_number = base->tp_as_number;
2142 if (type->tp_as_sequence == NULL)
2143 type->tp_as_sequence = base->tp_as_sequence;
2144 if (type->tp_as_mapping == NULL)
2145 type->tp_as_mapping = base->tp_as_mapping;
2146 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002147
Guido van Rossum1c450732001-10-08 15:18:27 +00002148 /* Link into each base class's list of subclasses */
2149 bases = type->tp_bases;
2150 n = PyTuple_GET_SIZE(bases);
2151 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002152 PyObject *b = PyTuple_GET_ITEM(bases, i);
2153 if (PyType_Check(b) &&
2154 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002155 goto error;
2156 }
2157
Guido van Rossum13d52f02001-08-10 21:24:08 +00002158 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002159 assert(type->tp_dict != NULL);
2160 type->tp_flags =
2161 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002163
2164 error:
2165 type->tp_flags &= ~Py_TPFLAGS_READYING;
2166 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002167}
2168
Guido van Rossum1c450732001-10-08 15:18:27 +00002169static int
2170add_subclass(PyTypeObject *base, PyTypeObject *type)
2171{
2172 int i;
2173 PyObject *list, *ref, *new;
2174
2175 list = base->tp_subclasses;
2176 if (list == NULL) {
2177 base->tp_subclasses = list = PyList_New(0);
2178 if (list == NULL)
2179 return -1;
2180 }
2181 assert(PyList_Check(list));
2182 new = PyWeakref_NewRef((PyObject *)type, NULL);
2183 i = PyList_GET_SIZE(list);
2184 while (--i >= 0) {
2185 ref = PyList_GET_ITEM(list, i);
2186 assert(PyWeakref_CheckRef(ref));
2187 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2188 return PyList_SetItem(list, i, new);
2189 }
2190 i = PyList_Append(list, new);
2191 Py_DECREF(new);
2192 return i;
2193}
2194
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195
2196/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2197
2198/* There's a wrapper *function* for each distinct function typedef used
2199 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2200 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2201 Most tables have only one entry; the tables for binary operators have two
2202 entries, one regular and one with reversed arguments. */
2203
2204static PyObject *
2205wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2206{
2207 inquiry func = (inquiry)wrapped;
2208 int res;
2209
2210 if (!PyArg_ParseTuple(args, ""))
2211 return NULL;
2212 res = (*func)(self);
2213 if (res == -1 && PyErr_Occurred())
2214 return NULL;
2215 return PyInt_FromLong((long)res);
2216}
2217
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218static PyObject *
2219wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2220{
2221 binaryfunc func = (binaryfunc)wrapped;
2222 PyObject *other;
2223
2224 if (!PyArg_ParseTuple(args, "O", &other))
2225 return NULL;
2226 return (*func)(self, other);
2227}
2228
2229static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002230wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2231{
2232 binaryfunc func = (binaryfunc)wrapped;
2233 PyObject *other;
2234
2235 if (!PyArg_ParseTuple(args, "O", &other))
2236 return NULL;
2237 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002238 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002239 Py_INCREF(Py_NotImplemented);
2240 return Py_NotImplemented;
2241 }
2242 return (*func)(self, other);
2243}
2244
2245static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2247{
2248 binaryfunc func = (binaryfunc)wrapped;
2249 PyObject *other;
2250
2251 if (!PyArg_ParseTuple(args, "O", &other))
2252 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002253 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002254 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002255 Py_INCREF(Py_NotImplemented);
2256 return Py_NotImplemented;
2257 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258 return (*func)(other, self);
2259}
2260
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002261static PyObject *
2262wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2263{
2264 coercion func = (coercion)wrapped;
2265 PyObject *other, *res;
2266 int ok;
2267
2268 if (!PyArg_ParseTuple(args, "O", &other))
2269 return NULL;
2270 ok = func(&self, &other);
2271 if (ok < 0)
2272 return NULL;
2273 if (ok > 0) {
2274 Py_INCREF(Py_NotImplemented);
2275 return Py_NotImplemented;
2276 }
2277 res = PyTuple_New(2);
2278 if (res == NULL) {
2279 Py_DECREF(self);
2280 Py_DECREF(other);
2281 return NULL;
2282 }
2283 PyTuple_SET_ITEM(res, 0, self);
2284 PyTuple_SET_ITEM(res, 1, other);
2285 return res;
2286}
2287
Tim Peters6d6c1a32001-08-02 04:15:00 +00002288static PyObject *
2289wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2290{
2291 ternaryfunc func = (ternaryfunc)wrapped;
2292 PyObject *other;
2293 PyObject *third = Py_None;
2294
2295 /* Note: This wrapper only works for __pow__() */
2296
2297 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2298 return NULL;
2299 return (*func)(self, other, third);
2300}
2301
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002302static PyObject *
2303wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2304{
2305 ternaryfunc func = (ternaryfunc)wrapped;
2306 PyObject *other;
2307 PyObject *third = Py_None;
2308
2309 /* Note: This wrapper only works for __pow__() */
2310
2311 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2312 return NULL;
2313 return (*func)(other, self, third);
2314}
2315
Tim Peters6d6c1a32001-08-02 04:15:00 +00002316static PyObject *
2317wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2318{
2319 unaryfunc func = (unaryfunc)wrapped;
2320
2321 if (!PyArg_ParseTuple(args, ""))
2322 return NULL;
2323 return (*func)(self);
2324}
2325
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326static PyObject *
2327wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2328{
2329 intargfunc func = (intargfunc)wrapped;
2330 int i;
2331
2332 if (!PyArg_ParseTuple(args, "i", &i))
2333 return NULL;
2334 return (*func)(self, i);
2335}
2336
Guido van Rossum5d815f32001-08-17 21:57:47 +00002337static int
2338getindex(PyObject *self, PyObject *arg)
2339{
2340 int i;
2341
2342 i = PyInt_AsLong(arg);
2343 if (i == -1 && PyErr_Occurred())
2344 return -1;
2345 if (i < 0) {
2346 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2347 if (sq && sq->sq_length) {
2348 int n = (*sq->sq_length)(self);
2349 if (n < 0)
2350 return -1;
2351 i += n;
2352 }
2353 }
2354 return i;
2355}
2356
2357static PyObject *
2358wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2359{
2360 intargfunc func = (intargfunc)wrapped;
2361 PyObject *arg;
2362 int i;
2363
Guido van Rossumf4593e02001-10-03 12:09:30 +00002364 if (PyTuple_GET_SIZE(args) == 1) {
2365 arg = PyTuple_GET_ITEM(args, 0);
2366 i = getindex(self, arg);
2367 if (i == -1 && PyErr_Occurred())
2368 return NULL;
2369 return (*func)(self, i);
2370 }
2371 PyArg_ParseTuple(args, "O", &arg);
2372 assert(PyErr_Occurred());
2373 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002374}
2375
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376static PyObject *
2377wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2378{
2379 intintargfunc func = (intintargfunc)wrapped;
2380 int i, j;
2381
2382 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2383 return NULL;
2384 return (*func)(self, i, j);
2385}
2386
Tim Peters6d6c1a32001-08-02 04:15:00 +00002387static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002388wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389{
2390 intobjargproc func = (intobjargproc)wrapped;
2391 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002392 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393
Guido van Rossum5d815f32001-08-17 21:57:47 +00002394 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2395 return NULL;
2396 i = getindex(self, arg);
2397 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398 return NULL;
2399 res = (*func)(self, i, value);
2400 if (res == -1 && PyErr_Occurred())
2401 return NULL;
2402 Py_INCREF(Py_None);
2403 return Py_None;
2404}
2405
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002406static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002407wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002408{
2409 intobjargproc func = (intobjargproc)wrapped;
2410 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002411 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002412
Guido van Rossum5d815f32001-08-17 21:57:47 +00002413 if (!PyArg_ParseTuple(args, "O", &arg))
2414 return NULL;
2415 i = getindex(self, arg);
2416 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002417 return NULL;
2418 res = (*func)(self, i, NULL);
2419 if (res == -1 && PyErr_Occurred())
2420 return NULL;
2421 Py_INCREF(Py_None);
2422 return Py_None;
2423}
2424
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425static PyObject *
2426wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2427{
2428 intintobjargproc func = (intintobjargproc)wrapped;
2429 int i, j, res;
2430 PyObject *value;
2431
2432 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2433 return NULL;
2434 res = (*func)(self, i, j, value);
2435 if (res == -1 && PyErr_Occurred())
2436 return NULL;
2437 Py_INCREF(Py_None);
2438 return Py_None;
2439}
2440
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002441static PyObject *
2442wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2443{
2444 intintobjargproc func = (intintobjargproc)wrapped;
2445 int i, j, res;
2446
2447 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2448 return NULL;
2449 res = (*func)(self, i, j, NULL);
2450 if (res == -1 && PyErr_Occurred())
2451 return NULL;
2452 Py_INCREF(Py_None);
2453 return Py_None;
2454}
2455
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456/* XXX objobjproc is a misnomer; should be objargpred */
2457static PyObject *
2458wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2459{
2460 objobjproc func = (objobjproc)wrapped;
2461 int res;
2462 PyObject *value;
2463
2464 if (!PyArg_ParseTuple(args, "O", &value))
2465 return NULL;
2466 res = (*func)(self, value);
2467 if (res == -1 && PyErr_Occurred())
2468 return NULL;
2469 return PyInt_FromLong((long)res);
2470}
2471
Tim Peters6d6c1a32001-08-02 04:15:00 +00002472static PyObject *
2473wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2474{
2475 objobjargproc func = (objobjargproc)wrapped;
2476 int res;
2477 PyObject *key, *value;
2478
2479 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2480 return NULL;
2481 res = (*func)(self, key, value);
2482 if (res == -1 && PyErr_Occurred())
2483 return NULL;
2484 Py_INCREF(Py_None);
2485 return Py_None;
2486}
2487
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002488static PyObject *
2489wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2490{
2491 objobjargproc func = (objobjargproc)wrapped;
2492 int res;
2493 PyObject *key;
2494
2495 if (!PyArg_ParseTuple(args, "O", &key))
2496 return NULL;
2497 res = (*func)(self, key, NULL);
2498 if (res == -1 && PyErr_Occurred())
2499 return NULL;
2500 Py_INCREF(Py_None);
2501 return Py_None;
2502}
2503
Tim Peters6d6c1a32001-08-02 04:15:00 +00002504static PyObject *
2505wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2506{
2507 cmpfunc func = (cmpfunc)wrapped;
2508 int res;
2509 PyObject *other;
2510
2511 if (!PyArg_ParseTuple(args, "O", &other))
2512 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002513 if (other->ob_type->tp_compare != func &&
2514 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002515 PyErr_Format(
2516 PyExc_TypeError,
2517 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2518 self->ob_type->tp_name,
2519 self->ob_type->tp_name,
2520 other->ob_type->tp_name);
2521 return NULL;
2522 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002523 res = (*func)(self, other);
2524 if (PyErr_Occurred())
2525 return NULL;
2526 return PyInt_FromLong((long)res);
2527}
2528
Tim Peters6d6c1a32001-08-02 04:15:00 +00002529static PyObject *
2530wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2531{
2532 setattrofunc func = (setattrofunc)wrapped;
2533 int res;
2534 PyObject *name, *value;
2535
2536 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2537 return NULL;
2538 res = (*func)(self, name, value);
2539 if (res < 0)
2540 return NULL;
2541 Py_INCREF(Py_None);
2542 return Py_None;
2543}
2544
2545static PyObject *
2546wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2547{
2548 setattrofunc func = (setattrofunc)wrapped;
2549 int res;
2550 PyObject *name;
2551
2552 if (!PyArg_ParseTuple(args, "O", &name))
2553 return NULL;
2554 res = (*func)(self, name, NULL);
2555 if (res < 0)
2556 return NULL;
2557 Py_INCREF(Py_None);
2558 return Py_None;
2559}
2560
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561static PyObject *
2562wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2563{
2564 hashfunc func = (hashfunc)wrapped;
2565 long res;
2566
2567 if (!PyArg_ParseTuple(args, ""))
2568 return NULL;
2569 res = (*func)(self);
2570 if (res == -1 && PyErr_Occurred())
2571 return NULL;
2572 return PyInt_FromLong(res);
2573}
2574
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002576wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577{
2578 ternaryfunc func = (ternaryfunc)wrapped;
2579
Guido van Rossumc8e56452001-10-22 00:43:43 +00002580 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002581}
2582
Tim Peters6d6c1a32001-08-02 04:15:00 +00002583static PyObject *
2584wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2585{
2586 richcmpfunc func = (richcmpfunc)wrapped;
2587 PyObject *other;
2588
2589 if (!PyArg_ParseTuple(args, "O", &other))
2590 return NULL;
2591 return (*func)(self, other, op);
2592}
2593
2594#undef RICHCMP_WRAPPER
2595#define RICHCMP_WRAPPER(NAME, OP) \
2596static PyObject * \
2597richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2598{ \
2599 return wrap_richcmpfunc(self, args, wrapped, OP); \
2600}
2601
Jack Jansen8e938b42001-08-08 15:29:49 +00002602RICHCMP_WRAPPER(lt, Py_LT)
2603RICHCMP_WRAPPER(le, Py_LE)
2604RICHCMP_WRAPPER(eq, Py_EQ)
2605RICHCMP_WRAPPER(ne, Py_NE)
2606RICHCMP_WRAPPER(gt, Py_GT)
2607RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002608
Tim Peters6d6c1a32001-08-02 04:15:00 +00002609static PyObject *
2610wrap_next(PyObject *self, PyObject *args, void *wrapped)
2611{
2612 unaryfunc func = (unaryfunc)wrapped;
2613 PyObject *res;
2614
2615 if (!PyArg_ParseTuple(args, ""))
2616 return NULL;
2617 res = (*func)(self);
2618 if (res == NULL && !PyErr_Occurred())
2619 PyErr_SetNone(PyExc_StopIteration);
2620 return res;
2621}
2622
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623static PyObject *
2624wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2625{
2626 descrgetfunc func = (descrgetfunc)wrapped;
2627 PyObject *obj;
2628 PyObject *type = NULL;
2629
2630 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2631 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632 return (*func)(self, obj, type);
2633}
2634
Tim Peters6d6c1a32001-08-02 04:15:00 +00002635static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002636wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002637{
2638 descrsetfunc func = (descrsetfunc)wrapped;
2639 PyObject *obj, *value;
2640 int ret;
2641
2642 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2643 return NULL;
2644 ret = (*func)(self, obj, value);
2645 if (ret < 0)
2646 return NULL;
2647 Py_INCREF(Py_None);
2648 return Py_None;
2649}
2650
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002652wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002653{
2654 initproc func = (initproc)wrapped;
2655
Guido van Rossumc8e56452001-10-22 00:43:43 +00002656 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657 return NULL;
2658 Py_INCREF(Py_None);
2659 return Py_None;
2660}
2661
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002663tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002664{
Barry Warsaw60f01882001-08-22 19:24:42 +00002665 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002666 PyObject *arg0, *res;
2667
2668 if (self == NULL || !PyType_Check(self))
2669 Py_FatalError("__new__() called with non-type 'self'");
2670 type = (PyTypeObject *)self;
2671 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002672 PyErr_Format(PyExc_TypeError,
2673 "%s.__new__(): not enough arguments",
2674 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002675 return NULL;
2676 }
2677 arg0 = PyTuple_GET_ITEM(args, 0);
2678 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002679 PyErr_Format(PyExc_TypeError,
2680 "%s.__new__(X): X is not a type object (%s)",
2681 type->tp_name,
2682 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002683 return NULL;
2684 }
2685 subtype = (PyTypeObject *)arg0;
2686 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002687 PyErr_Format(PyExc_TypeError,
2688 "%s.__new__(%s): %s is not a subtype of %s",
2689 type->tp_name,
2690 subtype->tp_name,
2691 subtype->tp_name,
2692 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002693 return NULL;
2694 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002695
2696 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002697 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002698 most derived base that's not a heap type is this type. */
2699 staticbase = subtype;
2700 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2701 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002702 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002703 PyErr_Format(PyExc_TypeError,
2704 "%s.__new__(%s) is not safe, use %s.__new__()",
2705 type->tp_name,
2706 subtype->tp_name,
2707 staticbase == NULL ? "?" : staticbase->tp_name);
2708 return NULL;
2709 }
2710
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002711 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2712 if (args == NULL)
2713 return NULL;
2714 res = type->tp_new(subtype, args, kwds);
2715 Py_DECREF(args);
2716 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717}
2718
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002719static struct PyMethodDef tp_new_methoddef[] = {
2720 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2721 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002722 {0}
2723};
2724
2725static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002726add_tp_new_wrapper(PyTypeObject *type)
2727{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002728 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002729
Guido van Rossum687ae002001-10-15 22:03:32 +00002730 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002731 return 0;
2732 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002733 if (func == NULL)
2734 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002735 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002736}
2737
Guido van Rossumf040ede2001-08-07 16:40:56 +00002738/* Slot wrappers that call the corresponding __foo__ slot. See comments
2739 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002740
Guido van Rossumdc91b992001-08-08 22:26:22 +00002741#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002743FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002745 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002746 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002747}
2748
Guido van Rossumdc91b992001-08-08 22:26:22 +00002749#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002751FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002752{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002753 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002754 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755}
2756
Guido van Rossumdc91b992001-08-08 22:26:22 +00002757
2758#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002760FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002762 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002763 int do_other = self->ob_type != other->ob_type && \
2764 other->ob_type->tp_as_number != NULL && \
2765 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002766 if (self->ob_type->tp_as_number != NULL && \
2767 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2768 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002769 if (do_other && \
2770 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2771 r = call_maybe( \
2772 other, ROPSTR, &rcache_str, "(O)", self); \
2773 if (r != Py_NotImplemented) \
2774 return r; \
2775 Py_DECREF(r); \
2776 do_other = 0; \
2777 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002778 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002779 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002780 if (r != Py_NotImplemented || \
2781 other->ob_type == self->ob_type) \
2782 return r; \
2783 Py_DECREF(r); \
2784 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002785 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002786 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002787 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002788 } \
2789 Py_INCREF(Py_NotImplemented); \
2790 return Py_NotImplemented; \
2791}
2792
2793#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2794 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2795
2796#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2797static PyObject * \
2798FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2799{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002800 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002801 return call_method(self, OPSTR, &cache_str, \
2802 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803}
2804
2805static int
2806slot_sq_length(PyObject *self)
2807{
Guido van Rossum2730b132001-08-28 18:22:14 +00002808 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002809 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002810 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002811
2812 if (res == NULL)
2813 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002814 len = (int)PyInt_AsLong(res);
2815 Py_DECREF(res);
2816 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817}
2818
Guido van Rossumdc91b992001-08-08 22:26:22 +00002819SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2820SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002821
2822/* Super-optimized version of slot_sq_item.
2823 Other slots could do the same... */
2824static PyObject *
2825slot_sq_item(PyObject *self, int i)
2826{
2827 static PyObject *getitem_str;
2828 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2829 descrgetfunc f;
2830
2831 if (getitem_str == NULL) {
2832 getitem_str = PyString_InternFromString("__getitem__");
2833 if (getitem_str == NULL)
2834 return NULL;
2835 }
2836 func = _PyType_Lookup(self->ob_type, getitem_str);
2837 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002838 if ((f = func->ob_type->tp_descr_get) == NULL)
2839 Py_INCREF(func);
2840 else
2841 func = f(func, self, (PyObject *)(self->ob_type));
2842 ival = PyInt_FromLong(i);
2843 if (ival != NULL) {
2844 args = PyTuple_New(1);
2845 if (args != NULL) {
2846 PyTuple_SET_ITEM(args, 0, ival);
2847 retval = PyObject_Call(func, args, NULL);
2848 Py_XDECREF(args);
2849 Py_XDECREF(func);
2850 return retval;
2851 }
2852 }
2853 }
2854 else {
2855 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2856 }
2857 Py_XDECREF(args);
2858 Py_XDECREF(ival);
2859 Py_XDECREF(func);
2860 return NULL;
2861}
2862
Guido van Rossumdc91b992001-08-08 22:26:22 +00002863SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864
2865static int
2866slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2867{
2868 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002869 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002870
2871 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002872 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002873 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002874 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002875 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002876 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877 if (res == NULL)
2878 return -1;
2879 Py_DECREF(res);
2880 return 0;
2881}
2882
2883static int
2884slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2885{
2886 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002887 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888
2889 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002890 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002891 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002892 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002893 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002894 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002895 if (res == NULL)
2896 return -1;
2897 Py_DECREF(res);
2898 return 0;
2899}
2900
2901static int
2902slot_sq_contains(PyObject *self, PyObject *value)
2903{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002904 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002905 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002906
Guido van Rossum55f20992001-10-01 17:18:22 +00002907 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002908
2909 if (func != NULL) {
2910 args = Py_BuildValue("(O)", value);
2911 if (args == NULL)
2912 res = NULL;
2913 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002914 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002915 Py_DECREF(args);
2916 }
2917 Py_DECREF(func);
2918 if (res == NULL)
2919 return -1;
2920 return PyObject_IsTrue(res);
2921 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002922 else if (PyErr_Occurred())
2923 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002924 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002925 return _PySequence_IterSearch(self, value,
2926 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002927 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002928}
2929
Guido van Rossumdc91b992001-08-08 22:26:22 +00002930SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2931SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932
2933#define slot_mp_length slot_sq_length
2934
Guido van Rossumdc91b992001-08-08 22:26:22 +00002935SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002936
2937static int
2938slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2939{
2940 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002941 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942
2943 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002944 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002945 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002947 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002948 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002949 if (res == NULL)
2950 return -1;
2951 Py_DECREF(res);
2952 return 0;
2953}
2954
Guido van Rossumdc91b992001-08-08 22:26:22 +00002955SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2956SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2957SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2958SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2959SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2960SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2961
2962staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2963
2964SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2965 nb_power, "__pow__", "__rpow__")
2966
2967static PyObject *
2968slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2969{
Guido van Rossum2730b132001-08-28 18:22:14 +00002970 static PyObject *pow_str;
2971
Guido van Rossumdc91b992001-08-08 22:26:22 +00002972 if (modulus == Py_None)
2973 return slot_nb_power_binary(self, other);
2974 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002975 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002976 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002977}
2978
2979SLOT0(slot_nb_negative, "__neg__")
2980SLOT0(slot_nb_positive, "__pos__")
2981SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002982
2983static int
2984slot_nb_nonzero(PyObject *self)
2985{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002986 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002987 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002988
Guido van Rossum55f20992001-10-01 17:18:22 +00002989 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002990 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002991 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002992 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002993 func = lookup_maybe(self, "__len__", &len_str);
2994 if (func == NULL) {
2995 if (PyErr_Occurred())
2996 return -1;
2997 else
2998 return 1;
2999 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003000 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003001 res = PyObject_CallObject(func, NULL);
3002 Py_DECREF(func);
3003 if (res == NULL)
3004 return -1;
3005 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006}
3007
Guido van Rossumdc91b992001-08-08 22:26:22 +00003008SLOT0(slot_nb_invert, "__invert__")
3009SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3010SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3011SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3012SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3013SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003014
3015static int
3016slot_nb_coerce(PyObject **a, PyObject **b)
3017{
3018 static PyObject *coerce_str;
3019 PyObject *self = *a, *other = *b;
3020
3021 if (self->ob_type->tp_as_number != NULL &&
3022 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3023 PyObject *r;
3024 r = call_maybe(
3025 self, "__coerce__", &coerce_str, "(O)", other);
3026 if (r == NULL)
3027 return -1;
3028 if (r == Py_NotImplemented) {
3029 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003030 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003031 else {
3032 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3033 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003034 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003035 Py_DECREF(r);
3036 return -1;
3037 }
3038 *a = PyTuple_GET_ITEM(r, 0);
3039 Py_INCREF(*a);
3040 *b = PyTuple_GET_ITEM(r, 1);
3041 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003042 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003043 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003044 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003045 }
3046 if (other->ob_type->tp_as_number != NULL &&
3047 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3048 PyObject *r;
3049 r = call_maybe(
3050 other, "__coerce__", &coerce_str, "(O)", self);
3051 if (r == NULL)
3052 return -1;
3053 if (r == Py_NotImplemented) {
3054 Py_DECREF(r);
3055 return 1;
3056 }
3057 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3058 PyErr_SetString(PyExc_TypeError,
3059 "__coerce__ didn't return a 2-tuple");
3060 Py_DECREF(r);
3061 return -1;
3062 }
3063 *a = PyTuple_GET_ITEM(r, 1);
3064 Py_INCREF(*a);
3065 *b = PyTuple_GET_ITEM(r, 0);
3066 Py_INCREF(*b);
3067 Py_DECREF(r);
3068 return 0;
3069 }
3070 return 1;
3071}
3072
Guido van Rossumdc91b992001-08-08 22:26:22 +00003073SLOT0(slot_nb_int, "__int__")
3074SLOT0(slot_nb_long, "__long__")
3075SLOT0(slot_nb_float, "__float__")
3076SLOT0(slot_nb_oct, "__oct__")
3077SLOT0(slot_nb_hex, "__hex__")
3078SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3079SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3080SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3081SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3082SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3083SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3084SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3085SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3086SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3087SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3088SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3089SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3090 "__floordiv__", "__rfloordiv__")
3091SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3092SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3093SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094
3095static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003096half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003098 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003099 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003100 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003101
Guido van Rossum60718732001-08-28 17:47:51 +00003102 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003103 if (func == NULL) {
3104 PyErr_Clear();
3105 }
3106 else {
3107 args = Py_BuildValue("(O)", other);
3108 if (args == NULL)
3109 res = NULL;
3110 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003111 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003112 Py_DECREF(args);
3113 }
3114 if (res != Py_NotImplemented) {
3115 if (res == NULL)
3116 return -2;
3117 c = PyInt_AsLong(res);
3118 Py_DECREF(res);
3119 if (c == -1 && PyErr_Occurred())
3120 return -2;
3121 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3122 }
3123 Py_DECREF(res);
3124 }
3125 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126}
3127
Guido van Rossumab3b0342001-09-18 20:38:53 +00003128/* This slot is published for the benefit of try_3way_compare in object.c */
3129int
3130_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003131{
3132 int c;
3133
Guido van Rossumab3b0342001-09-18 20:38:53 +00003134 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003135 c = half_compare(self, other);
3136 if (c <= 1)
3137 return c;
3138 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003139 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003140 c = half_compare(other, self);
3141 if (c < -1)
3142 return -2;
3143 if (c <= 1)
3144 return -c;
3145 }
3146 return (void *)self < (void *)other ? -1 :
3147 (void *)self > (void *)other ? 1 : 0;
3148}
3149
3150static PyObject *
3151slot_tp_repr(PyObject *self)
3152{
3153 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003154 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003155
Guido van Rossum60718732001-08-28 17:47:51 +00003156 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003157 if (func != NULL) {
3158 res = PyEval_CallObject(func, NULL);
3159 Py_DECREF(func);
3160 return res;
3161 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003162 PyErr_Clear();
3163 return PyString_FromFormat("<%s object at %p>",
3164 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003165}
3166
3167static PyObject *
3168slot_tp_str(PyObject *self)
3169{
3170 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003171 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003172
Guido van Rossum60718732001-08-28 17:47:51 +00003173 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003174 if (func != NULL) {
3175 res = PyEval_CallObject(func, NULL);
3176 Py_DECREF(func);
3177 return res;
3178 }
3179 else {
3180 PyErr_Clear();
3181 return slot_tp_repr(self);
3182 }
3183}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003184
3185static long
3186slot_tp_hash(PyObject *self)
3187{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003188 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003189 static PyObject *hash_str, *eq_str, *cmp_str;
3190
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191 long h;
3192
Guido van Rossum60718732001-08-28 17:47:51 +00003193 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003194
3195 if (func != NULL) {
3196 res = PyEval_CallObject(func, NULL);
3197 Py_DECREF(func);
3198 if (res == NULL)
3199 return -1;
3200 h = PyInt_AsLong(res);
3201 }
3202 else {
3203 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003204 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003205 if (func == NULL) {
3206 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003207 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003208 }
3209 if (func != NULL) {
3210 Py_DECREF(func);
3211 PyErr_SetString(PyExc_TypeError, "unhashable type");
3212 return -1;
3213 }
3214 PyErr_Clear();
3215 h = _Py_HashPointer((void *)self);
3216 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003217 if (h == -1 && !PyErr_Occurred())
3218 h = -2;
3219 return h;
3220}
3221
3222static PyObject *
3223slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3224{
Guido van Rossum60718732001-08-28 17:47:51 +00003225 static PyObject *call_str;
3226 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227 PyObject *res;
3228
3229 if (meth == NULL)
3230 return NULL;
3231 res = PyObject_Call(meth, args, kwds);
3232 Py_DECREF(meth);
3233 return res;
3234}
3235
Guido van Rossum14a6f832001-10-17 13:59:09 +00003236/* There are two slot dispatch functions for tp_getattro.
3237
3238 - slot_tp_getattro() is used when __getattribute__ is overridden
3239 but no __getattr__ hook is present;
3240
3241 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3242
Guido van Rossumc334df52002-04-04 23:44:47 +00003243 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3244 detects the absence of __getattr__ and then installs the simpler slot if
3245 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003246
Tim Peters6d6c1a32001-08-02 04:15:00 +00003247static PyObject *
3248slot_tp_getattro(PyObject *self, PyObject *name)
3249{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003250 static PyObject *getattribute_str = NULL;
3251 return call_method(self, "__getattribute__", &getattribute_str,
3252 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253}
3254
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003255static PyObject *
3256slot_tp_getattr_hook(PyObject *self, PyObject *name)
3257{
3258 PyTypeObject *tp = self->ob_type;
3259 PyObject *getattr, *getattribute, *res;
3260 static PyObject *getattribute_str = NULL;
3261 static PyObject *getattr_str = NULL;
3262
3263 if (getattr_str == NULL) {
3264 getattr_str = PyString_InternFromString("__getattr__");
3265 if (getattr_str == NULL)
3266 return NULL;
3267 }
3268 if (getattribute_str == NULL) {
3269 getattribute_str =
3270 PyString_InternFromString("__getattribute__");
3271 if (getattribute_str == NULL)
3272 return NULL;
3273 }
3274 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003275 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003276 /* No __getattr__ hook: use a simpler dispatcher */
3277 tp->tp_getattro = slot_tp_getattro;
3278 return slot_tp_getattro(self, name);
3279 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003280 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003281 if (getattribute == NULL ||
3282 (getattribute->ob_type == &PyWrapperDescr_Type &&
3283 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3284 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003285 res = PyObject_GenericGetAttr(self, name);
3286 else
3287 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003288 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003289 PyErr_Clear();
3290 res = PyObject_CallFunction(getattr, "OO", self, name);
3291 }
3292 return res;
3293}
3294
Tim Peters6d6c1a32001-08-02 04:15:00 +00003295static int
3296slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3297{
3298 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003299 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300
3301 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003302 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003303 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003305 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003306 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003307 if (res == NULL)
3308 return -1;
3309 Py_DECREF(res);
3310 return 0;
3311}
3312
3313/* Map rich comparison operators to their __xx__ namesakes */
3314static char *name_op[] = {
3315 "__lt__",
3316 "__le__",
3317 "__eq__",
3318 "__ne__",
3319 "__gt__",
3320 "__ge__",
3321};
3322
3323static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003324half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003326 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003327 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003328
Guido van Rossum60718732001-08-28 17:47:51 +00003329 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003330 if (func == NULL) {
3331 PyErr_Clear();
3332 Py_INCREF(Py_NotImplemented);
3333 return Py_NotImplemented;
3334 }
3335 args = Py_BuildValue("(O)", other);
3336 if (args == NULL)
3337 res = NULL;
3338 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003339 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003340 Py_DECREF(args);
3341 }
3342 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003343 return res;
3344}
3345
Guido van Rossumb8f63662001-08-15 23:57:02 +00003346/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3347static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3348
3349static PyObject *
3350slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3351{
3352 PyObject *res;
3353
3354 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3355 res = half_richcompare(self, other, op);
3356 if (res != Py_NotImplemented)
3357 return res;
3358 Py_DECREF(res);
3359 }
3360 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3361 res = half_richcompare(other, self, swapped_op[op]);
3362 if (res != Py_NotImplemented) {
3363 return res;
3364 }
3365 Py_DECREF(res);
3366 }
3367 Py_INCREF(Py_NotImplemented);
3368 return Py_NotImplemented;
3369}
3370
3371static PyObject *
3372slot_tp_iter(PyObject *self)
3373{
3374 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003375 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003376
Guido van Rossum60718732001-08-28 17:47:51 +00003377 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003378 if (func != NULL) {
3379 res = PyObject_CallObject(func, NULL);
3380 Py_DECREF(func);
3381 return res;
3382 }
3383 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003384 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003385 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003386 PyErr_SetString(PyExc_TypeError,
3387 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003388 return NULL;
3389 }
3390 Py_DECREF(func);
3391 return PySeqIter_New(self);
3392}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393
3394static PyObject *
3395slot_tp_iternext(PyObject *self)
3396{
Guido van Rossum2730b132001-08-28 18:22:14 +00003397 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003398 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399}
3400
Guido van Rossum1a493502001-08-17 16:47:50 +00003401static PyObject *
3402slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3403{
3404 PyTypeObject *tp = self->ob_type;
3405 PyObject *get;
3406 static PyObject *get_str = NULL;
3407
3408 if (get_str == NULL) {
3409 get_str = PyString_InternFromString("__get__");
3410 if (get_str == NULL)
3411 return NULL;
3412 }
3413 get = _PyType_Lookup(tp, get_str);
3414 if (get == NULL) {
3415 /* Avoid further slowdowns */
3416 if (tp->tp_descr_get == slot_tp_descr_get)
3417 tp->tp_descr_get = NULL;
3418 Py_INCREF(self);
3419 return self;
3420 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003421 if (obj == NULL)
3422 obj = Py_None;
3423 if (type == NULL)
3424 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003425 return PyObject_CallFunction(get, "OOO", self, obj, type);
3426}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003427
3428static int
3429slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3430{
Guido van Rossum2c252392001-08-24 10:13:31 +00003431 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003432 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003433
3434 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003435 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003436 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003437 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003438 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003439 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003440 if (res == NULL)
3441 return -1;
3442 Py_DECREF(res);
3443 return 0;
3444}
3445
3446static int
3447slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3448{
Guido van Rossum60718732001-08-28 17:47:51 +00003449 static PyObject *init_str;
3450 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451 PyObject *res;
3452
3453 if (meth == NULL)
3454 return -1;
3455 res = PyObject_Call(meth, args, kwds);
3456 Py_DECREF(meth);
3457 if (res == NULL)
3458 return -1;
3459 Py_DECREF(res);
3460 return 0;
3461}
3462
3463static PyObject *
3464slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3465{
3466 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3467 PyObject *newargs, *x;
3468 int i, n;
3469
3470 if (func == NULL)
3471 return NULL;
3472 assert(PyTuple_Check(args));
3473 n = PyTuple_GET_SIZE(args);
3474 newargs = PyTuple_New(n+1);
3475 if (newargs == NULL)
3476 return NULL;
3477 Py_INCREF(type);
3478 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3479 for (i = 0; i < n; i++) {
3480 x = PyTuple_GET_ITEM(args, i);
3481 Py_INCREF(x);
3482 PyTuple_SET_ITEM(newargs, i+1, x);
3483 }
3484 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003485 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486 Py_DECREF(func);
3487 return x;
3488}
3489
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003490
3491/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3492 functions. The offsets here are relative to the 'etype' structure, which
3493 incorporates the additional structures used for numbers, sequences and
3494 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3495 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003496 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3497 terminated with an all-zero entry. (This table is further initialized and
3498 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003499
Guido van Rossum6d204072001-10-21 00:44:31 +00003500typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003501
3502#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003503#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003504#undef ETSLOT
3505#undef SQSLOT
3506#undef MPSLOT
3507#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003508#undef UNSLOT
3509#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003510#undef BINSLOT
3511#undef RBINSLOT
3512
Guido van Rossum6d204072001-10-21 00:44:31 +00003513#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3514 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003515#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3516 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3517 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003518#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3519 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3520#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3521 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3522#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3523 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3524#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3525 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3526#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3527 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3528 "x." NAME "() <==> " DOC)
3529#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3530 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3531 "x." NAME "(y) <==> x" DOC "y")
3532#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3533 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3534 "x." NAME "(y) <==> x" DOC "y")
3535#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3536 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3537 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003538
3539static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003540 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3541 "x.__len__() <==> len(x)"),
3542 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3543 "x.__add__(y) <==> x+y"),
3544 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3545 "x.__mul__(n) <==> x*n"),
3546 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3547 "x.__rmul__(n) <==> n*x"),
3548 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3549 "x.__getitem__(y) <==> x[y]"),
3550 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3551 "x.__getslice__(i, j) <==> x[i:j]"),
3552 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3553 "x.__setitem__(i, y) <==> x[i]=y"),
3554 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3555 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003556 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003557 wrap_intintobjargproc,
3558 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3559 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3560 "x.__delslice__(i, j) <==> del x[i:j]"),
3561 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3562 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003563 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003564 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003565 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003566 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003567
Guido van Rossum6d204072001-10-21 00:44:31 +00003568 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3569 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003570 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003571 wrap_binaryfunc,
3572 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003573 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003574 wrap_objobjargproc,
3575 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003576 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003577 wrap_delitem,
3578 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003579
Guido van Rossum6d204072001-10-21 00:44:31 +00003580 BINSLOT("__add__", nb_add, slot_nb_add,
3581 "+"),
3582 RBINSLOT("__radd__", nb_add, slot_nb_add,
3583 "+"),
3584 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3585 "-"),
3586 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3587 "-"),
3588 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3589 "*"),
3590 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3591 "*"),
3592 BINSLOT("__div__", nb_divide, slot_nb_divide,
3593 "/"),
3594 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3595 "/"),
3596 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3597 "%"),
3598 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3599 "%"),
3600 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3601 "divmod(x, y)"),
3602 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3603 "divmod(y, x)"),
3604 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3605 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3606 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3607 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3608 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3609 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3610 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3611 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003612 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003613 "x != 0"),
3614 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3615 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3616 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3617 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3618 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3619 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3620 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3621 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3622 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3623 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3624 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3625 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3626 "x.__coerce__(y) <==> coerce(x, y)"),
3627 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3628 "int(x)"),
3629 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3630 "long(x)"),
3631 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3632 "float(x)"),
3633 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3634 "oct(x)"),
3635 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3636 "hex(x)"),
3637 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3638 wrap_binaryfunc, "+"),
3639 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3640 wrap_binaryfunc, "-"),
3641 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3642 wrap_binaryfunc, "*"),
3643 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3644 wrap_binaryfunc, "/"),
3645 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3646 wrap_binaryfunc, "%"),
3647 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3648 wrap_ternaryfunc, "**"),
3649 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3650 wrap_binaryfunc, "<<"),
3651 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3652 wrap_binaryfunc, ">>"),
3653 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3654 wrap_binaryfunc, "&"),
3655 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3656 wrap_binaryfunc, "^"),
3657 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3658 wrap_binaryfunc, "|"),
3659 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3660 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3661 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3662 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3663 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3664 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3665 IBSLOT("__itruediv__", nb_inplace_true_divide,
3666 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003667
Guido van Rossum6d204072001-10-21 00:44:31 +00003668 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3669 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003670 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003671 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3672 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003673 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003674 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3675 "x.__cmp__(y) <==> cmp(x,y)"),
3676 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3677 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003678 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3679 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003680 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003681 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3682 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3683 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3684 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3685 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3686 "x.__setattr__('name', value) <==> x.name = value"),
3687 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3688 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3689 "x.__delattr__('name') <==> del x.name"),
3690 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3691 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3692 "x.__lt__(y) <==> x<y"),
3693 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3694 "x.__le__(y) <==> x<=y"),
3695 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3696 "x.__eq__(y) <==> x==y"),
3697 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3698 "x.__ne__(y) <==> x!=y"),
3699 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3700 "x.__gt__(y) <==> x>y"),
3701 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3702 "x.__ge__(y) <==> x>=y"),
3703 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3704 "x.__iter__() <==> iter(x)"),
3705 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3706 "x.next() -> the next value, or raise StopIteration"),
3707 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3708 "descr.__get__(obj[, type]) -> value"),
3709 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3710 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003711 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003712 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003713 "see x.__class__.__doc__ for signature",
3714 PyWrapperFlag_KEYWORDS),
3715 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003716 {NULL}
3717};
3718
Guido van Rossumc334df52002-04-04 23:44:47 +00003719/* Given a type pointer and an offset gotten from a slotdef entry, return a
3720 pointer to the actual slot. This is not quite the same as simply adding
3721 the offset to the type pointer, since it takes care to indirect through the
3722 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3723 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003724static void **
3725slotptr(PyTypeObject *type, int offset)
3726{
3727 char *ptr;
3728
3729 assert(offset >= 0);
3730 assert(offset < offsetof(etype, as_buffer));
3731 if (offset >= offsetof(etype, as_mapping)) {
3732 ptr = (void *)type->tp_as_mapping;
3733 offset -= offsetof(etype, as_mapping);
3734 }
3735 else if (offset >= offsetof(etype, as_sequence)) {
3736 ptr = (void *)type->tp_as_sequence;
3737 offset -= offsetof(etype, as_sequence);
3738 }
3739 else if (offset >= offsetof(etype, as_number)) {
3740 ptr = (void *)type->tp_as_number;
3741 offset -= offsetof(etype, as_number);
3742 }
3743 else {
3744 ptr = (void *)type;
3745 }
3746 if (ptr != NULL)
3747 ptr += offset;
3748 return (void **)ptr;
3749}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003750
Guido van Rossumc334df52002-04-04 23:44:47 +00003751/* Length of array of slotdef pointers used to store slots with the
3752 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3753 the same __name__, for any __name__. Since that's a static property, it is
3754 appropriate to declare fixed-size arrays for this. */
3755#define MAX_EQUIV 10
3756
3757/* Return a slot pointer for a given name, but ONLY if the attribute has
3758 exactly one slot function. The name must be an interned string. */
3759static void **
3760resolve_slotdups(PyTypeObject *type, PyObject *name)
3761{
3762 /* XXX Maybe this could be optimized more -- but is it worth it? */
3763
3764 /* pname and ptrs act as a little cache */
3765 static PyObject *pname;
3766 static slotdef *ptrs[MAX_EQUIV];
3767 slotdef *p, **pp;
3768 void **res, **ptr;
3769
3770 if (pname != name) {
3771 /* Collect all slotdefs that match name into ptrs. */
3772 pname = name;
3773 pp = ptrs;
3774 for (p = slotdefs; p->name_strobj; p++) {
3775 if (p->name_strobj == name)
3776 *pp++ = p;
3777 }
3778 *pp = NULL;
3779 }
3780
3781 /* Look in all matching slots of the type; if exactly one of these has
3782 a filled-in slot, return its value. Otherwise return NULL. */
3783 res = NULL;
3784 for (pp = ptrs; *pp; pp++) {
3785 ptr = slotptr(type, (*pp)->offset);
3786 if (ptr == NULL || *ptr == NULL)
3787 continue;
3788 if (res != NULL)
3789 return NULL;
3790 res = ptr;
3791 }
3792 return res;
3793}
3794
3795/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3796 does some incredibly complex thinking and then sticks something into the
3797 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3798 interests, and then stores a generic wrapper or a specific function into
3799 the slot.) Return a pointer to the next slotdef with a different offset,
3800 because that's convenient for fixup_slot_dispatchers(). */
3801static slotdef *
3802update_one_slot(PyTypeObject *type, slotdef *p)
3803{
3804 PyObject *descr;
3805 PyWrapperDescrObject *d;
3806 void *generic = NULL, *specific = NULL;
3807 int use_generic = 0;
3808 int offset = p->offset;
3809 void **ptr = slotptr(type, offset);
3810
3811 if (ptr == NULL) {
3812 do {
3813 ++p;
3814 } while (p->offset == offset);
3815 return p;
3816 }
3817 do {
3818 descr = _PyType_Lookup(type, p->name_strobj);
3819 if (descr == NULL)
3820 continue;
3821 if (descr->ob_type == &PyWrapperDescr_Type) {
3822 void **tptr = resolve_slotdups(type, p->name_strobj);
3823 if (tptr == NULL || tptr == ptr)
3824 generic = p->function;
3825 d = (PyWrapperDescrObject *)descr;
3826 if (d->d_base->wrapper == p->wrapper &&
3827 PyType_IsSubtype(type, d->d_type))
3828 {
3829 if (specific == NULL ||
3830 specific == d->d_wrapped)
3831 specific = d->d_wrapped;
3832 else
3833 use_generic = 1;
3834 }
3835 }
3836 else {
3837 use_generic = 1;
3838 generic = p->function;
3839 }
3840 } while ((++p)->offset == offset);
3841 if (specific && !use_generic)
3842 *ptr = specific;
3843 else
3844 *ptr = generic;
3845 return p;
3846}
3847
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003848staticforward int recurse_down_subclasses(PyTypeObject *type,
3849 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003850
Guido van Rossumc334df52002-04-04 23:44:47 +00003851/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3852 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003853static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003854update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003855{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003856 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003857
Guido van Rossumc334df52002-04-04 23:44:47 +00003858 for (pp = pp0; *pp; pp++)
3859 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003860 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003861}
3862
Guido van Rossumc334df52002-04-04 23:44:47 +00003863/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3864 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003865static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003866recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003867{
3868 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003869 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003870 int i, n;
3871
3872 subclasses = type->tp_subclasses;
3873 if (subclasses == NULL)
3874 return 0;
3875 assert(PyList_Check(subclasses));
3876 n = PyList_GET_SIZE(subclasses);
3877 for (i = 0; i < n; i++) {
3878 ref = PyList_GET_ITEM(subclasses, i);
3879 assert(PyWeakref_CheckRef(ref));
3880 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3881 if (subclass == NULL)
3882 continue;
3883 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003884 /* Avoid recursing down into unaffected classes */
3885 dict = subclass->tp_dict;
3886 if (dict != NULL && PyDict_Check(dict) &&
3887 PyDict_GetItem(dict, name) != NULL)
3888 continue;
3889 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003890 return -1;
3891 }
3892 return 0;
3893}
3894
Guido van Rossumc334df52002-04-04 23:44:47 +00003895/* Comparison function for qsort() to compare slotdefs by their offset, and
3896 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003897static int
3898slotdef_cmp(const void *aa, const void *bb)
3899{
3900 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3901 int c = a->offset - b->offset;
3902 if (c != 0)
3903 return c;
3904 else
3905 return a - b;
3906}
3907
Guido van Rossumc334df52002-04-04 23:44:47 +00003908/* Initialize the slotdefs table by adding interned string objects for the
3909 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003910static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003911init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003912{
3913 slotdef *p;
3914 static int initialized = 0;
3915
3916 if (initialized)
3917 return;
3918 for (p = slotdefs; p->name; p++) {
3919 p->name_strobj = PyString_InternFromString(p->name);
3920 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00003921 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003922 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003923 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3924 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003925 initialized = 1;
3926}
3927
Guido van Rossumc334df52002-04-04 23:44:47 +00003928/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003929static int
3930update_slot(PyTypeObject *type, PyObject *name)
3931{
Guido van Rossumc334df52002-04-04 23:44:47 +00003932 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003933 slotdef *p;
3934 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003935 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003936
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003937 init_slotdefs();
3938 pp = ptrs;
3939 for (p = slotdefs; p->name; p++) {
3940 /* XXX assume name is interned! */
3941 if (p->name_strobj == name)
3942 *pp++ = p;
3943 }
3944 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003945 for (pp = ptrs; *pp; pp++) {
3946 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003947 offset = p->offset;
3948 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003949 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003950 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003951 }
Guido van Rossumc334df52002-04-04 23:44:47 +00003952 if (ptrs[0] == NULL)
3953 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003954 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003955}
3956
Guido van Rossumc334df52002-04-04 23:44:47 +00003957/* Store the proper functions in the slot dispatches at class (type)
3958 definition time, based upon which operations the class overrides in its
3959 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003960static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003961fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003963 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003965 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00003966 for (p = slotdefs; p->name; )
3967 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003968}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003969
Guido van Rossum6d204072001-10-21 00:44:31 +00003970/* This function is called by PyType_Ready() to populate the type's
3971 dictionary with method descriptors for function slots. For each
3972 function slot (like tp_repr) that's defined in the type, one or
3973 more corresponding descriptors are added in the type's tp_dict
3974 dictionary under the appropriate name (like __repr__). Some
3975 function slots cause more than one descriptor to be added (for
3976 example, the nb_add slot adds both __add__ and __radd__
3977 descriptors) and some function slots compete for the same
3978 descriptor (for example both sq_item and mp_subscript generate a
3979 __getitem__ descriptor). This only adds new descriptors and
3980 doesn't overwrite entries in tp_dict that were previously
3981 defined. The descriptors contain a reference to the C function
3982 they must call, so that it's safe if they are copied into a
3983 subtype's __dict__ and the subtype has a different C function in
3984 its slot -- calling the method defined by the descriptor will call
3985 the C function that was used to create it, rather than the C
3986 function present in the slot when it is called. (This is important
3987 because a subtype may have a C function in the slot that calls the
3988 method from the dictionary, and we want to avoid infinite recursion
3989 here.) */
3990
3991static int
3992add_operators(PyTypeObject *type)
3993{
3994 PyObject *dict = type->tp_dict;
3995 slotdef *p;
3996 PyObject *descr;
3997 void **ptr;
3998
3999 init_slotdefs();
4000 for (p = slotdefs; p->name; p++) {
4001 if (p->wrapper == NULL)
4002 continue;
4003 ptr = slotptr(type, p->offset);
4004 if (!ptr || !*ptr)
4005 continue;
4006 if (PyDict_GetItem(dict, p->name_strobj))
4007 continue;
4008 descr = PyDescr_NewWrapper(type, p, *ptr);
4009 if (descr == NULL)
4010 return -1;
4011 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4012 return -1;
4013 Py_DECREF(descr);
4014 }
4015 if (type->tp_new != NULL) {
4016 if (add_tp_new_wrapper(type) < 0)
4017 return -1;
4018 }
4019 return 0;
4020}
4021
Guido van Rossum705f0f52001-08-24 16:47:00 +00004022
4023/* Cooperative 'super' */
4024
4025typedef struct {
4026 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004027 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004028 PyObject *obj;
4029} superobject;
4030
Guido van Rossum6f799372001-09-20 20:46:19 +00004031static PyMemberDef super_members[] = {
4032 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4033 "the class invoking super()"},
4034 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4035 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004036 {0}
4037};
4038
Guido van Rossum705f0f52001-08-24 16:47:00 +00004039static void
4040super_dealloc(PyObject *self)
4041{
4042 superobject *su = (superobject *)self;
4043
Guido van Rossum048eb752001-10-02 21:24:57 +00004044 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004045 Py_XDECREF(su->obj);
4046 Py_XDECREF(su->type);
4047 self->ob_type->tp_free(self);
4048}
4049
4050static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004051super_repr(PyObject *self)
4052{
4053 superobject *su = (superobject *)self;
4054
4055 if (su->obj)
4056 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004057 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004058 su->type ? su->type->tp_name : "NULL",
4059 su->obj->ob_type->tp_name);
4060 else
4061 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004062 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004063 su->type ? su->type->tp_name : "NULL");
4064}
4065
4066static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004067super_getattro(PyObject *self, PyObject *name)
4068{
4069 superobject *su = (superobject *)self;
4070
4071 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004072 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004073 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004074 descrgetfunc f;
4075 int i, n;
4076
Guido van Rossum155db9a2002-04-02 17:53:47 +00004077 starttype = su->obj->ob_type;
4078 mro = starttype->tp_mro;
4079
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004080 if (mro == NULL)
4081 n = 0;
4082 else {
4083 assert(PyTuple_Check(mro));
4084 n = PyTuple_GET_SIZE(mro);
4085 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004086 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004087 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004088 break;
4089 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004090 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004091 starttype = (PyTypeObject *)(su->obj);
4092 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004093 if (mro == NULL)
4094 n = 0;
4095 else {
4096 assert(PyTuple_Check(mro));
4097 n = PyTuple_GET_SIZE(mro);
4098 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004099 for (i = 0; i < n; i++) {
4100 if ((PyObject *)(su->type) ==
4101 PyTuple_GET_ITEM(mro, i))
4102 break;
4103 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004104 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004105 i++;
4106 res = NULL;
4107 for (; i < n; i++) {
4108 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004109 if (PyType_Check(tmp))
4110 dict = ((PyTypeObject *)tmp)->tp_dict;
4111 else if (PyClass_Check(tmp))
4112 dict = ((PyClassObject *)tmp)->cl_dict;
4113 else
4114 continue;
4115 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004116 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004117 Py_INCREF(res);
4118 f = res->ob_type->tp_descr_get;
4119 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004120 tmp = f(res, su->obj,
4121 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004122 Py_DECREF(res);
4123 res = tmp;
4124 }
4125 return res;
4126 }
4127 }
4128 }
4129 return PyObject_GenericGetAttr(self, name);
4130}
4131
Guido van Rossum5b443c62001-12-03 15:38:28 +00004132static int
4133supercheck(PyTypeObject *type, PyObject *obj)
4134{
4135 if (!PyType_IsSubtype(obj->ob_type, type) &&
4136 !(PyType_Check(obj) &&
4137 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4138 PyErr_SetString(PyExc_TypeError,
4139 "super(type, obj): "
4140 "obj must be an instance or subtype of type");
4141 return -1;
4142 }
4143 else
4144 return 0;
4145}
4146
Guido van Rossum705f0f52001-08-24 16:47:00 +00004147static PyObject *
4148super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4149{
4150 superobject *su = (superobject *)self;
4151 superobject *new;
4152
4153 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4154 /* Not binding to an object, or already bound */
4155 Py_INCREF(self);
4156 return self;
4157 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004158 if (su->ob_type != &PySuper_Type)
4159 /* If su is an instance of a subclass of super,
4160 call its type */
4161 return PyObject_CallFunction((PyObject *)su->ob_type,
4162 "OO", su->type, obj);
4163 else {
4164 /* Inline the common case */
4165 if (supercheck(su->type, obj) < 0)
4166 return NULL;
4167 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4168 NULL, NULL);
4169 if (new == NULL)
4170 return NULL;
4171 Py_INCREF(su->type);
4172 Py_INCREF(obj);
4173 new->type = su->type;
4174 new->obj = obj;
4175 return (PyObject *)new;
4176 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004177}
4178
4179static int
4180super_init(PyObject *self, PyObject *args, PyObject *kwds)
4181{
4182 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004183 PyTypeObject *type;
4184 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004185
4186 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4187 return -1;
4188 if (obj == Py_None)
4189 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004190 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004191 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004192 Py_INCREF(type);
4193 Py_XINCREF(obj);
4194 su->type = type;
4195 su->obj = obj;
4196 return 0;
4197}
4198
4199static char super_doc[] =
4200"super(type) -> unbound super object\n"
4201"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004202"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004203"Typical use to call a cooperative superclass method:\n"
4204"class C(B):\n"
4205" def meth(self, arg):\n"
4206" super(C, self).meth(arg)";
4207
Guido van Rossum048eb752001-10-02 21:24:57 +00004208static int
4209super_traverse(PyObject *self, visitproc visit, void *arg)
4210{
4211 superobject *su = (superobject *)self;
4212 int err;
4213
4214#define VISIT(SLOT) \
4215 if (SLOT) { \
4216 err = visit((PyObject *)(SLOT), arg); \
4217 if (err) \
4218 return err; \
4219 }
4220
4221 VISIT(su->obj);
4222 VISIT(su->type);
4223
4224#undef VISIT
4225
4226 return 0;
4227}
4228
Guido van Rossum705f0f52001-08-24 16:47:00 +00004229PyTypeObject PySuper_Type = {
4230 PyObject_HEAD_INIT(&PyType_Type)
4231 0, /* ob_size */
4232 "super", /* tp_name */
4233 sizeof(superobject), /* tp_basicsize */
4234 0, /* tp_itemsize */
4235 /* methods */
4236 super_dealloc, /* tp_dealloc */
4237 0, /* tp_print */
4238 0, /* tp_getattr */
4239 0, /* tp_setattr */
4240 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004241 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004242 0, /* tp_as_number */
4243 0, /* tp_as_sequence */
4244 0, /* tp_as_mapping */
4245 0, /* tp_hash */
4246 0, /* tp_call */
4247 0, /* tp_str */
4248 super_getattro, /* tp_getattro */
4249 0, /* tp_setattro */
4250 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004251 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4252 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004253 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004254 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004255 0, /* tp_clear */
4256 0, /* tp_richcompare */
4257 0, /* tp_weaklistoffset */
4258 0, /* tp_iter */
4259 0, /* tp_iternext */
4260 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004261 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004262 0, /* tp_getset */
4263 0, /* tp_base */
4264 0, /* tp_dict */
4265 super_descr_get, /* tp_descr_get */
4266 0, /* tp_descr_set */
4267 0, /* tp_dictoffset */
4268 super_init, /* tp_init */
4269 PyType_GenericAlloc, /* tp_alloc */
4270 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004271 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004272};