blob: f647d57b6e717e6d87d3e733f73ebb83ec93dc9f [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;
Guido van Rossum6ca7d412002-04-18 00:22:00 +000085 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +000086 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +000087 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +000088 if (result == NULL) {
89 result = Py_None;
90 Py_INCREF(result);
91 }
92 else if (result->ob_type->tp_descr_get) {
93 result = result->ob_type->tp_descr_get(result, NULL, type);
94 }
95 else {
96 Py_INCREF(result);
97 }
Tim Peters24008312002-03-17 18:56:20 +000098 return result;
99}
100
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000101static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000102 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000103 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000105 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000106 {0}
107};
108
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000109static int
110type_compare(PyObject *v, PyObject *w)
111{
112 /* This is called with type objects only. So we
113 can just compare the addresses. */
114 Py_uintptr_t vv = (Py_uintptr_t)v;
115 Py_uintptr_t ww = (Py_uintptr_t)w;
116 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
117}
118
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000119static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000120type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000122 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000123 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000124
125 mod = type_module(type, NULL);
126 if (mod == NULL)
127 PyErr_Clear();
128 else if (!PyString_Check(mod)) {
129 Py_DECREF(mod);
130 mod = NULL;
131 }
132 name = type_name(type, NULL);
133 if (name == NULL)
134 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000135
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000136 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
137 kind = "class";
138 else
139 kind = "type";
140
Barry Warsaw7ce36942001-08-24 18:34:26 +0000141 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000142 rtn = PyString_FromFormat("<%s '%s.%s'>",
143 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000144 PyString_AS_STRING(mod),
145 PyString_AS_STRING(name));
146 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000147 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000148 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000149
Guido van Rossumc3542212001-08-16 09:18:56 +0000150 Py_XDECREF(mod);
151 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000152 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153}
154
Tim Peters6d6c1a32001-08-02 04:15:00 +0000155static PyObject *
156type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
157{
158 PyObject *obj;
159
160 if (type->tp_new == NULL) {
161 PyErr_Format(PyExc_TypeError,
162 "cannot create '%.100s' instances",
163 type->tp_name);
164 return NULL;
165 }
166
Tim Peters3f996e72001-09-13 19:18:27 +0000167 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000168 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000169 /* Ugly exception: when the call was type(something),
170 don't call tp_init on the result. */
171 if (type == &PyType_Type &&
172 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
173 (kwds == NULL ||
174 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
175 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000176 /* If the returned object is not an instance of type,
177 it won't be initialized. */
178 if (!PyType_IsSubtype(obj->ob_type, type))
179 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000180 type = obj->ob_type;
181 if (type->tp_init != NULL &&
182 type->tp_init(obj, args, kwds) < 0) {
183 Py_DECREF(obj);
184 obj = NULL;
185 }
186 }
187 return obj;
188}
189
190PyObject *
191PyType_GenericAlloc(PyTypeObject *type, int nitems)
192{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000193 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000194 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000195
196 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000197 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000198 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000199 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000200
Neil Schemenauerc806c882001-08-29 23:54:54 +0000201 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000203
Neil Schemenauerc806c882001-08-29 23:54:54 +0000204 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000205
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
207 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000208
Tim Peters6d6c1a32001-08-02 04:15:00 +0000209 if (type->tp_itemsize == 0)
210 PyObject_INIT(obj, type);
211 else
212 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000213
Tim Peters6d6c1a32001-08-02 04:15:00 +0000214 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000215 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000216 return obj;
217}
218
219PyObject *
220PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
221{
222 return type->tp_alloc(type, 0);
223}
224
Guido van Rossum9475a232001-10-05 20:51:39 +0000225/* Helpers for subtyping */
226
227static int
228subtype_traverse(PyObject *self, visitproc visit, void *arg)
229{
230 PyTypeObject *type, *base;
231 traverseproc f;
232 int err;
233
234 /* Find the nearest base with a different tp_traverse */
235 type = self->ob_type;
236 base = type->tp_base;
237 while ((f = base->tp_traverse) == subtype_traverse) {
238 base = base->tp_base;
239 assert(base);
240 }
241
242 if (type->tp_dictoffset != base->tp_dictoffset) {
243 PyObject **dictptr = _PyObject_GetDictPtr(self);
244 if (dictptr && *dictptr) {
245 err = visit(*dictptr, arg);
246 if (err)
247 return err;
248 }
249 }
250
251 if (f)
252 return f(self, visit, arg);
253 return 0;
254}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000255
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000256staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
257
258static int
259call_finalizer(PyObject *self)
260{
261 static PyObject *del_str = NULL;
262 PyObject *del, *res;
263 PyObject *error_type, *error_value, *error_traceback;
264
265 /* Temporarily resurrect the object. */
266#ifdef Py_TRACE_REFS
267#ifndef Py_REF_DEBUG
268# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
269#endif
270 /* much too complicated if Py_TRACE_REFS defined */
271 _Py_NewReference((PyObject *)self);
272#ifdef COUNT_ALLOCS
273 /* compensate for boost in _Py_NewReference; note that
274 * _Py_RefTotal was also boosted; we'll knock that down later.
275 */
276 self->ob_type->tp_allocs--;
277#endif
278#else /* !Py_TRACE_REFS */
279 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
280 Py_INCREF(self);
281#endif /* !Py_TRACE_REFS */
282
283 /* Save the current exception, if any. */
284 PyErr_Fetch(&error_type, &error_value, &error_traceback);
285
286 /* Execute __del__ method, if any. */
287 del = lookup_maybe(self, "__del__", &del_str);
288 if (del != NULL) {
289 res = PyEval_CallObject(del, NULL);
290 if (res == NULL)
291 PyErr_WriteUnraisable(del);
292 else
293 Py_DECREF(res);
294 Py_DECREF(del);
295 }
296
297 /* Restore the saved exception. */
298 PyErr_Restore(error_type, error_value, error_traceback);
299
300 /* Undo the temporary resurrection; can't use DECREF here, it would
301 * cause a recursive call.
302 */
303#ifdef Py_REF_DEBUG
304 /* _Py_RefTotal was boosted either by _Py_NewReference or
305 * Py_INCREF above.
306 */
307 _Py_RefTotal--;
308#endif
309 if (--self->ob_refcnt > 0) {
310#ifdef COUNT_ALLOCS
311 self->ob_type->tp_frees--;
312#endif
313 _PyObject_GC_TRACK(self);
314 return -1; /* __del__ added a reference; don't delete now */
315 }
316#ifdef Py_TRACE_REFS
317 _Py_ForgetReference((PyObject *)self);
318#ifdef COUNT_ALLOCS
319 /* compensate for increment in _Py_ForgetReference */
320 self->ob_type->tp_frees--;
321#endif
322#endif
323
324 return 0;
325}
326
Tim Peters6d6c1a32001-08-02 04:15:00 +0000327static void
328subtype_dealloc(PyObject *self)
329{
Guido van Rossum14227b42001-12-06 02:35:58 +0000330 PyTypeObject *type, *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000331 destructor f;
332
333 /* This exists so we can DECREF self->ob_type */
334
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000335 if (call_finalizer(self) < 0)
336 return;
337
Tim Peters6d6c1a32001-08-02 04:15:00 +0000338 /* Find the nearest base with a different tp_dealloc */
339 type = self->ob_type;
Guido van Rossum14227b42001-12-06 02:35:58 +0000340 base = type->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000341 while ((f = base->tp_dealloc) == subtype_dealloc) {
342 base = base->tp_base;
343 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000344 }
345
346 /* Clear __slots__ variables */
347 if (type->tp_basicsize != base->tp_basicsize &&
348 type->tp_itemsize == 0)
349 {
350 char *addr = ((char *)self);
351 char *p = addr + base->tp_basicsize;
352 char *q = addr + type->tp_basicsize;
353 for (; p < q; p += sizeof(PyObject *)) {
354 PyObject **pp;
355 if (p == addr + type->tp_dictoffset ||
356 p == addr + type->tp_weaklistoffset)
357 continue;
358 pp = (PyObject **)p;
359 if (*pp != NULL) {
360 Py_DECREF(*pp);
361 *pp = NULL;
Guido van Rossum33bab012001-12-05 22:45:48 +0000362 }
363 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000364 }
365
366 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000367 if (type->tp_dictoffset && !base->tp_dictoffset) {
368 PyObject **dictptr = _PyObject_GetDictPtr(self);
369 if (dictptr != NULL) {
370 PyObject *dict = *dictptr;
371 if (dict != NULL) {
372 Py_DECREF(dict);
373 *dictptr = NULL;
374 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375 }
376 }
377
Guido van Rossum9676b222001-08-17 20:32:36 +0000378 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000379 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000380 PyObject_ClearWeakRefs(self);
381
Tim Peters6d6c1a32001-08-02 04:15:00 +0000382 /* Finalize GC if the base doesn't do GC and we do */
383 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000384 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000385
386 /* Call the base tp_dealloc() */
387 assert(f);
388 f(self);
389
390 /* Can't reference self beyond this point */
391 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
392 Py_DECREF(type);
393 }
394}
395
Tim Peters6d6c1a32001-08-02 04:15:00 +0000396staticforward PyTypeObject *solid_base(PyTypeObject *type);
397
398typedef struct {
399 PyTypeObject type;
400 PyNumberMethods as_number;
401 PySequenceMethods as_sequence;
402 PyMappingMethods as_mapping;
403 PyBufferProcs as_buffer;
404 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000405 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000406} etype;
407
408/* type test with subclassing support */
409
410int
411PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
412{
413 PyObject *mro;
414
Guido van Rossum9478d072001-09-07 18:52:13 +0000415 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
416 return b == a || b == &PyBaseObject_Type;
417
Tim Peters6d6c1a32001-08-02 04:15:00 +0000418 mro = a->tp_mro;
419 if (mro != NULL) {
420 /* Deal with multiple inheritance without recursion
421 by walking the MRO tuple */
422 int i, n;
423 assert(PyTuple_Check(mro));
424 n = PyTuple_GET_SIZE(mro);
425 for (i = 0; i < n; i++) {
426 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
427 return 1;
428 }
429 return 0;
430 }
431 else {
432 /* a is not completely initilized yet; follow tp_base */
433 do {
434 if (a == b)
435 return 1;
436 a = a->tp_base;
437 } while (a != NULL);
438 return b == &PyBaseObject_Type;
439 }
440}
441
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000442/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000443 without looking in the instance dictionary
444 (so we can't use PyObject_GetAttr) but still binding
445 it to the instance. The arguments are the object,
446 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000447 static variable used to cache the interned Python string.
448
449 Two variants:
450
451 - lookup_maybe() returns NULL without raising an exception
452 when the _PyType_Lookup() call fails;
453
454 - lookup_method() always raises an exception upon errors.
455*/
Guido van Rossum60718732001-08-28 17:47:51 +0000456
457static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000458lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000459{
460 PyObject *res;
461
462 if (*attrobj == NULL) {
463 *attrobj = PyString_InternFromString(attrstr);
464 if (*attrobj == NULL)
465 return NULL;
466 }
467 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000468 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000469 descrgetfunc f;
470 if ((f = res->ob_type->tp_descr_get) == NULL)
471 Py_INCREF(res);
472 else
473 res = f(res, self, (PyObject *)(self->ob_type));
474 }
475 return res;
476}
477
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000478static PyObject *
479lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
480{
481 PyObject *res = lookup_maybe(self, attrstr, attrobj);
482 if (res == NULL && !PyErr_Occurred())
483 PyErr_SetObject(PyExc_AttributeError, *attrobj);
484 return res;
485}
486
Guido van Rossum2730b132001-08-28 18:22:14 +0000487/* A variation of PyObject_CallMethod that uses lookup_method()
488 instead of PyObject_GetAttrString(). This uses the same convention
489 as lookup_method to cache the interned name string object. */
490
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000491static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000492call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
493{
494 va_list va;
495 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000496 va_start(va, format);
497
Guido van Rossumda21c012001-10-03 00:50:18 +0000498 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000499 if (func == NULL) {
500 va_end(va);
501 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000502 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000503 return NULL;
504 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000505
506 if (format && *format)
507 args = Py_VaBuildValue(format, va);
508 else
509 args = PyTuple_New(0);
510
511 va_end(va);
512
513 if (args == NULL)
514 return NULL;
515
516 assert(PyTuple_Check(args));
517 retval = PyObject_Call(func, args, NULL);
518
519 Py_DECREF(args);
520 Py_DECREF(func);
521
522 return retval;
523}
524
525/* Clone of call_method() that returns NotImplemented when the lookup fails. */
526
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000527static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000528call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
529{
530 va_list va;
531 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000532 va_start(va, format);
533
Guido van Rossumda21c012001-10-03 00:50:18 +0000534 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000535 if (func == NULL) {
536 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000537 if (!PyErr_Occurred()) {
538 Py_INCREF(Py_NotImplemented);
539 return Py_NotImplemented;
540 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000541 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000542 }
543
544 if (format && *format)
545 args = Py_VaBuildValue(format, va);
546 else
547 args = PyTuple_New(0);
548
549 va_end(va);
550
Guido van Rossum717ce002001-09-14 16:58:08 +0000551 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000552 return NULL;
553
Guido van Rossum717ce002001-09-14 16:58:08 +0000554 assert(PyTuple_Check(args));
555 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000556
557 Py_DECREF(args);
558 Py_DECREF(func);
559
560 return retval;
561}
562
Tim Peters6d6c1a32001-08-02 04:15:00 +0000563/* Method resolution order algorithm from "Putting Metaclasses to Work"
564 by Forman and Danforth (Addison-Wesley 1999). */
565
566static int
567conservative_merge(PyObject *left, PyObject *right)
568{
569 int left_size;
570 int right_size;
571 int i, j, r, ok;
572 PyObject *temp, *rr;
573
574 assert(PyList_Check(left));
575 assert(PyList_Check(right));
576
577 again:
578 left_size = PyList_GET_SIZE(left);
579 right_size = PyList_GET_SIZE(right);
580 for (i = 0; i < left_size; i++) {
581 for (j = 0; j < right_size; j++) {
582 if (PyList_GET_ITEM(left, i) ==
583 PyList_GET_ITEM(right, j)) {
584 /* found a merge point */
585 temp = PyList_New(0);
586 if (temp == NULL)
587 return -1;
588 for (r = 0; r < j; r++) {
589 rr = PyList_GET_ITEM(right, r);
590 ok = PySequence_Contains(left, rr);
591 if (ok < 0) {
592 Py_DECREF(temp);
593 return -1;
594 }
595 if (!ok) {
596 ok = PyList_Append(temp, rr);
597 if (ok < 0) {
598 Py_DECREF(temp);
599 return -1;
600 }
601 }
602 }
603 ok = PyList_SetSlice(left, i, i, temp);
604 Py_DECREF(temp);
605 if (ok < 0)
606 return -1;
607 ok = PyList_SetSlice(right, 0, j+1, NULL);
608 if (ok < 0)
609 return -1;
610 goto again;
611 }
612 }
613 }
614 return PyList_SetSlice(left, left_size, left_size, right);
615}
616
617static int
618serious_order_disagreements(PyObject *left, PyObject *right)
619{
620 return 0; /* XXX later -- for now, we cheat: "don't do that" */
621}
622
Tim Petersa91e9642001-11-14 23:32:33 +0000623static int
624fill_classic_mro(PyObject *mro, PyObject *cls)
625{
626 PyObject *bases, *base;
627 int i, n;
628
629 assert(PyList_Check(mro));
630 assert(PyClass_Check(cls));
631 i = PySequence_Contains(mro, cls);
632 if (i < 0)
633 return -1;
634 if (!i) {
635 if (PyList_Append(mro, cls) < 0)
636 return -1;
637 }
638 bases = ((PyClassObject *)cls)->cl_bases;
639 assert(bases && PyTuple_Check(bases));
640 n = PyTuple_GET_SIZE(bases);
641 for (i = 0; i < n; i++) {
642 base = PyTuple_GET_ITEM(bases, i);
643 if (fill_classic_mro(mro, base) < 0)
644 return -1;
645 }
646 return 0;
647}
648
649static PyObject *
650classic_mro(PyObject *cls)
651{
652 PyObject *mro;
653
654 assert(PyClass_Check(cls));
655 mro = PyList_New(0);
656 if (mro != NULL) {
657 if (fill_classic_mro(mro, cls) == 0)
658 return mro;
659 Py_DECREF(mro);
660 }
661 return NULL;
662}
663
Tim Peters6d6c1a32001-08-02 04:15:00 +0000664static PyObject *
665mro_implementation(PyTypeObject *type)
666{
667 int i, n, ok;
668 PyObject *bases, *result;
669
670 bases = type->tp_bases;
671 n = PyTuple_GET_SIZE(bases);
672 result = Py_BuildValue("[O]", (PyObject *)type);
673 if (result == NULL)
674 return NULL;
675 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000676 PyObject *base = PyTuple_GET_ITEM(bases, i);
677 PyObject *parentMRO;
678 if (PyType_Check(base))
679 parentMRO = PySequence_List(
680 ((PyTypeObject*)base)->tp_mro);
681 else
682 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683 if (parentMRO == NULL) {
684 Py_DECREF(result);
685 return NULL;
686 }
687 if (serious_order_disagreements(result, parentMRO)) {
688 Py_DECREF(result);
689 return NULL;
690 }
691 ok = conservative_merge(result, parentMRO);
692 Py_DECREF(parentMRO);
693 if (ok < 0) {
694 Py_DECREF(result);
695 return NULL;
696 }
697 }
698 return result;
699}
700
701static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000702mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000703{
704 PyTypeObject *type = (PyTypeObject *)self;
705
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706 return mro_implementation(type);
707}
708
709static int
710mro_internal(PyTypeObject *type)
711{
712 PyObject *mro, *result, *tuple;
713
714 if (type->ob_type == &PyType_Type) {
715 result = mro_implementation(type);
716 }
717 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000718 static PyObject *mro_str;
719 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000720 if (mro == NULL)
721 return -1;
722 result = PyObject_CallObject(mro, NULL);
723 Py_DECREF(mro);
724 }
725 if (result == NULL)
726 return -1;
727 tuple = PySequence_Tuple(result);
728 Py_DECREF(result);
729 type->tp_mro = tuple;
730 return 0;
731}
732
733
734/* Calculate the best base amongst multiple base classes.
735 This is the first one that's on the path to the "solid base". */
736
737static PyTypeObject *
738best_base(PyObject *bases)
739{
740 int i, n;
741 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000742 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000743
744 assert(PyTuple_Check(bases));
745 n = PyTuple_GET_SIZE(bases);
746 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000747 base = NULL;
748 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000749 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000750 base_proto = PyTuple_GET_ITEM(bases, i);
751 if (PyClass_Check(base_proto))
752 continue;
753 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000754 PyErr_SetString(
755 PyExc_TypeError,
756 "bases must be types");
757 return NULL;
758 }
Tim Petersa91e9642001-11-14 23:32:33 +0000759 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000760 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000761 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762 return NULL;
763 }
764 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000765 if (winner == NULL) {
766 winner = candidate;
767 base = base_i;
768 }
769 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000770 ;
771 else if (PyType_IsSubtype(candidate, winner)) {
772 winner = candidate;
773 base = base_i;
774 }
775 else {
776 PyErr_SetString(
777 PyExc_TypeError,
778 "multiple bases have "
779 "instance lay-out conflict");
780 return NULL;
781 }
782 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000783 if (base == NULL)
784 PyErr_SetString(PyExc_TypeError,
785 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786 return base;
787}
788
789static int
790extra_ivars(PyTypeObject *type, PyTypeObject *base)
791{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000792 size_t t_size = type->tp_basicsize;
793 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000794
Guido van Rossum9676b222001-08-17 20:32:36 +0000795 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000796 if (type->tp_itemsize || base->tp_itemsize) {
797 /* If itemsize is involved, stricter rules */
798 return t_size != b_size ||
799 type->tp_itemsize != base->tp_itemsize;
800 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000801 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
802 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
803 t_size -= sizeof(PyObject *);
804 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
805 type->tp_dictoffset + sizeof(PyObject *) == t_size)
806 t_size -= sizeof(PyObject *);
807
808 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809}
810
811static PyTypeObject *
812solid_base(PyTypeObject *type)
813{
814 PyTypeObject *base;
815
816 if (type->tp_base)
817 base = solid_base(type->tp_base);
818 else
819 base = &PyBaseObject_Type;
820 if (extra_ivars(type, base))
821 return type;
822 else
823 return base;
824}
825
826staticforward void object_dealloc(PyObject *);
827staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000828staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000829staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830
831static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000832subtype_dict(PyObject *obj, void *context)
833{
834 PyObject **dictptr = _PyObject_GetDictPtr(obj);
835 PyObject *dict;
836
837 if (dictptr == NULL) {
838 PyErr_SetString(PyExc_AttributeError,
839 "This object has no __dict__");
840 return NULL;
841 }
842 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000843 if (dict == NULL)
844 *dictptr = dict = PyDict_New();
845 Py_XINCREF(dict);
846 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000847}
848
Guido van Rossum6661be32001-10-26 04:26:12 +0000849static int
850subtype_setdict(PyObject *obj, PyObject *value, void *context)
851{
852 PyObject **dictptr = _PyObject_GetDictPtr(obj);
853 PyObject *dict;
854
855 if (dictptr == NULL) {
856 PyErr_SetString(PyExc_AttributeError,
857 "This object has no __dict__");
858 return -1;
859 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000860 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000861 PyErr_SetString(PyExc_TypeError,
862 "__dict__ must be set to a dictionary");
863 return -1;
864 }
865 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000866 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000867 *dictptr = value;
868 Py_XDECREF(dict);
869 return 0;
870}
871
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000872static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000873 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000874 {0},
875};
876
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000877/* bozo: __getstate__ that raises TypeError */
878
879static PyObject *
880bozo_func(PyObject *self, PyObject *args)
881{
882 PyErr_SetString(PyExc_TypeError,
883 "a class that defines __slots__ without "
884 "defining __getstate__ cannot be pickled");
885 return NULL;
886}
887
Neal Norwitz93c1e232002-03-31 16:06:11 +0000888static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000889
890static PyObject *bozo_obj = NULL;
891
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000892static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000893type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
894{
895 PyObject *name, *bases, *dict;
896 static char *kwlist[] = {"name", "bases", "dict", 0};
897 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000898 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000899 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000900 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000901 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000902
Tim Peters3abca122001-10-27 19:37:48 +0000903 assert(args != NULL && PyTuple_Check(args));
904 assert(kwds == NULL || PyDict_Check(kwds));
905
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000906 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000907 {
908 const int nargs = PyTuple_GET_SIZE(args);
909 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
910
911 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
912 PyObject *x = PyTuple_GET_ITEM(args, 0);
913 Py_INCREF(x->ob_type);
914 return (PyObject *) x->ob_type;
915 }
916
917 /* SF bug 475327 -- if that didn't trigger, we need 3
918 arguments. but PyArg_ParseTupleAndKeywords below may give
919 a msg saying type() needs exactly 3. */
920 if (nargs + nkwds != 3) {
921 PyErr_SetString(PyExc_TypeError,
922 "type() takes 1 or 3 arguments");
923 return NULL;
924 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000925 }
926
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000927 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000928 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
929 &name,
930 &PyTuple_Type, &bases,
931 &PyDict_Type, &dict))
932 return NULL;
933
934 /* Determine the proper metatype to deal with this,
935 and check for metatype conflicts while we're at it.
936 Note that if some other metatype wins to contract,
937 it's possible that its instances are not types. */
938 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000939 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000940 for (i = 0; i < nbases; i++) {
941 tmp = PyTuple_GET_ITEM(bases, i);
942 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000943 if (tmptype == &PyClass_Type)
944 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000945 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000946 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000947 if (PyType_IsSubtype(tmptype, winner)) {
948 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000949 continue;
950 }
951 PyErr_SetString(PyExc_TypeError,
952 "metatype conflict among bases");
953 return NULL;
954 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000955 if (winner != metatype) {
956 if (winner->tp_new != type_new) /* Pass it to the winner */
957 return winner->tp_new(winner, args, kwds);
958 metatype = winner;
959 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960
961 /* Adjust for empty tuple bases */
962 if (nbases == 0) {
963 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
964 if (bases == NULL)
965 return NULL;
966 nbases = 1;
967 }
968 else
969 Py_INCREF(bases);
970
971 /* XXX From here until type is allocated, "return NULL" leaks bases! */
972
973 /* Calculate best base, and check that all bases are type objects */
974 base = best_base(bases);
975 if (base == NULL)
976 return NULL;
977 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
978 PyErr_Format(PyExc_TypeError,
979 "type '%.100s' is not an acceptable base type",
980 base->tp_name);
981 return NULL;
982 }
983
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984 /* Check for a __slots__ sequence variable in dict, and count it */
985 slots = PyDict_GetItemString(dict, "__slots__");
986 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000987 add_dict = 0;
988 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989 if (slots != NULL) {
990 /* Make it into a tuple */
991 if (PyString_Check(slots))
992 slots = Py_BuildValue("(O)", slots);
993 else
994 slots = PySequence_Tuple(slots);
995 if (slots == NULL)
996 return NULL;
997 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000998 if (nslots > 0 && base->tp_itemsize != 0) {
999 PyErr_Format(PyExc_TypeError,
1000 "nonempty __slots__ "
1001 "not supported for subtype of '%s'",
1002 base->tp_name);
1003 return NULL;
1004 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 for (i = 0; i < nslots; i++) {
1006 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
1007 PyErr_SetString(PyExc_TypeError,
1008 "__slots__ must be a sequence of strings");
1009 Py_DECREF(slots);
1010 return NULL;
1011 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001012 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013 }
1014 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001015 if (slots != NULL) {
1016 /* See if *this* class defines __getstate__ */
1017 PyObject *getstate = PyDict_GetItemString(dict,
1018 "__getstate__");
1019 if (getstate == NULL) {
1020 /* If not, provide a bozo that raises TypeError */
1021 if (bozo_obj == NULL) {
1022 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1023 if (bozo_obj == NULL) {
1024 /* XXX decref various things */
1025 return NULL;
1026 }
1027 }
1028 if (PyDict_SetItemString(dict,
1029 "__getstate__",
1030 bozo_obj) < 0) {
1031 /* XXX decref various things */
1032 return NULL;
1033 }
1034 }
1035 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036 if (slots == NULL && base->tp_dictoffset == 0 &&
1037 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001038 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001039 add_dict++;
1040 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001041 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1042 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001043 nslots++;
1044 add_weak++;
1045 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046
1047 /* XXX From here until type is safely allocated,
1048 "return NULL" may leak slots! */
1049
1050 /* Allocate the type object */
1051 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1052 if (type == NULL)
1053 return NULL;
1054
1055 /* Keep name and slots alive in the extended type object */
1056 et = (etype *)type;
1057 Py_INCREF(name);
1058 et->name = name;
1059 et->slots = slots;
1060
Guido van Rossumdc91b992001-08-08 22:26:22 +00001061 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001062 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1063 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001064 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1065 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001066
1067 /* It's a new-style number unless it specifically inherits any
1068 old-style numeric behavior */
1069 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1070 (base->tp_as_number == NULL))
1071 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1072
1073 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074 type->tp_as_number = &et->as_number;
1075 type->tp_as_sequence = &et->as_sequence;
1076 type->tp_as_mapping = &et->as_mapping;
1077 type->tp_as_buffer = &et->as_buffer;
1078 type->tp_name = PyString_AS_STRING(name);
1079
1080 /* Set tp_base and tp_bases */
1081 type->tp_bases = bases;
1082 Py_INCREF(base);
1083 type->tp_base = base;
1084
Guido van Rossum687ae002001-10-15 22:03:32 +00001085 /* Initialize tp_dict from passed-in dict */
1086 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 if (dict == NULL) {
1088 Py_DECREF(type);
1089 return NULL;
1090 }
1091
Guido van Rossumc3542212001-08-16 09:18:56 +00001092 /* Set __module__ in the dict */
1093 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1094 tmp = PyEval_GetGlobals();
1095 if (tmp != NULL) {
1096 tmp = PyDict_GetItemString(tmp, "__name__");
1097 if (tmp != NULL) {
1098 if (PyDict_SetItemString(dict, "__module__",
1099 tmp) < 0)
1100 return NULL;
1101 }
1102 }
1103 }
1104
Tim Peters2f93e282001-10-04 05:27:00 +00001105 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001106 and is a string. The __doc__ accessor will first look for tp_doc;
1107 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001108 */
1109 {
1110 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1111 if (doc != NULL && PyString_Check(doc)) {
1112 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001113 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001114 if (type->tp_doc == NULL) {
1115 Py_DECREF(type);
1116 return NULL;
1117 }
1118 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1119 }
1120 }
1121
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 /* Special-case __new__: if it's a plain function,
1123 make it a static function */
1124 tmp = PyDict_GetItemString(dict, "__new__");
1125 if (tmp != NULL && PyFunction_Check(tmp)) {
1126 tmp = PyStaticMethod_New(tmp);
1127 if (tmp == NULL) {
1128 Py_DECREF(type);
1129 return NULL;
1130 }
1131 PyDict_SetItemString(dict, "__new__", tmp);
1132 Py_DECREF(tmp);
1133 }
1134
1135 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1136 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001137 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138 if (slots != NULL) {
1139 for (i = 0; i < nslots; i++, mp++) {
1140 mp->name = PyString_AS_STRING(
1141 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001142 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001143 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001144 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001145 strcmp(mp->name, "__weakref__") == 0) {
1146 mp->type = T_OBJECT;
Guido van Rossum9676b222001-08-17 20:32:36 +00001147 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001148 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 slotoffset += sizeof(PyObject *);
1150 }
1151 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001152 else {
1153 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001154 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001155 type->tp_dictoffset =
1156 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001157 else
1158 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001159 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001160 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001161 }
1162 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001163 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001164 type->tp_weaklistoffset = slotoffset;
1165 mp->name = "__weakref__";
1166 mp->type = T_OBJECT;
1167 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001168 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001169 mp++;
1170 slotoffset += sizeof(PyObject *);
1171 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001172 }
1173 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001174 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001175 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176
1177 /* Special case some slots */
1178 if (type->tp_dictoffset != 0 || nslots > 0) {
1179 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1180 type->tp_getattro = PyObject_GenericGetAttr;
1181 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1182 type->tp_setattro = PyObject_GenericSetAttr;
1183 }
1184 type->tp_dealloc = subtype_dealloc;
1185
Guido van Rossum9475a232001-10-05 20:51:39 +00001186 /* Enable GC unless there are really no instance variables possible */
1187 if (!(type->tp_basicsize == sizeof(PyObject) &&
1188 type->tp_itemsize == 0))
1189 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1190
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191 /* Always override allocation strategy to use regular heap */
1192 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001193 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001194 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001195 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001196 type->tp_clear = base->tp_clear;
1197 }
1198 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001199 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200
1201 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001202 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 Py_DECREF(type);
1204 return NULL;
1205 }
1206
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001207 /* Put the proper slots in place */
1208 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001209
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 return (PyObject *)type;
1211}
1212
1213/* Internal API to look for a name through the MRO.
1214 This returns a borrowed reference, and doesn't set an exception! */
1215PyObject *
1216_PyType_Lookup(PyTypeObject *type, PyObject *name)
1217{
1218 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001219 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220
Guido van Rossum687ae002001-10-15 22:03:32 +00001221 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001222 mro = type->tp_mro;
1223 assert(PyTuple_Check(mro));
1224 n = PyTuple_GET_SIZE(mro);
1225 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001226 base = PyTuple_GET_ITEM(mro, i);
1227 if (PyClass_Check(base))
1228 dict = ((PyClassObject *)base)->cl_dict;
1229 else {
1230 assert(PyType_Check(base));
1231 dict = ((PyTypeObject *)base)->tp_dict;
1232 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233 assert(dict && PyDict_Check(dict));
1234 res = PyDict_GetItem(dict, name);
1235 if (res != NULL)
1236 return res;
1237 }
1238 return NULL;
1239}
1240
1241/* This is similar to PyObject_GenericGetAttr(),
1242 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1243static PyObject *
1244type_getattro(PyTypeObject *type, PyObject *name)
1245{
1246 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001247 PyObject *meta_attribute, *attribute;
1248 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249
1250 /* Initialize this type (we'll assume the metatype is initialized) */
1251 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001252 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 return NULL;
1254 }
1255
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001256 /* No readable descriptor found yet */
1257 meta_get = NULL;
1258
1259 /* Look for the attribute in the metatype */
1260 meta_attribute = _PyType_Lookup(metatype, name);
1261
1262 if (meta_attribute != NULL) {
1263 meta_get = meta_attribute->ob_type->tp_descr_get;
1264
1265 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1266 /* Data descriptors implement tp_descr_set to intercept
1267 * writes. Assume the attribute is not overridden in
1268 * type's tp_dict (and bases): call the descriptor now.
1269 */
1270 return meta_get(meta_attribute, (PyObject *)type,
1271 (PyObject *)metatype);
1272 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 }
1274
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001275 /* No data descriptor found on metatype. Look in tp_dict of this
1276 * type and its bases */
1277 attribute = _PyType_Lookup(type, name);
1278 if (attribute != NULL) {
1279 /* Implement descriptor functionality, if any */
1280 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1281 if (local_get != NULL) {
1282 /* NULL 2nd argument indicates the descriptor was
1283 * found on the target object itself (or a base) */
1284 return local_get(attribute, (PyObject *)NULL,
1285 (PyObject *)type);
1286 }
1287
1288 Py_INCREF(attribute);
1289 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001290 }
1291
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001292 /* No attribute found in local __dict__ (or bases): use the
1293 * descriptor from the metatype, if any */
1294 if (meta_get != NULL)
1295 return meta_get(meta_attribute, (PyObject *)type,
1296 (PyObject *)metatype);
1297
1298 /* If an ordinary attribute was found on the metatype, return it now */
1299 if (meta_attribute != NULL) {
1300 Py_INCREF(meta_attribute);
1301 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302 }
1303
1304 /* Give up */
1305 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001306 "type object '%.50s' has no attribute '%.400s'",
1307 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308 return NULL;
1309}
1310
1311static int
1312type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1313{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001314 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1315 PyErr_Format(
1316 PyExc_TypeError,
1317 "can't set attributes of built-in/extension type '%s'",
1318 type->tp_name);
1319 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001320 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001321 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1322 return -1;
1323 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324}
1325
1326static void
1327type_dealloc(PyTypeObject *type)
1328{
1329 etype *et;
1330
1331 /* Assert this is a heap-allocated type object */
1332 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001333 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001334 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 et = (etype *)type;
1336 Py_XDECREF(type->tp_base);
1337 Py_XDECREF(type->tp_dict);
1338 Py_XDECREF(type->tp_bases);
1339 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001340 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001341 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342 Py_XDECREF(et->name);
1343 Py_XDECREF(et->slots);
1344 type->ob_type->tp_free((PyObject *)type);
1345}
1346
Guido van Rossum1c450732001-10-08 15:18:27 +00001347static PyObject *
1348type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1349{
1350 PyObject *list, *raw, *ref;
1351 int i, n;
1352
1353 list = PyList_New(0);
1354 if (list == NULL)
1355 return NULL;
1356 raw = type->tp_subclasses;
1357 if (raw == NULL)
1358 return list;
1359 assert(PyList_Check(raw));
1360 n = PyList_GET_SIZE(raw);
1361 for (i = 0; i < n; i++) {
1362 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001363 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001364 ref = PyWeakref_GET_OBJECT(ref);
1365 if (ref != Py_None) {
1366 if (PyList_Append(list, ref) < 0) {
1367 Py_DECREF(list);
1368 return NULL;
1369 }
1370 }
1371 }
1372 return list;
1373}
1374
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001376 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001378 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1379 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 {0}
1381};
1382
1383static char type_doc[] =
1384"type(object) -> the object's type\n"
1385"type(name, bases, dict) -> a new type";
1386
Guido van Rossum048eb752001-10-02 21:24:57 +00001387static int
1388type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1389{
1390 etype *et;
1391 int err;
1392
1393 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1394 return 0;
1395
1396 et = (etype *)type;
1397
1398#define VISIT(SLOT) \
1399 if (SLOT) { \
1400 err = visit((PyObject *)(SLOT), arg); \
1401 if (err) \
1402 return err; \
1403 }
1404
1405 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001406 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001407 VISIT(type->tp_mro);
1408 VISIT(type->tp_bases);
1409 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001410 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001411 VISIT(et->slots);
1412
1413#undef VISIT
1414
1415 return 0;
1416}
1417
1418static int
1419type_clear(PyTypeObject *type)
1420{
1421 etype *et;
1422 PyObject *tmp;
1423
1424 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1425 return 0;
1426
1427 et = (etype *)type;
1428
1429#define CLEAR(SLOT) \
1430 if (SLOT) { \
1431 tmp = (PyObject *)(SLOT); \
1432 SLOT = NULL; \
1433 Py_DECREF(tmp); \
1434 }
1435
1436 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001437 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001438 CLEAR(type->tp_mro);
1439 CLEAR(type->tp_bases);
1440 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001441 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001442 CLEAR(et->slots);
1443
Tim Peters2f93e282001-10-04 05:27:00 +00001444 if (type->tp_doc != NULL) {
1445 PyObject_FREE(type->tp_doc);
1446 type->tp_doc = NULL;
1447 }
1448
Guido van Rossum048eb752001-10-02 21:24:57 +00001449#undef CLEAR
1450
1451 return 0;
1452}
1453
1454static int
1455type_is_gc(PyTypeObject *type)
1456{
1457 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1458}
1459
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001460PyTypeObject PyType_Type = {
1461 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001462 0, /* ob_size */
1463 "type", /* tp_name */
1464 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001465 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466 (destructor)type_dealloc, /* tp_dealloc */
1467 0, /* tp_print */
1468 0, /* tp_getattr */
1469 0, /* tp_setattr */
1470 type_compare, /* tp_compare */
1471 (reprfunc)type_repr, /* tp_repr */
1472 0, /* tp_as_number */
1473 0, /* tp_as_sequence */
1474 0, /* tp_as_mapping */
1475 (hashfunc)_Py_HashPointer, /* tp_hash */
1476 (ternaryfunc)type_call, /* tp_call */
1477 0, /* tp_str */
1478 (getattrofunc)type_getattro, /* tp_getattro */
1479 (setattrofunc)type_setattro, /* tp_setattro */
1480 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001481 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1482 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001483 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001484 (traverseproc)type_traverse, /* tp_traverse */
1485 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001487 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 0, /* tp_iter */
1489 0, /* tp_iternext */
1490 type_methods, /* tp_methods */
1491 type_members, /* tp_members */
1492 type_getsets, /* tp_getset */
1493 0, /* tp_base */
1494 0, /* tp_dict */
1495 0, /* tp_descr_get */
1496 0, /* tp_descr_set */
1497 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1498 0, /* tp_init */
1499 0, /* tp_alloc */
1500 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001501 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001502 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001503};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504
1505
1506/* The base type of all types (eventually)... except itself. */
1507
1508static int
1509object_init(PyObject *self, PyObject *args, PyObject *kwds)
1510{
1511 return 0;
1512}
1513
1514static void
1515object_dealloc(PyObject *self)
1516{
1517 self->ob_type->tp_free(self);
1518}
1519
Guido van Rossum8e248182001-08-12 05:17:56 +00001520static PyObject *
1521object_repr(PyObject *self)
1522{
Guido van Rossum76e69632001-08-16 18:52:43 +00001523 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001524 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001525
Guido van Rossum76e69632001-08-16 18:52:43 +00001526 type = self->ob_type;
1527 mod = type_module(type, NULL);
1528 if (mod == NULL)
1529 PyErr_Clear();
1530 else if (!PyString_Check(mod)) {
1531 Py_DECREF(mod);
1532 mod = NULL;
1533 }
1534 name = type_name(type, NULL);
1535 if (name == NULL)
1536 return NULL;
1537 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001538 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001539 PyString_AS_STRING(mod),
1540 PyString_AS_STRING(name),
1541 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001542 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001543 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001544 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001545 Py_XDECREF(mod);
1546 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001547 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001548}
1549
Guido van Rossumb8f63662001-08-15 23:57:02 +00001550static PyObject *
1551object_str(PyObject *self)
1552{
1553 unaryfunc f;
1554
1555 f = self->ob_type->tp_repr;
1556 if (f == NULL)
1557 f = object_repr;
1558 return f(self);
1559}
1560
Guido van Rossum8e248182001-08-12 05:17:56 +00001561static long
1562object_hash(PyObject *self)
1563{
1564 return _Py_HashPointer(self);
1565}
Guido van Rossum8e248182001-08-12 05:17:56 +00001566
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001567static PyObject *
1568object_get_class(PyObject *self, void *closure)
1569{
1570 Py_INCREF(self->ob_type);
1571 return (PyObject *)(self->ob_type);
1572}
1573
1574static int
1575equiv_structs(PyTypeObject *a, PyTypeObject *b)
1576{
1577 return a == b ||
1578 (a != NULL &&
1579 b != NULL &&
1580 a->tp_basicsize == b->tp_basicsize &&
1581 a->tp_itemsize == b->tp_itemsize &&
1582 a->tp_dictoffset == b->tp_dictoffset &&
1583 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1584 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1585 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1586}
1587
1588static int
1589same_slots_added(PyTypeObject *a, PyTypeObject *b)
1590{
1591 PyTypeObject *base = a->tp_base;
1592 int size;
1593
1594 if (base != b->tp_base)
1595 return 0;
1596 if (equiv_structs(a, base) && equiv_structs(b, base))
1597 return 1;
1598 size = base->tp_basicsize;
1599 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1600 size += sizeof(PyObject *);
1601 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1602 size += sizeof(PyObject *);
1603 return size == a->tp_basicsize && size == b->tp_basicsize;
1604}
1605
1606static int
1607object_set_class(PyObject *self, PyObject *value, void *closure)
1608{
1609 PyTypeObject *old = self->ob_type;
1610 PyTypeObject *new, *newbase, *oldbase;
1611
Guido van Rossumb6b89422002-04-15 01:03:30 +00001612 if (value == NULL) {
1613 PyErr_SetString(PyExc_TypeError,
1614 "can't delete __class__ attribute");
1615 return -1;
1616 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001617 if (!PyType_Check(value)) {
1618 PyErr_Format(PyExc_TypeError,
1619 "__class__ must be set to new-style class, not '%s' object",
1620 value->ob_type->tp_name);
1621 return -1;
1622 }
1623 new = (PyTypeObject *)value;
1624 newbase = new;
1625 oldbase = old;
1626 while (equiv_structs(newbase, newbase->tp_base))
1627 newbase = newbase->tp_base;
1628 while (equiv_structs(oldbase, oldbase->tp_base))
1629 oldbase = oldbase->tp_base;
1630 if (newbase != oldbase &&
1631 (newbase->tp_base != oldbase->tp_base ||
1632 !same_slots_added(newbase, oldbase))) {
1633 PyErr_Format(PyExc_TypeError,
1634 "__class__ assignment: "
1635 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001636 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001637 old->tp_name);
1638 return -1;
1639 }
1640 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1641 Py_INCREF(new);
1642 }
1643 self->ob_type = new;
1644 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1645 Py_DECREF(old);
1646 }
1647 return 0;
1648}
1649
1650static PyGetSetDef object_getsets[] = {
1651 {"__class__", object_get_class, object_set_class,
1652 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 {0}
1654};
1655
Guido van Rossum3926a632001-09-25 16:25:58 +00001656static PyObject *
1657object_reduce(PyObject *self, PyObject *args)
1658{
1659 /* Call copy_reg._reduce(self) */
1660 static PyObject *copy_reg_str;
1661 PyObject *copy_reg, *res;
1662
1663 if (!copy_reg_str) {
1664 copy_reg_str = PyString_InternFromString("copy_reg");
1665 if (copy_reg_str == NULL)
1666 return NULL;
1667 }
1668 copy_reg = PyImport_Import(copy_reg_str);
1669 if (!copy_reg)
1670 return NULL;
1671 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1672 Py_DECREF(copy_reg);
1673 return res;
1674}
1675
1676static PyMethodDef object_methods[] = {
1677 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1678 {0}
1679};
1680
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681PyTypeObject PyBaseObject_Type = {
1682 PyObject_HEAD_INIT(&PyType_Type)
1683 0, /* ob_size */
1684 "object", /* tp_name */
1685 sizeof(PyObject), /* tp_basicsize */
1686 0, /* tp_itemsize */
1687 (destructor)object_dealloc, /* tp_dealloc */
1688 0, /* tp_print */
1689 0, /* tp_getattr */
1690 0, /* tp_setattr */
1691 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001692 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 0, /* tp_as_number */
1694 0, /* tp_as_sequence */
1695 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001696 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001697 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001698 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001699 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001700 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701 0, /* tp_as_buffer */
1702 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1703 "The most base type", /* tp_doc */
1704 0, /* tp_traverse */
1705 0, /* tp_clear */
1706 0, /* tp_richcompare */
1707 0, /* tp_weaklistoffset */
1708 0, /* tp_iter */
1709 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001710 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001711 0, /* tp_members */
1712 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713 0, /* tp_base */
1714 0, /* tp_dict */
1715 0, /* tp_descr_get */
1716 0, /* tp_descr_set */
1717 0, /* tp_dictoffset */
1718 object_init, /* tp_init */
1719 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001720 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001721 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722};
1723
1724
1725/* Initialize the __dict__ in a type object */
1726
Fred Drake7bf97152002-03-28 05:33:33 +00001727static PyObject *
1728create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1729{
1730 PyObject *cfunc;
1731 PyObject *result;
1732
1733 cfunc = PyCFunction_New(meth, NULL);
1734 if (cfunc == NULL)
1735 return NULL;
1736 result = func(cfunc);
1737 Py_DECREF(cfunc);
1738 return result;
1739}
1740
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741static int
1742add_methods(PyTypeObject *type, PyMethodDef *meth)
1743{
Guido van Rossum687ae002001-10-15 22:03:32 +00001744 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001745
1746 for (; meth->ml_name != NULL; meth++) {
1747 PyObject *descr;
1748 if (PyDict_GetItemString(dict, meth->ml_name))
1749 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001750 if (meth->ml_flags & METH_CLASS) {
1751 if (meth->ml_flags & METH_STATIC) {
1752 PyErr_SetString(PyExc_ValueError,
1753 "method cannot be both class and static");
1754 return -1;
1755 }
1756 descr = create_specialmethod(meth, PyClassMethod_New);
1757 }
1758 else if (meth->ml_flags & METH_STATIC) {
1759 descr = create_specialmethod(meth, PyStaticMethod_New);
1760 }
1761 else {
1762 descr = PyDescr_NewMethod(type, meth);
1763 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764 if (descr == NULL)
1765 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001766 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767 return -1;
1768 Py_DECREF(descr);
1769 }
1770 return 0;
1771}
1772
1773static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001774add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775{
Guido van Rossum687ae002001-10-15 22:03:32 +00001776 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777
1778 for (; memb->name != NULL; memb++) {
1779 PyObject *descr;
1780 if (PyDict_GetItemString(dict, memb->name))
1781 continue;
1782 descr = PyDescr_NewMember(type, memb);
1783 if (descr == NULL)
1784 return -1;
1785 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1786 return -1;
1787 Py_DECREF(descr);
1788 }
1789 return 0;
1790}
1791
1792static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001793add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794{
Guido van Rossum687ae002001-10-15 22:03:32 +00001795 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796
1797 for (; gsp->name != NULL; gsp++) {
1798 PyObject *descr;
1799 if (PyDict_GetItemString(dict, gsp->name))
1800 continue;
1801 descr = PyDescr_NewGetSet(type, gsp);
1802
1803 if (descr == NULL)
1804 return -1;
1805 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1806 return -1;
1807 Py_DECREF(descr);
1808 }
1809 return 0;
1810}
1811
Guido van Rossum13d52f02001-08-10 21:24:08 +00001812static void
1813inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001814{
1815 int oldsize, newsize;
1816
Guido van Rossum13d52f02001-08-10 21:24:08 +00001817 /* Special flag magic */
1818 if (!type->tp_as_buffer && base->tp_as_buffer) {
1819 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1820 type->tp_flags |=
1821 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1822 }
1823 if (!type->tp_as_sequence && base->tp_as_sequence) {
1824 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1825 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1826 }
1827 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1828 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1829 if ((!type->tp_as_number && base->tp_as_number) ||
1830 (!type->tp_as_sequence && base->tp_as_sequence)) {
1831 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1832 if (!type->tp_as_number && !type->tp_as_sequence) {
1833 type->tp_flags |= base->tp_flags &
1834 Py_TPFLAGS_HAVE_INPLACEOPS;
1835 }
1836 }
1837 /* Wow */
1838 }
1839 if (!type->tp_as_number && base->tp_as_number) {
1840 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1841 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1842 }
1843
1844 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001845 oldsize = base->tp_basicsize;
1846 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1847 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1848 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001849 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1850 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001851 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001852 if (type->tp_traverse == NULL)
1853 type->tp_traverse = base->tp_traverse;
1854 if (type->tp_clear == NULL)
1855 type->tp_clear = base->tp_clear;
1856 }
1857 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001858 /* The condition below could use some explanation.
1859 It appears that tp_new is not inherited for static types
1860 whose base class is 'object'; this seems to be a precaution
1861 so that old extension types don't suddenly become
1862 callable (object.__new__ wouldn't insure the invariants
1863 that the extension type's own factory function ensures).
1864 Heap types, of course, are under our control, so they do
1865 inherit tp_new; static extension types that specify some
1866 other built-in type as the default are considered
1867 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001868 if (base != &PyBaseObject_Type ||
1869 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1870 if (type->tp_new == NULL)
1871 type->tp_new = base->tp_new;
1872 }
1873 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001874 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001875
1876 /* Copy other non-function slots */
1877
1878#undef COPYVAL
1879#define COPYVAL(SLOT) \
1880 if (type->SLOT == 0) type->SLOT = base->SLOT
1881
1882 COPYVAL(tp_itemsize);
1883 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1884 COPYVAL(tp_weaklistoffset);
1885 }
1886 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1887 COPYVAL(tp_dictoffset);
1888 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001889}
1890
1891static void
1892inherit_slots(PyTypeObject *type, PyTypeObject *base)
1893{
1894 PyTypeObject *basebase;
1895
1896#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897#undef COPYSLOT
1898#undef COPYNUM
1899#undef COPYSEQ
1900#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001901#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001902
1903#define SLOTDEFINED(SLOT) \
1904 (base->SLOT != 0 && \
1905 (basebase == NULL || base->SLOT != basebase->SLOT))
1906
Tim Peters6d6c1a32001-08-02 04:15:00 +00001907#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001908 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909
1910#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1911#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1912#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001913#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914
Guido van Rossum13d52f02001-08-10 21:24:08 +00001915 /* This won't inherit indirect slots (from tp_as_number etc.)
1916 if type doesn't provide the space. */
1917
1918 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1919 basebase = base->tp_base;
1920 if (basebase->tp_as_number == NULL)
1921 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 COPYNUM(nb_add);
1923 COPYNUM(nb_subtract);
1924 COPYNUM(nb_multiply);
1925 COPYNUM(nb_divide);
1926 COPYNUM(nb_remainder);
1927 COPYNUM(nb_divmod);
1928 COPYNUM(nb_power);
1929 COPYNUM(nb_negative);
1930 COPYNUM(nb_positive);
1931 COPYNUM(nb_absolute);
1932 COPYNUM(nb_nonzero);
1933 COPYNUM(nb_invert);
1934 COPYNUM(nb_lshift);
1935 COPYNUM(nb_rshift);
1936 COPYNUM(nb_and);
1937 COPYNUM(nb_xor);
1938 COPYNUM(nb_or);
1939 COPYNUM(nb_coerce);
1940 COPYNUM(nb_int);
1941 COPYNUM(nb_long);
1942 COPYNUM(nb_float);
1943 COPYNUM(nb_oct);
1944 COPYNUM(nb_hex);
1945 COPYNUM(nb_inplace_add);
1946 COPYNUM(nb_inplace_subtract);
1947 COPYNUM(nb_inplace_multiply);
1948 COPYNUM(nb_inplace_divide);
1949 COPYNUM(nb_inplace_remainder);
1950 COPYNUM(nb_inplace_power);
1951 COPYNUM(nb_inplace_lshift);
1952 COPYNUM(nb_inplace_rshift);
1953 COPYNUM(nb_inplace_and);
1954 COPYNUM(nb_inplace_xor);
1955 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001956 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1957 COPYNUM(nb_true_divide);
1958 COPYNUM(nb_floor_divide);
1959 COPYNUM(nb_inplace_true_divide);
1960 COPYNUM(nb_inplace_floor_divide);
1961 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962 }
1963
Guido van Rossum13d52f02001-08-10 21:24:08 +00001964 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1965 basebase = base->tp_base;
1966 if (basebase->tp_as_sequence == NULL)
1967 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968 COPYSEQ(sq_length);
1969 COPYSEQ(sq_concat);
1970 COPYSEQ(sq_repeat);
1971 COPYSEQ(sq_item);
1972 COPYSEQ(sq_slice);
1973 COPYSEQ(sq_ass_item);
1974 COPYSEQ(sq_ass_slice);
1975 COPYSEQ(sq_contains);
1976 COPYSEQ(sq_inplace_concat);
1977 COPYSEQ(sq_inplace_repeat);
1978 }
1979
Guido van Rossum13d52f02001-08-10 21:24:08 +00001980 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1981 basebase = base->tp_base;
1982 if (basebase->tp_as_mapping == NULL)
1983 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984 COPYMAP(mp_length);
1985 COPYMAP(mp_subscript);
1986 COPYMAP(mp_ass_subscript);
1987 }
1988
Tim Petersfc57ccb2001-10-12 02:38:24 +00001989 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1990 basebase = base->tp_base;
1991 if (basebase->tp_as_buffer == NULL)
1992 basebase = NULL;
1993 COPYBUF(bf_getreadbuffer);
1994 COPYBUF(bf_getwritebuffer);
1995 COPYBUF(bf_getsegcount);
1996 COPYBUF(bf_getcharbuffer);
1997 }
1998
Guido van Rossum13d52f02001-08-10 21:24:08 +00001999 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002000
Tim Peters6d6c1a32001-08-02 04:15:00 +00002001 COPYSLOT(tp_dealloc);
2002 COPYSLOT(tp_print);
2003 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2004 type->tp_getattr = base->tp_getattr;
2005 type->tp_getattro = base->tp_getattro;
2006 }
2007 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2008 type->tp_setattr = base->tp_setattr;
2009 type->tp_setattro = base->tp_setattro;
2010 }
2011 /* tp_compare see tp_richcompare */
2012 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002013 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014 COPYSLOT(tp_call);
2015 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002017 if (type->tp_compare == NULL &&
2018 type->tp_richcompare == NULL &&
2019 type->tp_hash == NULL)
2020 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021 type->tp_compare = base->tp_compare;
2022 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002023 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002024 }
2025 }
2026 else {
2027 COPYSLOT(tp_compare);
2028 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2030 COPYSLOT(tp_iter);
2031 COPYSLOT(tp_iternext);
2032 }
2033 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2034 COPYSLOT(tp_descr_get);
2035 COPYSLOT(tp_descr_set);
2036 COPYSLOT(tp_dictoffset);
2037 COPYSLOT(tp_init);
2038 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002040 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042}
2043
Guido van Rossum13d52f02001-08-10 21:24:08 +00002044staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002045staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002046
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002048PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002050 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051 PyTypeObject *base;
2052 int i, n;
2053
Guido van Rossumd614f972001-08-10 17:39:49 +00002054 if (type->tp_flags & Py_TPFLAGS_READY) {
2055 assert(type->tp_dict != NULL);
2056 return 0;
2057 }
2058 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002059
2060 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061
2062 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2063 base = type->tp_base;
2064 if (base == NULL && type != &PyBaseObject_Type)
2065 base = type->tp_base = &PyBaseObject_Type;
2066
Guido van Rossum0986d822002-04-08 01:38:42 +00002067 /* Initialize ob_type if NULL. This means extensions that want to be
2068 compilable separately on Windows can call PyType_Ready() instead of
2069 initializing the ob_type field of their type objects. */
2070 if (type->ob_type == NULL)
2071 type->ob_type = base->ob_type;
2072
Tim Peters6d6c1a32001-08-02 04:15:00 +00002073 /* Initialize tp_bases */
2074 bases = type->tp_bases;
2075 if (bases == NULL) {
2076 if (base == NULL)
2077 bases = PyTuple_New(0);
2078 else
2079 bases = Py_BuildValue("(O)", base);
2080 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002081 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002082 type->tp_bases = bases;
2083 }
2084
2085 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002086 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002087 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002088 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 }
2090
Guido van Rossum687ae002001-10-15 22:03:32 +00002091 /* Initialize tp_dict */
2092 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002093 if (dict == NULL) {
2094 dict = PyDict_New();
2095 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002096 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002097 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098 }
2099
Guido van Rossum687ae002001-10-15 22:03:32 +00002100 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002102 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103 if (type->tp_methods != NULL) {
2104 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002105 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 }
2107 if (type->tp_members != NULL) {
2108 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002109 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110 }
2111 if (type->tp_getset != NULL) {
2112 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002113 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114 }
2115
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116 /* Calculate method resolution order */
2117 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002118 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002119 }
2120
Guido van Rossum13d52f02001-08-10 21:24:08 +00002121 /* Inherit special flags from dominant base */
2122 if (type->tp_base != NULL)
2123 inherit_special(type, type->tp_base);
2124
Tim Peters6d6c1a32001-08-02 04:15:00 +00002125 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002126 bases = type->tp_mro;
2127 assert(bases != NULL);
2128 assert(PyTuple_Check(bases));
2129 n = PyTuple_GET_SIZE(bases);
2130 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002131 PyObject *b = PyTuple_GET_ITEM(bases, i);
2132 if (PyType_Check(b))
2133 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002134 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002136 /* if the type dictionary doesn't contain a __doc__, set it from
2137 the tp_doc slot.
2138 */
2139 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2140 if (type->tp_doc != NULL) {
2141 PyObject *doc = PyString_FromString(type->tp_doc);
2142 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2143 Py_DECREF(doc);
2144 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002145 PyDict_SetItemString(type->tp_dict,
2146 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002147 }
2148 }
2149
Guido van Rossum13d52f02001-08-10 21:24:08 +00002150 /* Some more special stuff */
2151 base = type->tp_base;
2152 if (base != NULL) {
2153 if (type->tp_as_number == NULL)
2154 type->tp_as_number = base->tp_as_number;
2155 if (type->tp_as_sequence == NULL)
2156 type->tp_as_sequence = base->tp_as_sequence;
2157 if (type->tp_as_mapping == NULL)
2158 type->tp_as_mapping = base->tp_as_mapping;
2159 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002160
Guido van Rossum1c450732001-10-08 15:18:27 +00002161 /* Link into each base class's list of subclasses */
2162 bases = type->tp_bases;
2163 n = PyTuple_GET_SIZE(bases);
2164 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002165 PyObject *b = PyTuple_GET_ITEM(bases, i);
2166 if (PyType_Check(b) &&
2167 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002168 goto error;
2169 }
2170
Guido van Rossum13d52f02001-08-10 21:24:08 +00002171 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002172 assert(type->tp_dict != NULL);
2173 type->tp_flags =
2174 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002176
2177 error:
2178 type->tp_flags &= ~Py_TPFLAGS_READYING;
2179 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002180}
2181
Guido van Rossum1c450732001-10-08 15:18:27 +00002182static int
2183add_subclass(PyTypeObject *base, PyTypeObject *type)
2184{
2185 int i;
2186 PyObject *list, *ref, *new;
2187
2188 list = base->tp_subclasses;
2189 if (list == NULL) {
2190 base->tp_subclasses = list = PyList_New(0);
2191 if (list == NULL)
2192 return -1;
2193 }
2194 assert(PyList_Check(list));
2195 new = PyWeakref_NewRef((PyObject *)type, NULL);
2196 i = PyList_GET_SIZE(list);
2197 while (--i >= 0) {
2198 ref = PyList_GET_ITEM(list, i);
2199 assert(PyWeakref_CheckRef(ref));
2200 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2201 return PyList_SetItem(list, i, new);
2202 }
2203 i = PyList_Append(list, new);
2204 Py_DECREF(new);
2205 return i;
2206}
2207
Tim Peters6d6c1a32001-08-02 04:15:00 +00002208
2209/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2210
2211/* There's a wrapper *function* for each distinct function typedef used
2212 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2213 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2214 Most tables have only one entry; the tables for binary operators have two
2215 entries, one regular and one with reversed arguments. */
2216
2217static PyObject *
2218wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2219{
2220 inquiry func = (inquiry)wrapped;
2221 int res;
2222
2223 if (!PyArg_ParseTuple(args, ""))
2224 return NULL;
2225 res = (*func)(self);
2226 if (res == -1 && PyErr_Occurred())
2227 return NULL;
2228 return PyInt_FromLong((long)res);
2229}
2230
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231static PyObject *
2232wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2233{
2234 binaryfunc func = (binaryfunc)wrapped;
2235 PyObject *other;
2236
2237 if (!PyArg_ParseTuple(args, "O", &other))
2238 return NULL;
2239 return (*func)(self, other);
2240}
2241
2242static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002243wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2244{
2245 binaryfunc func = (binaryfunc)wrapped;
2246 PyObject *other;
2247
2248 if (!PyArg_ParseTuple(args, "O", &other))
2249 return NULL;
2250 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002251 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002252 Py_INCREF(Py_NotImplemented);
2253 return Py_NotImplemented;
2254 }
2255 return (*func)(self, other);
2256}
2257
2258static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2260{
2261 binaryfunc func = (binaryfunc)wrapped;
2262 PyObject *other;
2263
2264 if (!PyArg_ParseTuple(args, "O", &other))
2265 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002266 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002267 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002268 Py_INCREF(Py_NotImplemented);
2269 return Py_NotImplemented;
2270 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271 return (*func)(other, self);
2272}
2273
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002274static PyObject *
2275wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2276{
2277 coercion func = (coercion)wrapped;
2278 PyObject *other, *res;
2279 int ok;
2280
2281 if (!PyArg_ParseTuple(args, "O", &other))
2282 return NULL;
2283 ok = func(&self, &other);
2284 if (ok < 0)
2285 return NULL;
2286 if (ok > 0) {
2287 Py_INCREF(Py_NotImplemented);
2288 return Py_NotImplemented;
2289 }
2290 res = PyTuple_New(2);
2291 if (res == NULL) {
2292 Py_DECREF(self);
2293 Py_DECREF(other);
2294 return NULL;
2295 }
2296 PyTuple_SET_ITEM(res, 0, self);
2297 PyTuple_SET_ITEM(res, 1, other);
2298 return res;
2299}
2300
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301static PyObject *
2302wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2303{
2304 ternaryfunc func = (ternaryfunc)wrapped;
2305 PyObject *other;
2306 PyObject *third = Py_None;
2307
2308 /* Note: This wrapper only works for __pow__() */
2309
2310 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2311 return NULL;
2312 return (*func)(self, other, third);
2313}
2314
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002315static PyObject *
2316wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2317{
2318 ternaryfunc func = (ternaryfunc)wrapped;
2319 PyObject *other;
2320 PyObject *third = Py_None;
2321
2322 /* Note: This wrapper only works for __pow__() */
2323
2324 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2325 return NULL;
2326 return (*func)(other, self, third);
2327}
2328
Tim Peters6d6c1a32001-08-02 04:15:00 +00002329static PyObject *
2330wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2331{
2332 unaryfunc func = (unaryfunc)wrapped;
2333
2334 if (!PyArg_ParseTuple(args, ""))
2335 return NULL;
2336 return (*func)(self);
2337}
2338
Tim Peters6d6c1a32001-08-02 04:15:00 +00002339static PyObject *
2340wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2341{
2342 intargfunc func = (intargfunc)wrapped;
2343 int i;
2344
2345 if (!PyArg_ParseTuple(args, "i", &i))
2346 return NULL;
2347 return (*func)(self, i);
2348}
2349
Guido van Rossum5d815f32001-08-17 21:57:47 +00002350static int
2351getindex(PyObject *self, PyObject *arg)
2352{
2353 int i;
2354
2355 i = PyInt_AsLong(arg);
2356 if (i == -1 && PyErr_Occurred())
2357 return -1;
2358 if (i < 0) {
2359 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2360 if (sq && sq->sq_length) {
2361 int n = (*sq->sq_length)(self);
2362 if (n < 0)
2363 return -1;
2364 i += n;
2365 }
2366 }
2367 return i;
2368}
2369
2370static PyObject *
2371wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2372{
2373 intargfunc func = (intargfunc)wrapped;
2374 PyObject *arg;
2375 int i;
2376
Guido van Rossumf4593e02001-10-03 12:09:30 +00002377 if (PyTuple_GET_SIZE(args) == 1) {
2378 arg = PyTuple_GET_ITEM(args, 0);
2379 i = getindex(self, arg);
2380 if (i == -1 && PyErr_Occurred())
2381 return NULL;
2382 return (*func)(self, i);
2383 }
2384 PyArg_ParseTuple(args, "O", &arg);
2385 assert(PyErr_Occurred());
2386 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002387}
2388
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389static PyObject *
2390wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2391{
2392 intintargfunc func = (intintargfunc)wrapped;
2393 int i, j;
2394
2395 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2396 return NULL;
2397 return (*func)(self, i, j);
2398}
2399
Tim Peters6d6c1a32001-08-02 04:15:00 +00002400static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002401wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402{
2403 intobjargproc func = (intobjargproc)wrapped;
2404 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002405 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002406
Guido van Rossum5d815f32001-08-17 21:57:47 +00002407 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2408 return NULL;
2409 i = getindex(self, arg);
2410 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411 return NULL;
2412 res = (*func)(self, i, value);
2413 if (res == -1 && PyErr_Occurred())
2414 return NULL;
2415 Py_INCREF(Py_None);
2416 return Py_None;
2417}
2418
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002419static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002420wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002421{
2422 intobjargproc func = (intobjargproc)wrapped;
2423 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002424 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002425
Guido van Rossum5d815f32001-08-17 21:57:47 +00002426 if (!PyArg_ParseTuple(args, "O", &arg))
2427 return NULL;
2428 i = getindex(self, arg);
2429 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002430 return NULL;
2431 res = (*func)(self, i, NULL);
2432 if (res == -1 && PyErr_Occurred())
2433 return NULL;
2434 Py_INCREF(Py_None);
2435 return Py_None;
2436}
2437
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438static PyObject *
2439wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2440{
2441 intintobjargproc func = (intintobjargproc)wrapped;
2442 int i, j, res;
2443 PyObject *value;
2444
2445 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2446 return NULL;
2447 res = (*func)(self, i, j, value);
2448 if (res == -1 && PyErr_Occurred())
2449 return NULL;
2450 Py_INCREF(Py_None);
2451 return Py_None;
2452}
2453
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002454static PyObject *
2455wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2456{
2457 intintobjargproc func = (intintobjargproc)wrapped;
2458 int i, j, res;
2459
2460 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2461 return NULL;
2462 res = (*func)(self, i, j, NULL);
2463 if (res == -1 && PyErr_Occurred())
2464 return NULL;
2465 Py_INCREF(Py_None);
2466 return Py_None;
2467}
2468
Tim Peters6d6c1a32001-08-02 04:15:00 +00002469/* XXX objobjproc is a misnomer; should be objargpred */
2470static PyObject *
2471wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2472{
2473 objobjproc func = (objobjproc)wrapped;
2474 int res;
2475 PyObject *value;
2476
2477 if (!PyArg_ParseTuple(args, "O", &value))
2478 return NULL;
2479 res = (*func)(self, value);
2480 if (res == -1 && PyErr_Occurred())
2481 return NULL;
2482 return PyInt_FromLong((long)res);
2483}
2484
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485static PyObject *
2486wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2487{
2488 objobjargproc func = (objobjargproc)wrapped;
2489 int res;
2490 PyObject *key, *value;
2491
2492 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2493 return NULL;
2494 res = (*func)(self, key, value);
2495 if (res == -1 && PyErr_Occurred())
2496 return NULL;
2497 Py_INCREF(Py_None);
2498 return Py_None;
2499}
2500
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002501static PyObject *
2502wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2503{
2504 objobjargproc func = (objobjargproc)wrapped;
2505 int res;
2506 PyObject *key;
2507
2508 if (!PyArg_ParseTuple(args, "O", &key))
2509 return NULL;
2510 res = (*func)(self, key, NULL);
2511 if (res == -1 && PyErr_Occurred())
2512 return NULL;
2513 Py_INCREF(Py_None);
2514 return Py_None;
2515}
2516
Tim Peters6d6c1a32001-08-02 04:15:00 +00002517static PyObject *
2518wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2519{
2520 cmpfunc func = (cmpfunc)wrapped;
2521 int res;
2522 PyObject *other;
2523
2524 if (!PyArg_ParseTuple(args, "O", &other))
2525 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002526 if (other->ob_type->tp_compare != func &&
2527 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002528 PyErr_Format(
2529 PyExc_TypeError,
2530 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2531 self->ob_type->tp_name,
2532 self->ob_type->tp_name,
2533 other->ob_type->tp_name);
2534 return NULL;
2535 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002536 res = (*func)(self, other);
2537 if (PyErr_Occurred())
2538 return NULL;
2539 return PyInt_FromLong((long)res);
2540}
2541
Tim Peters6d6c1a32001-08-02 04:15:00 +00002542static PyObject *
2543wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2544{
2545 setattrofunc func = (setattrofunc)wrapped;
2546 int res;
2547 PyObject *name, *value;
2548
2549 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2550 return NULL;
2551 res = (*func)(self, name, value);
2552 if (res < 0)
2553 return NULL;
2554 Py_INCREF(Py_None);
2555 return Py_None;
2556}
2557
2558static PyObject *
2559wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2560{
2561 setattrofunc func = (setattrofunc)wrapped;
2562 int res;
2563 PyObject *name;
2564
2565 if (!PyArg_ParseTuple(args, "O", &name))
2566 return NULL;
2567 res = (*func)(self, name, NULL);
2568 if (res < 0)
2569 return NULL;
2570 Py_INCREF(Py_None);
2571 return Py_None;
2572}
2573
Tim Peters6d6c1a32001-08-02 04:15:00 +00002574static PyObject *
2575wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2576{
2577 hashfunc func = (hashfunc)wrapped;
2578 long res;
2579
2580 if (!PyArg_ParseTuple(args, ""))
2581 return NULL;
2582 res = (*func)(self);
2583 if (res == -1 && PyErr_Occurred())
2584 return NULL;
2585 return PyInt_FromLong(res);
2586}
2587
Tim Peters6d6c1a32001-08-02 04:15:00 +00002588static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002589wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590{
2591 ternaryfunc func = (ternaryfunc)wrapped;
2592
Guido van Rossumc8e56452001-10-22 00:43:43 +00002593 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002594}
2595
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596static PyObject *
2597wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2598{
2599 richcmpfunc func = (richcmpfunc)wrapped;
2600 PyObject *other;
2601
2602 if (!PyArg_ParseTuple(args, "O", &other))
2603 return NULL;
2604 return (*func)(self, other, op);
2605}
2606
2607#undef RICHCMP_WRAPPER
2608#define RICHCMP_WRAPPER(NAME, OP) \
2609static PyObject * \
2610richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2611{ \
2612 return wrap_richcmpfunc(self, args, wrapped, OP); \
2613}
2614
Jack Jansen8e938b42001-08-08 15:29:49 +00002615RICHCMP_WRAPPER(lt, Py_LT)
2616RICHCMP_WRAPPER(le, Py_LE)
2617RICHCMP_WRAPPER(eq, Py_EQ)
2618RICHCMP_WRAPPER(ne, Py_NE)
2619RICHCMP_WRAPPER(gt, Py_GT)
2620RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621
Tim Peters6d6c1a32001-08-02 04:15:00 +00002622static PyObject *
2623wrap_next(PyObject *self, PyObject *args, void *wrapped)
2624{
2625 unaryfunc func = (unaryfunc)wrapped;
2626 PyObject *res;
2627
2628 if (!PyArg_ParseTuple(args, ""))
2629 return NULL;
2630 res = (*func)(self);
2631 if (res == NULL && !PyErr_Occurred())
2632 PyErr_SetNone(PyExc_StopIteration);
2633 return res;
2634}
2635
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636static PyObject *
2637wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2638{
2639 descrgetfunc func = (descrgetfunc)wrapped;
2640 PyObject *obj;
2641 PyObject *type = NULL;
2642
2643 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2644 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002645 return (*func)(self, obj, type);
2646}
2647
Tim Peters6d6c1a32001-08-02 04:15:00 +00002648static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002649wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650{
2651 descrsetfunc func = (descrsetfunc)wrapped;
2652 PyObject *obj, *value;
2653 int ret;
2654
2655 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2656 return NULL;
2657 ret = (*func)(self, obj, value);
2658 if (ret < 0)
2659 return NULL;
2660 Py_INCREF(Py_None);
2661 return Py_None;
2662}
2663
Tim Peters6d6c1a32001-08-02 04:15:00 +00002664static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002665wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666{
2667 initproc func = (initproc)wrapped;
2668
Guido van Rossumc8e56452001-10-22 00:43:43 +00002669 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670 return NULL;
2671 Py_INCREF(Py_None);
2672 return Py_None;
2673}
2674
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002676tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677{
Barry Warsaw60f01882001-08-22 19:24:42 +00002678 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002679 PyObject *arg0, *res;
2680
2681 if (self == NULL || !PyType_Check(self))
2682 Py_FatalError("__new__() called with non-type 'self'");
2683 type = (PyTypeObject *)self;
2684 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002685 PyErr_Format(PyExc_TypeError,
2686 "%s.__new__(): not enough arguments",
2687 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002688 return NULL;
2689 }
2690 arg0 = PyTuple_GET_ITEM(args, 0);
2691 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002692 PyErr_Format(PyExc_TypeError,
2693 "%s.__new__(X): X is not a type object (%s)",
2694 type->tp_name,
2695 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002696 return NULL;
2697 }
2698 subtype = (PyTypeObject *)arg0;
2699 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002700 PyErr_Format(PyExc_TypeError,
2701 "%s.__new__(%s): %s is not a subtype of %s",
2702 type->tp_name,
2703 subtype->tp_name,
2704 subtype->tp_name,
2705 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002706 return NULL;
2707 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002708
2709 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002710 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002711 most derived base that's not a heap type is this type. */
2712 staticbase = subtype;
2713 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2714 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002715 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002716 PyErr_Format(PyExc_TypeError,
2717 "%s.__new__(%s) is not safe, use %s.__new__()",
2718 type->tp_name,
2719 subtype->tp_name,
2720 staticbase == NULL ? "?" : staticbase->tp_name);
2721 return NULL;
2722 }
2723
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002724 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2725 if (args == NULL)
2726 return NULL;
2727 res = type->tp_new(subtype, args, kwds);
2728 Py_DECREF(args);
2729 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730}
2731
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002732static struct PyMethodDef tp_new_methoddef[] = {
2733 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2734 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735 {0}
2736};
2737
2738static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002739add_tp_new_wrapper(PyTypeObject *type)
2740{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002741 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002742
Guido van Rossum687ae002001-10-15 22:03:32 +00002743 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002744 return 0;
2745 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002746 if (func == NULL)
2747 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002748 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002749}
2750
Guido van Rossumf040ede2001-08-07 16:40:56 +00002751/* Slot wrappers that call the corresponding __foo__ slot. See comments
2752 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753
Guido van Rossumdc91b992001-08-08 22:26:22 +00002754#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002756FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002758 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002759 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760}
2761
Guido van Rossumdc91b992001-08-08 22:26:22 +00002762#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002764FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002766 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002767 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768}
2769
Guido van Rossumdc91b992001-08-08 22:26:22 +00002770
2771#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002773FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002774{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002775 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002776 int do_other = self->ob_type != other->ob_type && \
2777 other->ob_type->tp_as_number != NULL && \
2778 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002779 if (self->ob_type->tp_as_number != NULL && \
2780 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2781 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002782 if (do_other && \
2783 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2784 r = call_maybe( \
2785 other, ROPSTR, &rcache_str, "(O)", self); \
2786 if (r != Py_NotImplemented) \
2787 return r; \
2788 Py_DECREF(r); \
2789 do_other = 0; \
2790 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002791 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002792 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002793 if (r != Py_NotImplemented || \
2794 other->ob_type == self->ob_type) \
2795 return r; \
2796 Py_DECREF(r); \
2797 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002798 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002799 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002800 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002801 } \
2802 Py_INCREF(Py_NotImplemented); \
2803 return Py_NotImplemented; \
2804}
2805
2806#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2807 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2808
2809#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2810static PyObject * \
2811FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2812{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002813 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002814 return call_method(self, OPSTR, &cache_str, \
2815 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816}
2817
2818static int
2819slot_sq_length(PyObject *self)
2820{
Guido van Rossum2730b132001-08-28 18:22:14 +00002821 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002822 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002823 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824
2825 if (res == NULL)
2826 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002827 len = (int)PyInt_AsLong(res);
2828 Py_DECREF(res);
2829 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830}
2831
Guido van Rossumdc91b992001-08-08 22:26:22 +00002832SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2833SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002834
2835/* Super-optimized version of slot_sq_item.
2836 Other slots could do the same... */
2837static PyObject *
2838slot_sq_item(PyObject *self, int i)
2839{
2840 static PyObject *getitem_str;
2841 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2842 descrgetfunc f;
2843
2844 if (getitem_str == NULL) {
2845 getitem_str = PyString_InternFromString("__getitem__");
2846 if (getitem_str == NULL)
2847 return NULL;
2848 }
2849 func = _PyType_Lookup(self->ob_type, getitem_str);
2850 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002851 if ((f = func->ob_type->tp_descr_get) == NULL)
2852 Py_INCREF(func);
2853 else
2854 func = f(func, self, (PyObject *)(self->ob_type));
2855 ival = PyInt_FromLong(i);
2856 if (ival != NULL) {
2857 args = PyTuple_New(1);
2858 if (args != NULL) {
2859 PyTuple_SET_ITEM(args, 0, ival);
2860 retval = PyObject_Call(func, args, NULL);
2861 Py_XDECREF(args);
2862 Py_XDECREF(func);
2863 return retval;
2864 }
2865 }
2866 }
2867 else {
2868 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2869 }
2870 Py_XDECREF(args);
2871 Py_XDECREF(ival);
2872 Py_XDECREF(func);
2873 return NULL;
2874}
2875
Guido van Rossumdc91b992001-08-08 22:26:22 +00002876SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877
2878static int
2879slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2880{
2881 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002882 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883
2884 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002885 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002886 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002888 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002889 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890 if (res == NULL)
2891 return -1;
2892 Py_DECREF(res);
2893 return 0;
2894}
2895
2896static int
2897slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2898{
2899 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002900 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901
2902 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002903 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002904 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002905 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002906 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002907 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908 if (res == NULL)
2909 return -1;
2910 Py_DECREF(res);
2911 return 0;
2912}
2913
2914static int
2915slot_sq_contains(PyObject *self, PyObject *value)
2916{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002917 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002918 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002919
Guido van Rossum55f20992001-10-01 17:18:22 +00002920 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002921
2922 if (func != NULL) {
2923 args = Py_BuildValue("(O)", value);
2924 if (args == NULL)
2925 res = NULL;
2926 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002927 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002928 Py_DECREF(args);
2929 }
2930 Py_DECREF(func);
2931 if (res == NULL)
2932 return -1;
2933 return PyObject_IsTrue(res);
2934 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002935 else if (PyErr_Occurred())
2936 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002937 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002938 return _PySequence_IterSearch(self, value,
2939 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002940 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941}
2942
Guido van Rossumdc91b992001-08-08 22:26:22 +00002943SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2944SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945
2946#define slot_mp_length slot_sq_length
2947
Guido van Rossumdc91b992001-08-08 22:26:22 +00002948SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002949
2950static int
2951slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2952{
2953 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002954 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002955
2956 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002957 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002958 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002960 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002961 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962 if (res == NULL)
2963 return -1;
2964 Py_DECREF(res);
2965 return 0;
2966}
2967
Guido van Rossumdc91b992001-08-08 22:26:22 +00002968SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2969SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2970SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2971SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2972SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2973SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2974
2975staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2976
2977SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2978 nb_power, "__pow__", "__rpow__")
2979
2980static PyObject *
2981slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2982{
Guido van Rossum2730b132001-08-28 18:22:14 +00002983 static PyObject *pow_str;
2984
Guido van Rossumdc91b992001-08-08 22:26:22 +00002985 if (modulus == Py_None)
2986 return slot_nb_power_binary(self, other);
2987 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002988 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002989 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002990}
2991
2992SLOT0(slot_nb_negative, "__neg__")
2993SLOT0(slot_nb_positive, "__pos__")
2994SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995
2996static int
2997slot_nb_nonzero(PyObject *self)
2998{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002999 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003000 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001
Guido van Rossum55f20992001-10-01 17:18:22 +00003002 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003003 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003004 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003005 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003006 func = lookup_maybe(self, "__len__", &len_str);
3007 if (func == NULL) {
3008 if (PyErr_Occurred())
3009 return -1;
3010 else
3011 return 1;
3012 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003013 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003014 res = PyObject_CallObject(func, NULL);
3015 Py_DECREF(func);
3016 if (res == NULL)
3017 return -1;
3018 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019}
3020
Guido van Rossumdc91b992001-08-08 22:26:22 +00003021SLOT0(slot_nb_invert, "__invert__")
3022SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3023SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3024SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3025SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3026SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003027
3028static int
3029slot_nb_coerce(PyObject **a, PyObject **b)
3030{
3031 static PyObject *coerce_str;
3032 PyObject *self = *a, *other = *b;
3033
3034 if (self->ob_type->tp_as_number != NULL &&
3035 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3036 PyObject *r;
3037 r = call_maybe(
3038 self, "__coerce__", &coerce_str, "(O)", other);
3039 if (r == NULL)
3040 return -1;
3041 if (r == Py_NotImplemented) {
3042 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003043 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003044 else {
3045 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3046 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003047 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003048 Py_DECREF(r);
3049 return -1;
3050 }
3051 *a = PyTuple_GET_ITEM(r, 0);
3052 Py_INCREF(*a);
3053 *b = PyTuple_GET_ITEM(r, 1);
3054 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003055 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003056 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003057 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003058 }
3059 if (other->ob_type->tp_as_number != NULL &&
3060 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3061 PyObject *r;
3062 r = call_maybe(
3063 other, "__coerce__", &coerce_str, "(O)", self);
3064 if (r == NULL)
3065 return -1;
3066 if (r == Py_NotImplemented) {
3067 Py_DECREF(r);
3068 return 1;
3069 }
3070 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3071 PyErr_SetString(PyExc_TypeError,
3072 "__coerce__ didn't return a 2-tuple");
3073 Py_DECREF(r);
3074 return -1;
3075 }
3076 *a = PyTuple_GET_ITEM(r, 1);
3077 Py_INCREF(*a);
3078 *b = PyTuple_GET_ITEM(r, 0);
3079 Py_INCREF(*b);
3080 Py_DECREF(r);
3081 return 0;
3082 }
3083 return 1;
3084}
3085
Guido van Rossumdc91b992001-08-08 22:26:22 +00003086SLOT0(slot_nb_int, "__int__")
3087SLOT0(slot_nb_long, "__long__")
3088SLOT0(slot_nb_float, "__float__")
3089SLOT0(slot_nb_oct, "__oct__")
3090SLOT0(slot_nb_hex, "__hex__")
3091SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3092SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3093SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3094SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3095SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3096SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3097SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3098SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3099SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3100SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3101SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3102SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3103 "__floordiv__", "__rfloordiv__")
3104SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3105SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3106SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107
3108static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003109half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003111 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003112 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003113 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114
Guido van Rossum60718732001-08-28 17:47:51 +00003115 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003116 if (func == NULL) {
3117 PyErr_Clear();
3118 }
3119 else {
3120 args = Py_BuildValue("(O)", other);
3121 if (args == NULL)
3122 res = NULL;
3123 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003124 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003125 Py_DECREF(args);
3126 }
3127 if (res != Py_NotImplemented) {
3128 if (res == NULL)
3129 return -2;
3130 c = PyInt_AsLong(res);
3131 Py_DECREF(res);
3132 if (c == -1 && PyErr_Occurred())
3133 return -2;
3134 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3135 }
3136 Py_DECREF(res);
3137 }
3138 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003139}
3140
Guido van Rossumab3b0342001-09-18 20:38:53 +00003141/* This slot is published for the benefit of try_3way_compare in object.c */
3142int
3143_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003144{
3145 int c;
3146
Guido van Rossumab3b0342001-09-18 20:38:53 +00003147 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003148 c = half_compare(self, other);
3149 if (c <= 1)
3150 return c;
3151 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003152 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003153 c = half_compare(other, self);
3154 if (c < -1)
3155 return -2;
3156 if (c <= 1)
3157 return -c;
3158 }
3159 return (void *)self < (void *)other ? -1 :
3160 (void *)self > (void *)other ? 1 : 0;
3161}
3162
3163static PyObject *
3164slot_tp_repr(PyObject *self)
3165{
3166 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003167 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003168
Guido van Rossum60718732001-08-28 17:47:51 +00003169 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003170 if (func != NULL) {
3171 res = PyEval_CallObject(func, NULL);
3172 Py_DECREF(func);
3173 return res;
3174 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003175 PyErr_Clear();
3176 return PyString_FromFormat("<%s object at %p>",
3177 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003178}
3179
3180static PyObject *
3181slot_tp_str(PyObject *self)
3182{
3183 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003184 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003185
Guido van Rossum60718732001-08-28 17:47:51 +00003186 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003187 if (func != NULL) {
3188 res = PyEval_CallObject(func, NULL);
3189 Py_DECREF(func);
3190 return res;
3191 }
3192 else {
3193 PyErr_Clear();
3194 return slot_tp_repr(self);
3195 }
3196}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003197
3198static long
3199slot_tp_hash(PyObject *self)
3200{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003201 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003202 static PyObject *hash_str, *eq_str, *cmp_str;
3203
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204 long h;
3205
Guido van Rossum60718732001-08-28 17:47:51 +00003206 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003207
3208 if (func != NULL) {
3209 res = PyEval_CallObject(func, NULL);
3210 Py_DECREF(func);
3211 if (res == NULL)
3212 return -1;
3213 h = PyInt_AsLong(res);
3214 }
3215 else {
3216 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003217 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003218 if (func == NULL) {
3219 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003220 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003221 }
3222 if (func != NULL) {
3223 Py_DECREF(func);
3224 PyErr_SetString(PyExc_TypeError, "unhashable type");
3225 return -1;
3226 }
3227 PyErr_Clear();
3228 h = _Py_HashPointer((void *)self);
3229 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003230 if (h == -1 && !PyErr_Occurred())
3231 h = -2;
3232 return h;
3233}
3234
3235static PyObject *
3236slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3237{
Guido van Rossum60718732001-08-28 17:47:51 +00003238 static PyObject *call_str;
3239 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 PyObject *res;
3241
3242 if (meth == NULL)
3243 return NULL;
3244 res = PyObject_Call(meth, args, kwds);
3245 Py_DECREF(meth);
3246 return res;
3247}
3248
Guido van Rossum14a6f832001-10-17 13:59:09 +00003249/* There are two slot dispatch functions for tp_getattro.
3250
3251 - slot_tp_getattro() is used when __getattribute__ is overridden
3252 but no __getattr__ hook is present;
3253
3254 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3255
Guido van Rossumc334df52002-04-04 23:44:47 +00003256 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3257 detects the absence of __getattr__ and then installs the simpler slot if
3258 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003259
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260static PyObject *
3261slot_tp_getattro(PyObject *self, PyObject *name)
3262{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003263 static PyObject *getattribute_str = NULL;
3264 return call_method(self, "__getattribute__", &getattribute_str,
3265 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003266}
3267
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003268static PyObject *
3269slot_tp_getattr_hook(PyObject *self, PyObject *name)
3270{
3271 PyTypeObject *tp = self->ob_type;
3272 PyObject *getattr, *getattribute, *res;
3273 static PyObject *getattribute_str = NULL;
3274 static PyObject *getattr_str = NULL;
3275
3276 if (getattr_str == NULL) {
3277 getattr_str = PyString_InternFromString("__getattr__");
3278 if (getattr_str == NULL)
3279 return NULL;
3280 }
3281 if (getattribute_str == NULL) {
3282 getattribute_str =
3283 PyString_InternFromString("__getattribute__");
3284 if (getattribute_str == NULL)
3285 return NULL;
3286 }
3287 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003288 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003289 /* No __getattr__ hook: use a simpler dispatcher */
3290 tp->tp_getattro = slot_tp_getattro;
3291 return slot_tp_getattro(self, name);
3292 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003293 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003294 if (getattribute == NULL ||
3295 (getattribute->ob_type == &PyWrapperDescr_Type &&
3296 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3297 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003298 res = PyObject_GenericGetAttr(self, name);
3299 else
3300 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003301 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003302 PyErr_Clear();
3303 res = PyObject_CallFunction(getattr, "OO", self, name);
3304 }
3305 return res;
3306}
3307
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308static int
3309slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3310{
3311 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003312 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313
3314 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003315 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003316 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003318 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003319 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003320 if (res == NULL)
3321 return -1;
3322 Py_DECREF(res);
3323 return 0;
3324}
3325
3326/* Map rich comparison operators to their __xx__ namesakes */
3327static char *name_op[] = {
3328 "__lt__",
3329 "__le__",
3330 "__eq__",
3331 "__ne__",
3332 "__gt__",
3333 "__ge__",
3334};
3335
3336static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003337half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003338{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003339 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003340 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003341
Guido van Rossum60718732001-08-28 17:47:51 +00003342 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003343 if (func == NULL) {
3344 PyErr_Clear();
3345 Py_INCREF(Py_NotImplemented);
3346 return Py_NotImplemented;
3347 }
3348 args = Py_BuildValue("(O)", other);
3349 if (args == NULL)
3350 res = NULL;
3351 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003352 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003353 Py_DECREF(args);
3354 }
3355 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003356 return res;
3357}
3358
Guido van Rossumb8f63662001-08-15 23:57:02 +00003359/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3360static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3361
3362static PyObject *
3363slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3364{
3365 PyObject *res;
3366
3367 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3368 res = half_richcompare(self, other, op);
3369 if (res != Py_NotImplemented)
3370 return res;
3371 Py_DECREF(res);
3372 }
3373 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3374 res = half_richcompare(other, self, swapped_op[op]);
3375 if (res != Py_NotImplemented) {
3376 return res;
3377 }
3378 Py_DECREF(res);
3379 }
3380 Py_INCREF(Py_NotImplemented);
3381 return Py_NotImplemented;
3382}
3383
3384static PyObject *
3385slot_tp_iter(PyObject *self)
3386{
3387 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003388 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003389
Guido van Rossum60718732001-08-28 17:47:51 +00003390 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003391 if (func != NULL) {
3392 res = PyObject_CallObject(func, NULL);
3393 Py_DECREF(func);
3394 return res;
3395 }
3396 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003397 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003398 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003399 PyErr_SetString(PyExc_TypeError,
3400 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003401 return NULL;
3402 }
3403 Py_DECREF(func);
3404 return PySeqIter_New(self);
3405}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003406
3407static PyObject *
3408slot_tp_iternext(PyObject *self)
3409{
Guido van Rossum2730b132001-08-28 18:22:14 +00003410 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003411 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412}
3413
Guido van Rossum1a493502001-08-17 16:47:50 +00003414static PyObject *
3415slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3416{
3417 PyTypeObject *tp = self->ob_type;
3418 PyObject *get;
3419 static PyObject *get_str = NULL;
3420
3421 if (get_str == NULL) {
3422 get_str = PyString_InternFromString("__get__");
3423 if (get_str == NULL)
3424 return NULL;
3425 }
3426 get = _PyType_Lookup(tp, get_str);
3427 if (get == NULL) {
3428 /* Avoid further slowdowns */
3429 if (tp->tp_descr_get == slot_tp_descr_get)
3430 tp->tp_descr_get = NULL;
3431 Py_INCREF(self);
3432 return self;
3433 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003434 if (obj == NULL)
3435 obj = Py_None;
3436 if (type == NULL)
3437 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003438 return PyObject_CallFunction(get, "OOO", self, obj, type);
3439}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003440
3441static int
3442slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3443{
Guido van Rossum2c252392001-08-24 10:13:31 +00003444 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003445 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003446
3447 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003448 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003449 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003450 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003451 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003452 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003453 if (res == NULL)
3454 return -1;
3455 Py_DECREF(res);
3456 return 0;
3457}
3458
3459static int
3460slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3461{
Guido van Rossum60718732001-08-28 17:47:51 +00003462 static PyObject *init_str;
3463 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003464 PyObject *res;
3465
3466 if (meth == NULL)
3467 return -1;
3468 res = PyObject_Call(meth, args, kwds);
3469 Py_DECREF(meth);
3470 if (res == NULL)
3471 return -1;
3472 Py_DECREF(res);
3473 return 0;
3474}
3475
3476static PyObject *
3477slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3478{
3479 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3480 PyObject *newargs, *x;
3481 int i, n;
3482
3483 if (func == NULL)
3484 return NULL;
3485 assert(PyTuple_Check(args));
3486 n = PyTuple_GET_SIZE(args);
3487 newargs = PyTuple_New(n+1);
3488 if (newargs == NULL)
3489 return NULL;
3490 Py_INCREF(type);
3491 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3492 for (i = 0; i < n; i++) {
3493 x = PyTuple_GET_ITEM(args, i);
3494 Py_INCREF(x);
3495 PyTuple_SET_ITEM(newargs, i+1, x);
3496 }
3497 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003498 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499 Py_DECREF(func);
3500 return x;
3501}
3502
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003503
3504/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3505 functions. The offsets here are relative to the 'etype' structure, which
3506 incorporates the additional structures used for numbers, sequences and
3507 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3508 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003509 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3510 terminated with an all-zero entry. (This table is further initialized and
3511 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003512
Guido van Rossum6d204072001-10-21 00:44:31 +00003513typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003514
3515#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003516#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003517#undef ETSLOT
3518#undef SQSLOT
3519#undef MPSLOT
3520#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003521#undef UNSLOT
3522#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003523#undef BINSLOT
3524#undef RBINSLOT
3525
Guido van Rossum6d204072001-10-21 00:44:31 +00003526#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3527 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003528#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3529 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3530 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003531#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3532 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3533#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3534 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3535#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3536 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3537#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3538 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3539#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3540 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3541 "x." NAME "() <==> " DOC)
3542#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3543 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3544 "x." NAME "(y) <==> x" DOC "y")
3545#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3546 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3547 "x." NAME "(y) <==> x" DOC "y")
3548#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3549 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3550 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003551
3552static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003553 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3554 "x.__len__() <==> len(x)"),
3555 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3556 "x.__add__(y) <==> x+y"),
3557 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3558 "x.__mul__(n) <==> x*n"),
3559 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3560 "x.__rmul__(n) <==> n*x"),
3561 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3562 "x.__getitem__(y) <==> x[y]"),
3563 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3564 "x.__getslice__(i, j) <==> x[i:j]"),
3565 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3566 "x.__setitem__(i, y) <==> x[i]=y"),
3567 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3568 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003569 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003570 wrap_intintobjargproc,
3571 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3572 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3573 "x.__delslice__(i, j) <==> del x[i:j]"),
3574 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3575 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003576 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003577 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003578 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003579 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003580
Guido van Rossum6d204072001-10-21 00:44:31 +00003581 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3582 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003583 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003584 wrap_binaryfunc,
3585 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003586 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003587 wrap_objobjargproc,
3588 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003589 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003590 wrap_delitem,
3591 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003592
Guido van Rossum6d204072001-10-21 00:44:31 +00003593 BINSLOT("__add__", nb_add, slot_nb_add,
3594 "+"),
3595 RBINSLOT("__radd__", nb_add, slot_nb_add,
3596 "+"),
3597 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3598 "-"),
3599 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3600 "-"),
3601 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3602 "*"),
3603 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3604 "*"),
3605 BINSLOT("__div__", nb_divide, slot_nb_divide,
3606 "/"),
3607 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3608 "/"),
3609 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3610 "%"),
3611 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3612 "%"),
3613 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3614 "divmod(x, y)"),
3615 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3616 "divmod(y, x)"),
3617 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3618 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3619 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3620 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3621 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3622 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3623 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3624 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003625 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003626 "x != 0"),
3627 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3628 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3629 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3630 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3631 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3632 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3633 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3634 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3635 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3636 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3637 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3638 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3639 "x.__coerce__(y) <==> coerce(x, y)"),
3640 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3641 "int(x)"),
3642 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3643 "long(x)"),
3644 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3645 "float(x)"),
3646 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3647 "oct(x)"),
3648 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3649 "hex(x)"),
3650 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3651 wrap_binaryfunc, "+"),
3652 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3653 wrap_binaryfunc, "-"),
3654 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3655 wrap_binaryfunc, "*"),
3656 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3657 wrap_binaryfunc, "/"),
3658 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3659 wrap_binaryfunc, "%"),
3660 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3661 wrap_ternaryfunc, "**"),
3662 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3663 wrap_binaryfunc, "<<"),
3664 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3665 wrap_binaryfunc, ">>"),
3666 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3667 wrap_binaryfunc, "&"),
3668 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3669 wrap_binaryfunc, "^"),
3670 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3671 wrap_binaryfunc, "|"),
3672 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3673 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3674 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3675 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3676 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3677 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3678 IBSLOT("__itruediv__", nb_inplace_true_divide,
3679 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003680
Guido van Rossum6d204072001-10-21 00:44:31 +00003681 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3682 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003683 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003684 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3685 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003686 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003687 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3688 "x.__cmp__(y) <==> cmp(x,y)"),
3689 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3690 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003691 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3692 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003693 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003694 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3695 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3696 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3697 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3698 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3699 "x.__setattr__('name', value) <==> x.name = value"),
3700 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3701 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3702 "x.__delattr__('name') <==> del x.name"),
3703 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3704 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3705 "x.__lt__(y) <==> x<y"),
3706 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3707 "x.__le__(y) <==> x<=y"),
3708 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3709 "x.__eq__(y) <==> x==y"),
3710 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3711 "x.__ne__(y) <==> x!=y"),
3712 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3713 "x.__gt__(y) <==> x>y"),
3714 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3715 "x.__ge__(y) <==> x>=y"),
3716 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3717 "x.__iter__() <==> iter(x)"),
3718 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3719 "x.next() -> the next value, or raise StopIteration"),
3720 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3721 "descr.__get__(obj[, type]) -> value"),
3722 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3723 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003724 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003725 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003726 "see x.__class__.__doc__ for signature",
3727 PyWrapperFlag_KEYWORDS),
3728 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003729 {NULL}
3730};
3731
Guido van Rossumc334df52002-04-04 23:44:47 +00003732/* Given a type pointer and an offset gotten from a slotdef entry, return a
3733 pointer to the actual slot. This is not quite the same as simply adding
3734 the offset to the type pointer, since it takes care to indirect through the
3735 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3736 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003737static void **
3738slotptr(PyTypeObject *type, int offset)
3739{
3740 char *ptr;
3741
3742 assert(offset >= 0);
3743 assert(offset < offsetof(etype, as_buffer));
3744 if (offset >= offsetof(etype, as_mapping)) {
3745 ptr = (void *)type->tp_as_mapping;
3746 offset -= offsetof(etype, as_mapping);
3747 }
3748 else if (offset >= offsetof(etype, as_sequence)) {
3749 ptr = (void *)type->tp_as_sequence;
3750 offset -= offsetof(etype, as_sequence);
3751 }
3752 else if (offset >= offsetof(etype, as_number)) {
3753 ptr = (void *)type->tp_as_number;
3754 offset -= offsetof(etype, as_number);
3755 }
3756 else {
3757 ptr = (void *)type;
3758 }
3759 if (ptr != NULL)
3760 ptr += offset;
3761 return (void **)ptr;
3762}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003763
Guido van Rossumc334df52002-04-04 23:44:47 +00003764/* Length of array of slotdef pointers used to store slots with the
3765 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3766 the same __name__, for any __name__. Since that's a static property, it is
3767 appropriate to declare fixed-size arrays for this. */
3768#define MAX_EQUIV 10
3769
3770/* Return a slot pointer for a given name, but ONLY if the attribute has
3771 exactly one slot function. The name must be an interned string. */
3772static void **
3773resolve_slotdups(PyTypeObject *type, PyObject *name)
3774{
3775 /* XXX Maybe this could be optimized more -- but is it worth it? */
3776
3777 /* pname and ptrs act as a little cache */
3778 static PyObject *pname;
3779 static slotdef *ptrs[MAX_EQUIV];
3780 slotdef *p, **pp;
3781 void **res, **ptr;
3782
3783 if (pname != name) {
3784 /* Collect all slotdefs that match name into ptrs. */
3785 pname = name;
3786 pp = ptrs;
3787 for (p = slotdefs; p->name_strobj; p++) {
3788 if (p->name_strobj == name)
3789 *pp++ = p;
3790 }
3791 *pp = NULL;
3792 }
3793
3794 /* Look in all matching slots of the type; if exactly one of these has
3795 a filled-in slot, return its value. Otherwise return NULL. */
3796 res = NULL;
3797 for (pp = ptrs; *pp; pp++) {
3798 ptr = slotptr(type, (*pp)->offset);
3799 if (ptr == NULL || *ptr == NULL)
3800 continue;
3801 if (res != NULL)
3802 return NULL;
3803 res = ptr;
3804 }
3805 return res;
3806}
3807
3808/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3809 does some incredibly complex thinking and then sticks something into the
3810 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3811 interests, and then stores a generic wrapper or a specific function into
3812 the slot.) Return a pointer to the next slotdef with a different offset,
3813 because that's convenient for fixup_slot_dispatchers(). */
3814static slotdef *
3815update_one_slot(PyTypeObject *type, slotdef *p)
3816{
3817 PyObject *descr;
3818 PyWrapperDescrObject *d;
3819 void *generic = NULL, *specific = NULL;
3820 int use_generic = 0;
3821 int offset = p->offset;
3822 void **ptr = slotptr(type, offset);
3823
3824 if (ptr == NULL) {
3825 do {
3826 ++p;
3827 } while (p->offset == offset);
3828 return p;
3829 }
3830 do {
3831 descr = _PyType_Lookup(type, p->name_strobj);
3832 if (descr == NULL)
3833 continue;
3834 if (descr->ob_type == &PyWrapperDescr_Type) {
3835 void **tptr = resolve_slotdups(type, p->name_strobj);
3836 if (tptr == NULL || tptr == ptr)
3837 generic = p->function;
3838 d = (PyWrapperDescrObject *)descr;
3839 if (d->d_base->wrapper == p->wrapper &&
3840 PyType_IsSubtype(type, d->d_type))
3841 {
3842 if (specific == NULL ||
3843 specific == d->d_wrapped)
3844 specific = d->d_wrapped;
3845 else
3846 use_generic = 1;
3847 }
3848 }
3849 else {
3850 use_generic = 1;
3851 generic = p->function;
3852 }
3853 } while ((++p)->offset == offset);
3854 if (specific && !use_generic)
3855 *ptr = specific;
3856 else
3857 *ptr = generic;
3858 return p;
3859}
3860
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003861staticforward int recurse_down_subclasses(PyTypeObject *type,
3862 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003863
Guido van Rossumc334df52002-04-04 23:44:47 +00003864/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3865 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003866static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003867update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003868{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003869 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003870
Guido van Rossumc334df52002-04-04 23:44:47 +00003871 for (pp = pp0; *pp; pp++)
3872 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003873 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003874}
3875
Guido van Rossumc334df52002-04-04 23:44:47 +00003876/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3877 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003878static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003879recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003880{
3881 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003882 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003883 int i, n;
3884
3885 subclasses = type->tp_subclasses;
3886 if (subclasses == NULL)
3887 return 0;
3888 assert(PyList_Check(subclasses));
3889 n = PyList_GET_SIZE(subclasses);
3890 for (i = 0; i < n; i++) {
3891 ref = PyList_GET_ITEM(subclasses, i);
3892 assert(PyWeakref_CheckRef(ref));
3893 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3894 if (subclass == NULL)
3895 continue;
3896 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003897 /* Avoid recursing down into unaffected classes */
3898 dict = subclass->tp_dict;
3899 if (dict != NULL && PyDict_Check(dict) &&
3900 PyDict_GetItem(dict, name) != NULL)
3901 continue;
3902 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003903 return -1;
3904 }
3905 return 0;
3906}
3907
Guido van Rossumc334df52002-04-04 23:44:47 +00003908/* Comparison function for qsort() to compare slotdefs by their offset, and
3909 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003910static int
3911slotdef_cmp(const void *aa, const void *bb)
3912{
3913 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3914 int c = a->offset - b->offset;
3915 if (c != 0)
3916 return c;
3917 else
3918 return a - b;
3919}
3920
Guido van Rossumc334df52002-04-04 23:44:47 +00003921/* Initialize the slotdefs table by adding interned string objects for the
3922 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003923static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003924init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003925{
3926 slotdef *p;
3927 static int initialized = 0;
3928
3929 if (initialized)
3930 return;
3931 for (p = slotdefs; p->name; p++) {
3932 p->name_strobj = PyString_InternFromString(p->name);
3933 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00003934 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003935 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003936 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3937 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003938 initialized = 1;
3939}
3940
Guido van Rossumc334df52002-04-04 23:44:47 +00003941/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003942static int
3943update_slot(PyTypeObject *type, PyObject *name)
3944{
Guido van Rossumc334df52002-04-04 23:44:47 +00003945 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003946 slotdef *p;
3947 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003948 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003949
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003950 init_slotdefs();
3951 pp = ptrs;
3952 for (p = slotdefs; p->name; p++) {
3953 /* XXX assume name is interned! */
3954 if (p->name_strobj == name)
3955 *pp++ = p;
3956 }
3957 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003958 for (pp = ptrs; *pp; pp++) {
3959 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003960 offset = p->offset;
3961 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003962 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003963 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003964 }
Guido van Rossumc334df52002-04-04 23:44:47 +00003965 if (ptrs[0] == NULL)
3966 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003967 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003968}
3969
Guido van Rossumc334df52002-04-04 23:44:47 +00003970/* Store the proper functions in the slot dispatches at class (type)
3971 definition time, based upon which operations the class overrides in its
3972 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003974fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003976 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003978 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00003979 for (p = slotdefs; p->name; )
3980 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003982
Guido van Rossum6d204072001-10-21 00:44:31 +00003983/* This function is called by PyType_Ready() to populate the type's
3984 dictionary with method descriptors for function slots. For each
3985 function slot (like tp_repr) that's defined in the type, one or
3986 more corresponding descriptors are added in the type's tp_dict
3987 dictionary under the appropriate name (like __repr__). Some
3988 function slots cause more than one descriptor to be added (for
3989 example, the nb_add slot adds both __add__ and __radd__
3990 descriptors) and some function slots compete for the same
3991 descriptor (for example both sq_item and mp_subscript generate a
3992 __getitem__ descriptor). This only adds new descriptors and
3993 doesn't overwrite entries in tp_dict that were previously
3994 defined. The descriptors contain a reference to the C function
3995 they must call, so that it's safe if they are copied into a
3996 subtype's __dict__ and the subtype has a different C function in
3997 its slot -- calling the method defined by the descriptor will call
3998 the C function that was used to create it, rather than the C
3999 function present in the slot when it is called. (This is important
4000 because a subtype may have a C function in the slot that calls the
4001 method from the dictionary, and we want to avoid infinite recursion
4002 here.) */
4003
4004static int
4005add_operators(PyTypeObject *type)
4006{
4007 PyObject *dict = type->tp_dict;
4008 slotdef *p;
4009 PyObject *descr;
4010 void **ptr;
4011
4012 init_slotdefs();
4013 for (p = slotdefs; p->name; p++) {
4014 if (p->wrapper == NULL)
4015 continue;
4016 ptr = slotptr(type, p->offset);
4017 if (!ptr || !*ptr)
4018 continue;
4019 if (PyDict_GetItem(dict, p->name_strobj))
4020 continue;
4021 descr = PyDescr_NewWrapper(type, p, *ptr);
4022 if (descr == NULL)
4023 return -1;
4024 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4025 return -1;
4026 Py_DECREF(descr);
4027 }
4028 if (type->tp_new != NULL) {
4029 if (add_tp_new_wrapper(type) < 0)
4030 return -1;
4031 }
4032 return 0;
4033}
4034
Guido van Rossum705f0f52001-08-24 16:47:00 +00004035
4036/* Cooperative 'super' */
4037
4038typedef struct {
4039 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004040 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004041 PyObject *obj;
4042} superobject;
4043
Guido van Rossum6f799372001-09-20 20:46:19 +00004044static PyMemberDef super_members[] = {
4045 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4046 "the class invoking super()"},
4047 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4048 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004049 {0}
4050};
4051
Guido van Rossum705f0f52001-08-24 16:47:00 +00004052static void
4053super_dealloc(PyObject *self)
4054{
4055 superobject *su = (superobject *)self;
4056
Guido van Rossum048eb752001-10-02 21:24:57 +00004057 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004058 Py_XDECREF(su->obj);
4059 Py_XDECREF(su->type);
4060 self->ob_type->tp_free(self);
4061}
4062
4063static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004064super_repr(PyObject *self)
4065{
4066 superobject *su = (superobject *)self;
4067
4068 if (su->obj)
4069 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004070 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004071 su->type ? su->type->tp_name : "NULL",
4072 su->obj->ob_type->tp_name);
4073 else
4074 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004075 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004076 su->type ? su->type->tp_name : "NULL");
4077}
4078
4079static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004080super_getattro(PyObject *self, PyObject *name)
4081{
4082 superobject *su = (superobject *)self;
4083
4084 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004085 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004086 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004087 descrgetfunc f;
4088 int i, n;
4089
Guido van Rossum155db9a2002-04-02 17:53:47 +00004090 starttype = su->obj->ob_type;
4091 mro = starttype->tp_mro;
4092
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 Rossum705f0f52001-08-24 16:47:00 +00004099 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004100 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004101 break;
4102 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004103 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004104 starttype = (PyTypeObject *)(su->obj);
4105 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004106 if (mro == NULL)
4107 n = 0;
4108 else {
4109 assert(PyTuple_Check(mro));
4110 n = PyTuple_GET_SIZE(mro);
4111 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004112 for (i = 0; i < n; i++) {
4113 if ((PyObject *)(su->type) ==
4114 PyTuple_GET_ITEM(mro, i))
4115 break;
4116 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004117 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004118 i++;
4119 res = NULL;
4120 for (; i < n; i++) {
4121 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004122 if (PyType_Check(tmp))
4123 dict = ((PyTypeObject *)tmp)->tp_dict;
4124 else if (PyClass_Check(tmp))
4125 dict = ((PyClassObject *)tmp)->cl_dict;
4126 else
4127 continue;
4128 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004129 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004130 Py_INCREF(res);
4131 f = res->ob_type->tp_descr_get;
4132 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004133 tmp = f(res, su->obj,
4134 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004135 Py_DECREF(res);
4136 res = tmp;
4137 }
4138 return res;
4139 }
4140 }
4141 }
4142 return PyObject_GenericGetAttr(self, name);
4143}
4144
Guido van Rossum5b443c62001-12-03 15:38:28 +00004145static int
4146supercheck(PyTypeObject *type, PyObject *obj)
4147{
4148 if (!PyType_IsSubtype(obj->ob_type, type) &&
4149 !(PyType_Check(obj) &&
4150 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4151 PyErr_SetString(PyExc_TypeError,
4152 "super(type, obj): "
4153 "obj must be an instance or subtype of type");
4154 return -1;
4155 }
4156 else
4157 return 0;
4158}
4159
Guido van Rossum705f0f52001-08-24 16:47:00 +00004160static PyObject *
4161super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4162{
4163 superobject *su = (superobject *)self;
4164 superobject *new;
4165
4166 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4167 /* Not binding to an object, or already bound */
4168 Py_INCREF(self);
4169 return self;
4170 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004171 if (su->ob_type != &PySuper_Type)
4172 /* If su is an instance of a subclass of super,
4173 call its type */
4174 return PyObject_CallFunction((PyObject *)su->ob_type,
4175 "OO", su->type, obj);
4176 else {
4177 /* Inline the common case */
4178 if (supercheck(su->type, obj) < 0)
4179 return NULL;
4180 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4181 NULL, NULL);
4182 if (new == NULL)
4183 return NULL;
4184 Py_INCREF(su->type);
4185 Py_INCREF(obj);
4186 new->type = su->type;
4187 new->obj = obj;
4188 return (PyObject *)new;
4189 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004190}
4191
4192static int
4193super_init(PyObject *self, PyObject *args, PyObject *kwds)
4194{
4195 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004196 PyTypeObject *type;
4197 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004198
4199 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4200 return -1;
4201 if (obj == Py_None)
4202 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004203 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004204 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004205 Py_INCREF(type);
4206 Py_XINCREF(obj);
4207 su->type = type;
4208 su->obj = obj;
4209 return 0;
4210}
4211
4212static char super_doc[] =
4213"super(type) -> unbound super object\n"
4214"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004215"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004216"Typical use to call a cooperative superclass method:\n"
4217"class C(B):\n"
4218" def meth(self, arg):\n"
4219" super(C, self).meth(arg)";
4220
Guido van Rossum048eb752001-10-02 21:24:57 +00004221static int
4222super_traverse(PyObject *self, visitproc visit, void *arg)
4223{
4224 superobject *su = (superobject *)self;
4225 int err;
4226
4227#define VISIT(SLOT) \
4228 if (SLOT) { \
4229 err = visit((PyObject *)(SLOT), arg); \
4230 if (err) \
4231 return err; \
4232 }
4233
4234 VISIT(su->obj);
4235 VISIT(su->type);
4236
4237#undef VISIT
4238
4239 return 0;
4240}
4241
Guido van Rossum705f0f52001-08-24 16:47:00 +00004242PyTypeObject PySuper_Type = {
4243 PyObject_HEAD_INIT(&PyType_Type)
4244 0, /* ob_size */
4245 "super", /* tp_name */
4246 sizeof(superobject), /* tp_basicsize */
4247 0, /* tp_itemsize */
4248 /* methods */
4249 super_dealloc, /* tp_dealloc */
4250 0, /* tp_print */
4251 0, /* tp_getattr */
4252 0, /* tp_setattr */
4253 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004254 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004255 0, /* tp_as_number */
4256 0, /* tp_as_sequence */
4257 0, /* tp_as_mapping */
4258 0, /* tp_hash */
4259 0, /* tp_call */
4260 0, /* tp_str */
4261 super_getattro, /* tp_getattro */
4262 0, /* tp_setattro */
4263 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004264 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4265 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004266 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004267 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004268 0, /* tp_clear */
4269 0, /* tp_richcompare */
4270 0, /* tp_weaklistoffset */
4271 0, /* tp_iter */
4272 0, /* tp_iternext */
4273 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004274 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004275 0, /* tp_getset */
4276 0, /* tp_base */
4277 0, /* tp_dict */
4278 super_descr_get, /* tp_descr_get */
4279 0, /* tp_descr_set */
4280 0, /* tp_dictoffset */
4281 super_init, /* tp_init */
4282 PyType_GenericAlloc, /* tp_alloc */
4283 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004284 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004285};