blob: ca7e64d8cfb1c809ae7813d72b6d6adea78f6a4c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum6f799372001-09-20 20:46:19 +00007static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000011 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000012 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
13 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
14 {"__dictoffset__", T_LONG,
15 offsetof(PyTypeObject, tp_dictoffset), READONLY},
16 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
17 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
24 char *s;
25
26 s = strrchr(type->tp_name, '.');
27 if (s == NULL)
28 s = type->tp_name;
29 else
30 s++;
31 return PyString_FromString(s);
32}
33
34static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000035type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000036{
Guido van Rossumc3542212001-08-16 09:18:56 +000037 PyObject *mod;
38 char *s;
39
40 s = strrchr(type->tp_name, '.');
41 if (s != NULL)
42 return PyString_FromStringAndSize(type->tp_name,
43 (int)(s - type->tp_name));
44 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
45 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000046 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000047 if (mod != NULL && PyString_Check(mod)) {
48 Py_INCREF(mod);
49 return mod;
50 }
51 PyErr_SetString(PyExc_AttributeError, "__module__");
52 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000053}
54
Guido van Rossum3926a632001-09-25 16:25:58 +000055static int
56type_set_module(PyTypeObject *type, PyObject *value, void *context)
57{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000058 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000059 strrchr(type->tp_name, '.')) {
60 PyErr_Format(PyExc_TypeError,
61 "can't set %s.__module__", type->tp_name);
62 return -1;
63 }
64 if (!value) {
65 PyErr_Format(PyExc_TypeError,
66 "can't delete %s.__module__", type->tp_name);
67 return -1;
68 }
69 return PyDict_SetItemString(type->tp_dict, "__module__", value);
70}
71
Tim Peters6d6c1a32001-08-02 04:15:00 +000072static PyObject *
73type_dict(PyTypeObject *type, void *context)
74{
75 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 Py_INCREF(Py_None);
77 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000078 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000079 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000080}
81
Neil Schemenauerf23473f2001-10-21 22:28:58 +000082static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000083 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +000084 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000085 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000086 {0}
87};
88
Martin v. Löwis0163d6d2001-06-09 07:34:05 +000089static int
90type_compare(PyObject *v, PyObject *w)
91{
92 /* This is called with type objects only. So we
93 can just compare the addresses. */
94 Py_uintptr_t vv = (Py_uintptr_t)v;
95 Py_uintptr_t ww = (Py_uintptr_t)w;
96 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
97}
98
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000102 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000103 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000104
105 mod = type_module(type, NULL);
106 if (mod == NULL)
107 PyErr_Clear();
108 else if (!PyString_Check(mod)) {
109 Py_DECREF(mod);
110 mod = NULL;
111 }
112 name = type_name(type, NULL);
113 if (name == NULL)
114 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000115
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000116 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
117 kind = "class";
118 else
119 kind = "type";
120
Barry Warsaw7ce36942001-08-24 18:34:26 +0000121 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000122 rtn = PyString_FromFormat("<%s '%s.%s'>",
123 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000124 PyString_AS_STRING(mod),
125 PyString_AS_STRING(name));
126 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000127 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000128 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000129
Guido van Rossumc3542212001-08-16 09:18:56 +0000130 Py_XDECREF(mod);
131 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000132 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133}
134
Tim Peters6d6c1a32001-08-02 04:15:00 +0000135static PyObject *
136type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
137{
138 PyObject *obj;
139
140 if (type->tp_new == NULL) {
141 PyErr_Format(PyExc_TypeError,
142 "cannot create '%.100s' instances",
143 type->tp_name);
144 return NULL;
145 }
146
Tim Peters3f996e72001-09-13 19:18:27 +0000147 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000148 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000149 /* Ugly exception: when the call was type(something),
150 don't call tp_init on the result. */
151 if (type == &PyType_Type &&
152 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
153 (kwds == NULL ||
154 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
155 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000156 type = obj->ob_type;
157 if (type->tp_init != NULL &&
158 type->tp_init(obj, args, kwds) < 0) {
159 Py_DECREF(obj);
160 obj = NULL;
161 }
162 }
163 return obj;
164}
165
166PyObject *
167PyType_GenericAlloc(PyTypeObject *type, int nitems)
168{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000169 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000170 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000171
172 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000173 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000174 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000175 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000176
Neil Schemenauerc806c882001-08-29 23:54:54 +0000177 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000178 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000179
Neil Schemenauerc806c882001-08-29 23:54:54 +0000180 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000181
Tim Peters6d6c1a32001-08-02 04:15:00 +0000182 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
183 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000184
Tim Peters6d6c1a32001-08-02 04:15:00 +0000185 if (type->tp_itemsize == 0)
186 PyObject_INIT(obj, type);
187 else
188 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000189
Tim Peters6d6c1a32001-08-02 04:15:00 +0000190 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000191 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000192 return obj;
193}
194
195PyObject *
196PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
197{
198 return type->tp_alloc(type, 0);
199}
200
Guido van Rossum9475a232001-10-05 20:51:39 +0000201/* Helpers for subtyping */
202
203static int
204subtype_traverse(PyObject *self, visitproc visit, void *arg)
205{
206 PyTypeObject *type, *base;
207 traverseproc f;
208 int err;
209
210 /* Find the nearest base with a different tp_traverse */
211 type = self->ob_type;
212 base = type->tp_base;
213 while ((f = base->tp_traverse) == subtype_traverse) {
214 base = base->tp_base;
215 assert(base);
216 }
217
218 if (type->tp_dictoffset != base->tp_dictoffset) {
219 PyObject **dictptr = _PyObject_GetDictPtr(self);
220 if (dictptr && *dictptr) {
221 err = visit(*dictptr, arg);
222 if (err)
223 return err;
224 }
225 }
226
227 if (f)
228 return f(self, visit, arg);
229 return 0;
230}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000232staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
233
234static int
235call_finalizer(PyObject *self)
236{
237 static PyObject *del_str = NULL;
238 PyObject *del, *res;
239 PyObject *error_type, *error_value, *error_traceback;
240
241 /* Temporarily resurrect the object. */
242#ifdef Py_TRACE_REFS
243#ifndef Py_REF_DEBUG
244# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
245#endif
246 /* much too complicated if Py_TRACE_REFS defined */
247 _Py_NewReference((PyObject *)self);
248#ifdef COUNT_ALLOCS
249 /* compensate for boost in _Py_NewReference; note that
250 * _Py_RefTotal was also boosted; we'll knock that down later.
251 */
252 self->ob_type->tp_allocs--;
253#endif
254#else /* !Py_TRACE_REFS */
255 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
256 Py_INCREF(self);
257#endif /* !Py_TRACE_REFS */
258
259 /* Save the current exception, if any. */
260 PyErr_Fetch(&error_type, &error_value, &error_traceback);
261
262 /* Execute __del__ method, if any. */
263 del = lookup_maybe(self, "__del__", &del_str);
264 if (del != NULL) {
265 res = PyEval_CallObject(del, NULL);
266 if (res == NULL)
267 PyErr_WriteUnraisable(del);
268 else
269 Py_DECREF(res);
270 Py_DECREF(del);
271 }
272
273 /* Restore the saved exception. */
274 PyErr_Restore(error_type, error_value, error_traceback);
275
276 /* Undo the temporary resurrection; can't use DECREF here, it would
277 * cause a recursive call.
278 */
279#ifdef Py_REF_DEBUG
280 /* _Py_RefTotal was boosted either by _Py_NewReference or
281 * Py_INCREF above.
282 */
283 _Py_RefTotal--;
284#endif
285 if (--self->ob_refcnt > 0) {
286#ifdef COUNT_ALLOCS
287 self->ob_type->tp_frees--;
288#endif
289 _PyObject_GC_TRACK(self);
290 return -1; /* __del__ added a reference; don't delete now */
291 }
292#ifdef Py_TRACE_REFS
293 _Py_ForgetReference((PyObject *)self);
294#ifdef COUNT_ALLOCS
295 /* compensate for increment in _Py_ForgetReference */
296 self->ob_type->tp_frees--;
297#endif
298#endif
299
300 return 0;
301}
302
Tim Peters6d6c1a32001-08-02 04:15:00 +0000303static void
304subtype_dealloc(PyObject *self)
305{
Guido van Rossum14227b42001-12-06 02:35:58 +0000306 PyTypeObject *type, *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000307 destructor f;
308
309 /* This exists so we can DECREF self->ob_type */
310
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000311 if (call_finalizer(self) < 0)
312 return;
313
Tim Peters6d6c1a32001-08-02 04:15:00 +0000314 /* Find the nearest base with a different tp_dealloc */
315 type = self->ob_type;
Guido van Rossum14227b42001-12-06 02:35:58 +0000316 base = type->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000317 while ((f = base->tp_dealloc) == subtype_dealloc) {
318 base = base->tp_base;
319 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000320 }
321
322 /* Clear __slots__ variables */
323 if (type->tp_basicsize != base->tp_basicsize &&
324 type->tp_itemsize == 0)
325 {
326 char *addr = ((char *)self);
327 char *p = addr + base->tp_basicsize;
328 char *q = addr + type->tp_basicsize;
329 for (; p < q; p += sizeof(PyObject *)) {
330 PyObject **pp;
331 if (p == addr + type->tp_dictoffset ||
332 p == addr + type->tp_weaklistoffset)
333 continue;
334 pp = (PyObject **)p;
335 if (*pp != NULL) {
336 Py_DECREF(*pp);
337 *pp = NULL;
Guido van Rossum33bab012001-12-05 22:45:48 +0000338 }
339 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000340 }
341
342 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000343 if (type->tp_dictoffset && !base->tp_dictoffset) {
344 PyObject **dictptr = _PyObject_GetDictPtr(self);
345 if (dictptr != NULL) {
346 PyObject *dict = *dictptr;
347 if (dict != NULL) {
348 Py_DECREF(dict);
349 *dictptr = NULL;
350 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351 }
352 }
353
Guido van Rossum9676b222001-08-17 20:32:36 +0000354 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000355 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000356 PyObject_ClearWeakRefs(self);
357
Tim Peters6d6c1a32001-08-02 04:15:00 +0000358 /* Finalize GC if the base doesn't do GC and we do */
359 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000360 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000361
362 /* Call the base tp_dealloc() */
363 assert(f);
364 f(self);
365
366 /* Can't reference self beyond this point */
367 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
368 Py_DECREF(type);
369 }
370}
371
Tim Peters6d6c1a32001-08-02 04:15:00 +0000372staticforward PyTypeObject *solid_base(PyTypeObject *type);
373
374typedef struct {
375 PyTypeObject type;
376 PyNumberMethods as_number;
377 PySequenceMethods as_sequence;
378 PyMappingMethods as_mapping;
379 PyBufferProcs as_buffer;
380 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000381 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000382} etype;
383
384/* type test with subclassing support */
385
386int
387PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
388{
389 PyObject *mro;
390
Guido van Rossum9478d072001-09-07 18:52:13 +0000391 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
392 return b == a || b == &PyBaseObject_Type;
393
Tim Peters6d6c1a32001-08-02 04:15:00 +0000394 mro = a->tp_mro;
395 if (mro != NULL) {
396 /* Deal with multiple inheritance without recursion
397 by walking the MRO tuple */
398 int i, n;
399 assert(PyTuple_Check(mro));
400 n = PyTuple_GET_SIZE(mro);
401 for (i = 0; i < n; i++) {
402 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
403 return 1;
404 }
405 return 0;
406 }
407 else {
408 /* a is not completely initilized yet; follow tp_base */
409 do {
410 if (a == b)
411 return 1;
412 a = a->tp_base;
413 } while (a != NULL);
414 return b == &PyBaseObject_Type;
415 }
416}
417
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000418/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000419 without looking in the instance dictionary
420 (so we can't use PyObject_GetAttr) but still binding
421 it to the instance. The arguments are the object,
422 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000423 static variable used to cache the interned Python string.
424
425 Two variants:
426
427 - lookup_maybe() returns NULL without raising an exception
428 when the _PyType_Lookup() call fails;
429
430 - lookup_method() always raises an exception upon errors.
431*/
Guido van Rossum60718732001-08-28 17:47:51 +0000432
433static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000434lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000435{
436 PyObject *res;
437
438 if (*attrobj == NULL) {
439 *attrobj = PyString_InternFromString(attrstr);
440 if (*attrobj == NULL)
441 return NULL;
442 }
443 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000444 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000445 descrgetfunc f;
446 if ((f = res->ob_type->tp_descr_get) == NULL)
447 Py_INCREF(res);
448 else
449 res = f(res, self, (PyObject *)(self->ob_type));
450 }
451 return res;
452}
453
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000454static PyObject *
455lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
456{
457 PyObject *res = lookup_maybe(self, attrstr, attrobj);
458 if (res == NULL && !PyErr_Occurred())
459 PyErr_SetObject(PyExc_AttributeError, *attrobj);
460 return res;
461}
462
Guido van Rossum2730b132001-08-28 18:22:14 +0000463/* A variation of PyObject_CallMethod that uses lookup_method()
464 instead of PyObject_GetAttrString(). This uses the same convention
465 as lookup_method to cache the interned name string object. */
466
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000467static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000468call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
469{
470 va_list va;
471 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000472 va_start(va, format);
473
Guido van Rossumda21c012001-10-03 00:50:18 +0000474 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000475 if (func == NULL) {
476 va_end(va);
477 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000478 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000479 return NULL;
480 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000481
482 if (format && *format)
483 args = Py_VaBuildValue(format, va);
484 else
485 args = PyTuple_New(0);
486
487 va_end(va);
488
489 if (args == NULL)
490 return NULL;
491
492 assert(PyTuple_Check(args));
493 retval = PyObject_Call(func, args, NULL);
494
495 Py_DECREF(args);
496 Py_DECREF(func);
497
498 return retval;
499}
500
501/* Clone of call_method() that returns NotImplemented when the lookup fails. */
502
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000503static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000504call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
505{
506 va_list va;
507 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000508 va_start(va, format);
509
Guido van Rossumda21c012001-10-03 00:50:18 +0000510 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000511 if (func == NULL) {
512 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000513 if (!PyErr_Occurred()) {
514 Py_INCREF(Py_NotImplemented);
515 return Py_NotImplemented;
516 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000517 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000518 }
519
520 if (format && *format)
521 args = Py_VaBuildValue(format, va);
522 else
523 args = PyTuple_New(0);
524
525 va_end(va);
526
Guido van Rossum717ce002001-09-14 16:58:08 +0000527 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000528 return NULL;
529
Guido van Rossum717ce002001-09-14 16:58:08 +0000530 assert(PyTuple_Check(args));
531 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000532
533 Py_DECREF(args);
534 Py_DECREF(func);
535
536 return retval;
537}
538
Tim Peters6d6c1a32001-08-02 04:15:00 +0000539/* Method resolution order algorithm from "Putting Metaclasses to Work"
540 by Forman and Danforth (Addison-Wesley 1999). */
541
542static int
543conservative_merge(PyObject *left, PyObject *right)
544{
545 int left_size;
546 int right_size;
547 int i, j, r, ok;
548 PyObject *temp, *rr;
549
550 assert(PyList_Check(left));
551 assert(PyList_Check(right));
552
553 again:
554 left_size = PyList_GET_SIZE(left);
555 right_size = PyList_GET_SIZE(right);
556 for (i = 0; i < left_size; i++) {
557 for (j = 0; j < right_size; j++) {
558 if (PyList_GET_ITEM(left, i) ==
559 PyList_GET_ITEM(right, j)) {
560 /* found a merge point */
561 temp = PyList_New(0);
562 if (temp == NULL)
563 return -1;
564 for (r = 0; r < j; r++) {
565 rr = PyList_GET_ITEM(right, r);
566 ok = PySequence_Contains(left, rr);
567 if (ok < 0) {
568 Py_DECREF(temp);
569 return -1;
570 }
571 if (!ok) {
572 ok = PyList_Append(temp, rr);
573 if (ok < 0) {
574 Py_DECREF(temp);
575 return -1;
576 }
577 }
578 }
579 ok = PyList_SetSlice(left, i, i, temp);
580 Py_DECREF(temp);
581 if (ok < 0)
582 return -1;
583 ok = PyList_SetSlice(right, 0, j+1, NULL);
584 if (ok < 0)
585 return -1;
586 goto again;
587 }
588 }
589 }
590 return PyList_SetSlice(left, left_size, left_size, right);
591}
592
593static int
594serious_order_disagreements(PyObject *left, PyObject *right)
595{
596 return 0; /* XXX later -- for now, we cheat: "don't do that" */
597}
598
Tim Petersa91e9642001-11-14 23:32:33 +0000599static int
600fill_classic_mro(PyObject *mro, PyObject *cls)
601{
602 PyObject *bases, *base;
603 int i, n;
604
605 assert(PyList_Check(mro));
606 assert(PyClass_Check(cls));
607 i = PySequence_Contains(mro, cls);
608 if (i < 0)
609 return -1;
610 if (!i) {
611 if (PyList_Append(mro, cls) < 0)
612 return -1;
613 }
614 bases = ((PyClassObject *)cls)->cl_bases;
615 assert(bases && PyTuple_Check(bases));
616 n = PyTuple_GET_SIZE(bases);
617 for (i = 0; i < n; i++) {
618 base = PyTuple_GET_ITEM(bases, i);
619 if (fill_classic_mro(mro, base) < 0)
620 return -1;
621 }
622 return 0;
623}
624
625static PyObject *
626classic_mro(PyObject *cls)
627{
628 PyObject *mro;
629
630 assert(PyClass_Check(cls));
631 mro = PyList_New(0);
632 if (mro != NULL) {
633 if (fill_classic_mro(mro, cls) == 0)
634 return mro;
635 Py_DECREF(mro);
636 }
637 return NULL;
638}
639
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640static PyObject *
641mro_implementation(PyTypeObject *type)
642{
643 int i, n, ok;
644 PyObject *bases, *result;
645
646 bases = type->tp_bases;
647 n = PyTuple_GET_SIZE(bases);
648 result = Py_BuildValue("[O]", (PyObject *)type);
649 if (result == NULL)
650 return NULL;
651 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000652 PyObject *base = PyTuple_GET_ITEM(bases, i);
653 PyObject *parentMRO;
654 if (PyType_Check(base))
655 parentMRO = PySequence_List(
656 ((PyTypeObject*)base)->tp_mro);
657 else
658 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659 if (parentMRO == NULL) {
660 Py_DECREF(result);
661 return NULL;
662 }
663 if (serious_order_disagreements(result, parentMRO)) {
664 Py_DECREF(result);
665 return NULL;
666 }
667 ok = conservative_merge(result, parentMRO);
668 Py_DECREF(parentMRO);
669 if (ok < 0) {
670 Py_DECREF(result);
671 return NULL;
672 }
673 }
674 return result;
675}
676
677static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000678mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679{
680 PyTypeObject *type = (PyTypeObject *)self;
681
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682 return mro_implementation(type);
683}
684
685static int
686mro_internal(PyTypeObject *type)
687{
688 PyObject *mro, *result, *tuple;
689
690 if (type->ob_type == &PyType_Type) {
691 result = mro_implementation(type);
692 }
693 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000694 static PyObject *mro_str;
695 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696 if (mro == NULL)
697 return -1;
698 result = PyObject_CallObject(mro, NULL);
699 Py_DECREF(mro);
700 }
701 if (result == NULL)
702 return -1;
703 tuple = PySequence_Tuple(result);
704 Py_DECREF(result);
705 type->tp_mro = tuple;
706 return 0;
707}
708
709
710/* Calculate the best base amongst multiple base classes.
711 This is the first one that's on the path to the "solid base". */
712
713static PyTypeObject *
714best_base(PyObject *bases)
715{
716 int i, n;
717 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000718 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719
720 assert(PyTuple_Check(bases));
721 n = PyTuple_GET_SIZE(bases);
722 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000723 base = NULL;
724 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000725 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000726 base_proto = PyTuple_GET_ITEM(bases, i);
727 if (PyClass_Check(base_proto))
728 continue;
729 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000730 PyErr_SetString(
731 PyExc_TypeError,
732 "bases must be types");
733 return NULL;
734 }
Tim Petersa91e9642001-11-14 23:32:33 +0000735 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000736 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000737 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000738 return NULL;
739 }
740 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000741 if (winner == NULL) {
742 winner = candidate;
743 base = base_i;
744 }
745 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000746 ;
747 else if (PyType_IsSubtype(candidate, winner)) {
748 winner = candidate;
749 base = base_i;
750 }
751 else {
752 PyErr_SetString(
753 PyExc_TypeError,
754 "multiple bases have "
755 "instance lay-out conflict");
756 return NULL;
757 }
758 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000759 if (base == NULL)
760 PyErr_SetString(PyExc_TypeError,
761 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762 return base;
763}
764
765static int
766extra_ivars(PyTypeObject *type, PyTypeObject *base)
767{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000768 size_t t_size = type->tp_basicsize;
769 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000770
Guido van Rossum9676b222001-08-17 20:32:36 +0000771 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772 if (type->tp_itemsize || base->tp_itemsize) {
773 /* If itemsize is involved, stricter rules */
774 return t_size != b_size ||
775 type->tp_itemsize != base->tp_itemsize;
776 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000777 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
778 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
779 t_size -= sizeof(PyObject *);
780 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
781 type->tp_dictoffset + sizeof(PyObject *) == t_size)
782 t_size -= sizeof(PyObject *);
783
784 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000785}
786
787static PyTypeObject *
788solid_base(PyTypeObject *type)
789{
790 PyTypeObject *base;
791
792 if (type->tp_base)
793 base = solid_base(type->tp_base);
794 else
795 base = &PyBaseObject_Type;
796 if (extra_ivars(type, base))
797 return type;
798 else
799 return base;
800}
801
802staticforward void object_dealloc(PyObject *);
803staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000804staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000805staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000806
807static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000808subtype_dict(PyObject *obj, void *context)
809{
810 PyObject **dictptr = _PyObject_GetDictPtr(obj);
811 PyObject *dict;
812
813 if (dictptr == NULL) {
814 PyErr_SetString(PyExc_AttributeError,
815 "This object has no __dict__");
816 return NULL;
817 }
818 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000819 if (dict == NULL)
820 *dictptr = dict = PyDict_New();
821 Py_XINCREF(dict);
822 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000823}
824
Guido van Rossum6661be32001-10-26 04:26:12 +0000825static int
826subtype_setdict(PyObject *obj, PyObject *value, void *context)
827{
828 PyObject **dictptr = _PyObject_GetDictPtr(obj);
829 PyObject *dict;
830
831 if (dictptr == NULL) {
832 PyErr_SetString(PyExc_AttributeError,
833 "This object has no __dict__");
834 return -1;
835 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000836 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000837 PyErr_SetString(PyExc_TypeError,
838 "__dict__ must be set to a dictionary");
839 return -1;
840 }
841 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000842 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000843 *dictptr = value;
844 Py_XDECREF(dict);
845 return 0;
846}
847
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000848static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000849 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000850 {0},
851};
852
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000853/* bozo: __getstate__ that raises TypeError */
854
855static PyObject *
856bozo_func(PyObject *self, PyObject *args)
857{
858 PyErr_SetString(PyExc_TypeError,
859 "a class that defines __slots__ without "
860 "defining __getstate__ cannot be pickled");
861 return NULL;
862}
863
864static PyMethodDef bozo_ml = {"__getstate__", bozo_func};
865
866static PyObject *bozo_obj = NULL;
867
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000868static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
870{
871 PyObject *name, *bases, *dict;
872 static char *kwlist[] = {"name", "bases", "dict", 0};
873 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000874 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000876 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000877 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878
Tim Peters3abca122001-10-27 19:37:48 +0000879 assert(args != NULL && PyTuple_Check(args));
880 assert(kwds == NULL || PyDict_Check(kwds));
881
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000882 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000883 {
884 const int nargs = PyTuple_GET_SIZE(args);
885 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
886
887 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
888 PyObject *x = PyTuple_GET_ITEM(args, 0);
889 Py_INCREF(x->ob_type);
890 return (PyObject *) x->ob_type;
891 }
892
893 /* SF bug 475327 -- if that didn't trigger, we need 3
894 arguments. but PyArg_ParseTupleAndKeywords below may give
895 a msg saying type() needs exactly 3. */
896 if (nargs + nkwds != 3) {
897 PyErr_SetString(PyExc_TypeError,
898 "type() takes 1 or 3 arguments");
899 return NULL;
900 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000901 }
902
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000903 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000904 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
905 &name,
906 &PyTuple_Type, &bases,
907 &PyDict_Type, &dict))
908 return NULL;
909
910 /* Determine the proper metatype to deal with this,
911 and check for metatype conflicts while we're at it.
912 Note that if some other metatype wins to contract,
913 it's possible that its instances are not types. */
914 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000915 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000916 for (i = 0; i < nbases; i++) {
917 tmp = PyTuple_GET_ITEM(bases, i);
918 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000919 if (tmptype == &PyClass_Type)
920 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000921 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000922 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000923 if (PyType_IsSubtype(tmptype, winner)) {
924 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000925 continue;
926 }
927 PyErr_SetString(PyExc_TypeError,
928 "metatype conflict among bases");
929 return NULL;
930 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000931 if (winner != metatype) {
932 if (winner->tp_new != type_new) /* Pass it to the winner */
933 return winner->tp_new(winner, args, kwds);
934 metatype = winner;
935 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000936
937 /* Adjust for empty tuple bases */
938 if (nbases == 0) {
939 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
940 if (bases == NULL)
941 return NULL;
942 nbases = 1;
943 }
944 else
945 Py_INCREF(bases);
946
947 /* XXX From here until type is allocated, "return NULL" leaks bases! */
948
949 /* Calculate best base, and check that all bases are type objects */
950 base = best_base(bases);
951 if (base == NULL)
952 return NULL;
953 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
954 PyErr_Format(PyExc_TypeError,
955 "type '%.100s' is not an acceptable base type",
956 base->tp_name);
957 return NULL;
958 }
959
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960 /* Check for a __slots__ sequence variable in dict, and count it */
961 slots = PyDict_GetItemString(dict, "__slots__");
962 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000963 add_dict = 0;
964 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965 if (slots != NULL) {
966 /* Make it into a tuple */
967 if (PyString_Check(slots))
968 slots = Py_BuildValue("(O)", slots);
969 else
970 slots = PySequence_Tuple(slots);
971 if (slots == NULL)
972 return NULL;
973 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000974 if (nslots > 0 && base->tp_itemsize != 0) {
975 PyErr_Format(PyExc_TypeError,
976 "nonempty __slots__ "
977 "not supported for subtype of '%s'",
978 base->tp_name);
979 return NULL;
980 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981 for (i = 0; i < nslots; i++) {
982 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
983 PyErr_SetString(PyExc_TypeError,
984 "__slots__ must be a sequence of strings");
985 Py_DECREF(slots);
986 return NULL;
987 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000988 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989 }
990 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000991 if (slots != NULL) {
992 /* See if *this* class defines __getstate__ */
993 PyObject *getstate = PyDict_GetItemString(dict,
994 "__getstate__");
995 if (getstate == NULL) {
996 /* If not, provide a bozo that raises TypeError */
997 if (bozo_obj == NULL) {
998 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
999 if (bozo_obj == NULL) {
1000 /* XXX decref various things */
1001 return NULL;
1002 }
1003 }
1004 if (PyDict_SetItemString(dict,
1005 "__getstate__",
1006 bozo_obj) < 0) {
1007 /* XXX decref various things */
1008 return NULL;
1009 }
1010 }
1011 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012 if (slots == NULL && base->tp_dictoffset == 0 &&
1013 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001014 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001015 add_dict++;
1016 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001017 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1018 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001019 nslots++;
1020 add_weak++;
1021 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022
1023 /* XXX From here until type is safely allocated,
1024 "return NULL" may leak slots! */
1025
1026 /* Allocate the type object */
1027 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1028 if (type == NULL)
1029 return NULL;
1030
1031 /* Keep name and slots alive in the extended type object */
1032 et = (etype *)type;
1033 Py_INCREF(name);
1034 et->name = name;
1035 et->slots = slots;
1036
Guido van Rossumdc91b992001-08-08 22:26:22 +00001037 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1039 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001040 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1041 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001042
1043 /* It's a new-style number unless it specifically inherits any
1044 old-style numeric behavior */
1045 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1046 (base->tp_as_number == NULL))
1047 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1048
1049 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050 type->tp_as_number = &et->as_number;
1051 type->tp_as_sequence = &et->as_sequence;
1052 type->tp_as_mapping = &et->as_mapping;
1053 type->tp_as_buffer = &et->as_buffer;
1054 type->tp_name = PyString_AS_STRING(name);
1055
1056 /* Set tp_base and tp_bases */
1057 type->tp_bases = bases;
1058 Py_INCREF(base);
1059 type->tp_base = base;
1060
Guido van Rossum687ae002001-10-15 22:03:32 +00001061 /* Initialize tp_dict from passed-in dict */
1062 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063 if (dict == NULL) {
1064 Py_DECREF(type);
1065 return NULL;
1066 }
1067
Guido van Rossumc3542212001-08-16 09:18:56 +00001068 /* Set __module__ in the dict */
1069 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1070 tmp = PyEval_GetGlobals();
1071 if (tmp != NULL) {
1072 tmp = PyDict_GetItemString(tmp, "__name__");
1073 if (tmp != NULL) {
1074 if (PyDict_SetItemString(dict, "__module__",
1075 tmp) < 0)
1076 return NULL;
1077 }
1078 }
1079 }
1080
Tim Peters2f93e282001-10-04 05:27:00 +00001081 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00001082 and is a string. Note that the tp_doc slot will only be used
1083 by C code -- python code will use the version in tp_dict, so
1084 it isn't that important that non string __doc__'s are ignored.
Tim Peters2f93e282001-10-04 05:27:00 +00001085 */
1086 {
1087 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1088 if (doc != NULL && PyString_Check(doc)) {
1089 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001090 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001091 if (type->tp_doc == NULL) {
1092 Py_DECREF(type);
1093 return NULL;
1094 }
1095 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1096 }
1097 }
1098
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 /* Special-case __new__: if it's a plain function,
1100 make it a static function */
1101 tmp = PyDict_GetItemString(dict, "__new__");
1102 if (tmp != NULL && PyFunction_Check(tmp)) {
1103 tmp = PyStaticMethod_New(tmp);
1104 if (tmp == NULL) {
1105 Py_DECREF(type);
1106 return NULL;
1107 }
1108 PyDict_SetItemString(dict, "__new__", tmp);
1109 Py_DECREF(tmp);
1110 }
1111
1112 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1113 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001114 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115 if (slots != NULL) {
1116 for (i = 0; i < nslots; i++, mp++) {
1117 mp->name = PyString_AS_STRING(
1118 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001119 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001121 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001122 strcmp(mp->name, "__weakref__") == 0) {
1123 mp->type = T_OBJECT;
Guido van Rossum9676b222001-08-17 20:32:36 +00001124 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001125 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126 slotoffset += sizeof(PyObject *);
1127 }
1128 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001129 else {
1130 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001131 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001132 type->tp_dictoffset =
1133 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001134 else
1135 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001136 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001137 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001138 }
1139 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001140 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001141 type->tp_weaklistoffset = slotoffset;
1142 mp->name = "__weakref__";
1143 mp->type = T_OBJECT;
1144 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001145 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001146 mp++;
1147 slotoffset += sizeof(PyObject *);
1148 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 }
1150 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001151 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001152 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153
1154 /* Special case some slots */
1155 if (type->tp_dictoffset != 0 || nslots > 0) {
1156 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1157 type->tp_getattro = PyObject_GenericGetAttr;
1158 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1159 type->tp_setattro = PyObject_GenericSetAttr;
1160 }
1161 type->tp_dealloc = subtype_dealloc;
1162
Guido van Rossum9475a232001-10-05 20:51:39 +00001163 /* Enable GC unless there are really no instance variables possible */
1164 if (!(type->tp_basicsize == sizeof(PyObject) &&
1165 type->tp_itemsize == 0))
1166 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1167
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168 /* Always override allocation strategy to use regular heap */
1169 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001170 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1171 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001172 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001173 type->tp_clear = base->tp_clear;
1174 }
1175 else
1176 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177
1178 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001179 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180 Py_DECREF(type);
1181 return NULL;
1182 }
1183
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001184 /* Put the proper slots in place */
1185 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001186
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 return (PyObject *)type;
1188}
1189
1190/* Internal API to look for a name through the MRO.
1191 This returns a borrowed reference, and doesn't set an exception! */
1192PyObject *
1193_PyType_Lookup(PyTypeObject *type, PyObject *name)
1194{
1195 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001196 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001197
Guido van Rossum687ae002001-10-15 22:03:32 +00001198 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 mro = type->tp_mro;
1200 assert(PyTuple_Check(mro));
1201 n = PyTuple_GET_SIZE(mro);
1202 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001203 base = PyTuple_GET_ITEM(mro, i);
1204 if (PyClass_Check(base))
1205 dict = ((PyClassObject *)base)->cl_dict;
1206 else {
1207 assert(PyType_Check(base));
1208 dict = ((PyTypeObject *)base)->tp_dict;
1209 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 assert(dict && PyDict_Check(dict));
1211 res = PyDict_GetItem(dict, name);
1212 if (res != NULL)
1213 return res;
1214 }
1215 return NULL;
1216}
1217
1218/* This is similar to PyObject_GenericGetAttr(),
1219 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1220static PyObject *
1221type_getattro(PyTypeObject *type, PyObject *name)
1222{
1223 PyTypeObject *metatype = type->ob_type;
1224 PyObject *descr, *res;
1225 descrgetfunc f;
1226
1227 /* Initialize this type (we'll assume the metatype is initialized) */
1228 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001229 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001230 return NULL;
1231 }
1232
1233 /* Get a descriptor from the metatype */
1234 descr = _PyType_Lookup(metatype, name);
1235 f = NULL;
1236 if (descr != NULL) {
1237 f = descr->ob_type->tp_descr_get;
1238 if (f != NULL && PyDescr_IsData(descr))
1239 return f(descr,
1240 (PyObject *)type, (PyObject *)metatype);
1241 }
1242
Guido van Rossum687ae002001-10-15 22:03:32 +00001243 /* Look in tp_dict of this type and its bases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 res = _PyType_Lookup(type, name);
1245 if (res != NULL) {
1246 f = res->ob_type->tp_descr_get;
1247 if (f != NULL)
1248 return f(res, (PyObject *)NULL, (PyObject *)type);
1249 Py_INCREF(res);
1250 return res;
1251 }
1252
1253 /* Use the descriptor from the metatype */
1254 if (f != NULL) {
1255 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1256 return res;
1257 }
1258 if (descr != NULL) {
1259 Py_INCREF(descr);
1260 return descr;
1261 }
1262
1263 /* Give up */
1264 PyErr_Format(PyExc_AttributeError,
1265 "type object '%.50s' has no attribute '%.400s'",
1266 type->tp_name, PyString_AS_STRING(name));
1267 return NULL;
1268}
1269
1270static int
1271type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1272{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001273 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1274 PyErr_Format(
1275 PyExc_TypeError,
1276 "can't set attributes of built-in/extension type '%s'",
1277 type->tp_name);
1278 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001279 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001280 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1281 return -1;
1282 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283}
1284
1285static void
1286type_dealloc(PyTypeObject *type)
1287{
1288 etype *et;
1289
1290 /* Assert this is a heap-allocated type object */
1291 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001292 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001293 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 et = (etype *)type;
1295 Py_XDECREF(type->tp_base);
1296 Py_XDECREF(type->tp_dict);
1297 Py_XDECREF(type->tp_bases);
1298 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001299 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001300 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301 Py_XDECREF(et->name);
1302 Py_XDECREF(et->slots);
1303 type->ob_type->tp_free((PyObject *)type);
1304}
1305
Guido van Rossum1c450732001-10-08 15:18:27 +00001306static PyObject *
1307type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1308{
1309 PyObject *list, *raw, *ref;
1310 int i, n;
1311
1312 list = PyList_New(0);
1313 if (list == NULL)
1314 return NULL;
1315 raw = type->tp_subclasses;
1316 if (raw == NULL)
1317 return list;
1318 assert(PyList_Check(raw));
1319 n = PyList_GET_SIZE(raw);
1320 for (i = 0; i < n; i++) {
1321 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001322 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001323 ref = PyWeakref_GET_OBJECT(ref);
1324 if (ref != Py_None) {
1325 if (PyList_Append(list, ref) < 0) {
1326 Py_DECREF(list);
1327 return NULL;
1328 }
1329 }
1330 }
1331 return list;
1332}
1333
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001335 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001336 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001337 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1338 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 {0}
1340};
1341
1342static char type_doc[] =
1343"type(object) -> the object's type\n"
1344"type(name, bases, dict) -> a new type";
1345
Guido van Rossum048eb752001-10-02 21:24:57 +00001346static int
1347type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1348{
1349 etype *et;
1350 int err;
1351
1352 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1353 return 0;
1354
1355 et = (etype *)type;
1356
1357#define VISIT(SLOT) \
1358 if (SLOT) { \
1359 err = visit((PyObject *)(SLOT), arg); \
1360 if (err) \
1361 return err; \
1362 }
1363
1364 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001365 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001366 VISIT(type->tp_mro);
1367 VISIT(type->tp_bases);
1368 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001369 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001370 VISIT(et->slots);
1371
1372#undef VISIT
1373
1374 return 0;
1375}
1376
1377static int
1378type_clear(PyTypeObject *type)
1379{
1380 etype *et;
1381 PyObject *tmp;
1382
1383 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1384 return 0;
1385
1386 et = (etype *)type;
1387
1388#define CLEAR(SLOT) \
1389 if (SLOT) { \
1390 tmp = (PyObject *)(SLOT); \
1391 SLOT = NULL; \
1392 Py_DECREF(tmp); \
1393 }
1394
1395 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001396 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001397 CLEAR(type->tp_mro);
1398 CLEAR(type->tp_bases);
1399 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001400 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001401 CLEAR(et->slots);
1402
Tim Peters2f93e282001-10-04 05:27:00 +00001403 if (type->tp_doc != NULL) {
1404 PyObject_FREE(type->tp_doc);
1405 type->tp_doc = NULL;
1406 }
1407
Guido van Rossum048eb752001-10-02 21:24:57 +00001408#undef CLEAR
1409
1410 return 0;
1411}
1412
1413static int
1414type_is_gc(PyTypeObject *type)
1415{
1416 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1417}
1418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001419PyTypeObject PyType_Type = {
1420 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001421 0, /* ob_size */
1422 "type", /* tp_name */
1423 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001424 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 (destructor)type_dealloc, /* tp_dealloc */
1426 0, /* tp_print */
1427 0, /* tp_getattr */
1428 0, /* tp_setattr */
1429 type_compare, /* tp_compare */
1430 (reprfunc)type_repr, /* tp_repr */
1431 0, /* tp_as_number */
1432 0, /* tp_as_sequence */
1433 0, /* tp_as_mapping */
1434 (hashfunc)_Py_HashPointer, /* tp_hash */
1435 (ternaryfunc)type_call, /* tp_call */
1436 0, /* tp_str */
1437 (getattrofunc)type_getattro, /* tp_getattro */
1438 (setattrofunc)type_setattro, /* tp_setattro */
1439 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001440 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1441 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001443 (traverseproc)type_traverse, /* tp_traverse */
1444 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001446 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447 0, /* tp_iter */
1448 0, /* tp_iternext */
1449 type_methods, /* tp_methods */
1450 type_members, /* tp_members */
1451 type_getsets, /* tp_getset */
1452 0, /* tp_base */
1453 0, /* tp_dict */
1454 0, /* tp_descr_get */
1455 0, /* tp_descr_set */
1456 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1457 0, /* tp_init */
1458 0, /* tp_alloc */
1459 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001460 _PyObject_GC_Del, /* tp_free */
1461 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001462};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463
1464
1465/* The base type of all types (eventually)... except itself. */
1466
1467static int
1468object_init(PyObject *self, PyObject *args, PyObject *kwds)
1469{
1470 return 0;
1471}
1472
1473static void
1474object_dealloc(PyObject *self)
1475{
1476 self->ob_type->tp_free(self);
1477}
1478
Guido van Rossum8e248182001-08-12 05:17:56 +00001479static PyObject *
1480object_repr(PyObject *self)
1481{
Guido van Rossum76e69632001-08-16 18:52:43 +00001482 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001483 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001484
Guido van Rossum76e69632001-08-16 18:52:43 +00001485 type = self->ob_type;
1486 mod = type_module(type, NULL);
1487 if (mod == NULL)
1488 PyErr_Clear();
1489 else if (!PyString_Check(mod)) {
1490 Py_DECREF(mod);
1491 mod = NULL;
1492 }
1493 name = type_name(type, NULL);
1494 if (name == NULL)
1495 return NULL;
1496 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001497 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001498 PyString_AS_STRING(mod),
1499 PyString_AS_STRING(name),
1500 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001501 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001502 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001503 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001504 Py_XDECREF(mod);
1505 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001506 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001507}
1508
Guido van Rossumb8f63662001-08-15 23:57:02 +00001509static PyObject *
1510object_str(PyObject *self)
1511{
1512 unaryfunc f;
1513
1514 f = self->ob_type->tp_repr;
1515 if (f == NULL)
1516 f = object_repr;
1517 return f(self);
1518}
1519
Guido van Rossum8e248182001-08-12 05:17:56 +00001520static long
1521object_hash(PyObject *self)
1522{
1523 return _Py_HashPointer(self);
1524}
Guido van Rossum8e248182001-08-12 05:17:56 +00001525
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001526static PyObject *
1527object_get_class(PyObject *self, void *closure)
1528{
1529 Py_INCREF(self->ob_type);
1530 return (PyObject *)(self->ob_type);
1531}
1532
1533static int
1534equiv_structs(PyTypeObject *a, PyTypeObject *b)
1535{
1536 return a == b ||
1537 (a != NULL &&
1538 b != NULL &&
1539 a->tp_basicsize == b->tp_basicsize &&
1540 a->tp_itemsize == b->tp_itemsize &&
1541 a->tp_dictoffset == b->tp_dictoffset &&
1542 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1543 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1544 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1545}
1546
1547static int
1548same_slots_added(PyTypeObject *a, PyTypeObject *b)
1549{
1550 PyTypeObject *base = a->tp_base;
1551 int size;
1552
1553 if (base != b->tp_base)
1554 return 0;
1555 if (equiv_structs(a, base) && equiv_structs(b, base))
1556 return 1;
1557 size = base->tp_basicsize;
1558 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1559 size += sizeof(PyObject *);
1560 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1561 size += sizeof(PyObject *);
1562 return size == a->tp_basicsize && size == b->tp_basicsize;
1563}
1564
1565static int
1566object_set_class(PyObject *self, PyObject *value, void *closure)
1567{
1568 PyTypeObject *old = self->ob_type;
1569 PyTypeObject *new, *newbase, *oldbase;
1570
1571 if (!PyType_Check(value)) {
1572 PyErr_Format(PyExc_TypeError,
1573 "__class__ must be set to new-style class, not '%s' object",
1574 value->ob_type->tp_name);
1575 return -1;
1576 }
1577 new = (PyTypeObject *)value;
1578 newbase = new;
1579 oldbase = old;
1580 while (equiv_structs(newbase, newbase->tp_base))
1581 newbase = newbase->tp_base;
1582 while (equiv_structs(oldbase, oldbase->tp_base))
1583 oldbase = oldbase->tp_base;
1584 if (newbase != oldbase &&
1585 (newbase->tp_base != oldbase->tp_base ||
1586 !same_slots_added(newbase, oldbase))) {
1587 PyErr_Format(PyExc_TypeError,
1588 "__class__ assignment: "
1589 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001590 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001591 old->tp_name);
1592 return -1;
1593 }
1594 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1595 Py_INCREF(new);
1596 }
1597 self->ob_type = new;
1598 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1599 Py_DECREF(old);
1600 }
1601 return 0;
1602}
1603
1604static PyGetSetDef object_getsets[] = {
1605 {"__class__", object_get_class, object_set_class,
1606 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 {0}
1608};
1609
Guido van Rossum3926a632001-09-25 16:25:58 +00001610static PyObject *
1611object_reduce(PyObject *self, PyObject *args)
1612{
1613 /* Call copy_reg._reduce(self) */
1614 static PyObject *copy_reg_str;
1615 PyObject *copy_reg, *res;
1616
1617 if (!copy_reg_str) {
1618 copy_reg_str = PyString_InternFromString("copy_reg");
1619 if (copy_reg_str == NULL)
1620 return NULL;
1621 }
1622 copy_reg = PyImport_Import(copy_reg_str);
1623 if (!copy_reg)
1624 return NULL;
1625 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1626 Py_DECREF(copy_reg);
1627 return res;
1628}
1629
1630static PyMethodDef object_methods[] = {
1631 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1632 {0}
1633};
1634
Tim Peters6d6c1a32001-08-02 04:15:00 +00001635PyTypeObject PyBaseObject_Type = {
1636 PyObject_HEAD_INIT(&PyType_Type)
1637 0, /* ob_size */
1638 "object", /* tp_name */
1639 sizeof(PyObject), /* tp_basicsize */
1640 0, /* tp_itemsize */
1641 (destructor)object_dealloc, /* tp_dealloc */
1642 0, /* tp_print */
1643 0, /* tp_getattr */
1644 0, /* tp_setattr */
1645 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001646 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647 0, /* tp_as_number */
1648 0, /* tp_as_sequence */
1649 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001650 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001652 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001654 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 0, /* tp_as_buffer */
1656 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1657 "The most base type", /* tp_doc */
1658 0, /* tp_traverse */
1659 0, /* tp_clear */
1660 0, /* tp_richcompare */
1661 0, /* tp_weaklistoffset */
1662 0, /* tp_iter */
1663 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001664 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001665 0, /* tp_members */
1666 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 0, /* tp_base */
1668 0, /* tp_dict */
1669 0, /* tp_descr_get */
1670 0, /* tp_descr_set */
1671 0, /* tp_dictoffset */
1672 object_init, /* tp_init */
1673 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001674 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001675 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676};
1677
1678
1679/* Initialize the __dict__ in a type object */
1680
1681static int
1682add_methods(PyTypeObject *type, PyMethodDef *meth)
1683{
Guido van Rossum687ae002001-10-15 22:03:32 +00001684 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001685
1686 for (; meth->ml_name != NULL; meth++) {
1687 PyObject *descr;
1688 if (PyDict_GetItemString(dict, meth->ml_name))
1689 continue;
1690 descr = PyDescr_NewMethod(type, meth);
1691 if (descr == NULL)
1692 return -1;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001693 if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 return -1;
1695 Py_DECREF(descr);
1696 }
1697 return 0;
1698}
1699
1700static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001701add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702{
Guido van Rossum687ae002001-10-15 22:03:32 +00001703 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704
1705 for (; memb->name != NULL; memb++) {
1706 PyObject *descr;
1707 if (PyDict_GetItemString(dict, memb->name))
1708 continue;
1709 descr = PyDescr_NewMember(type, memb);
1710 if (descr == NULL)
1711 return -1;
1712 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1713 return -1;
1714 Py_DECREF(descr);
1715 }
1716 return 0;
1717}
1718
1719static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001720add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721{
Guido van Rossum687ae002001-10-15 22:03:32 +00001722 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723
1724 for (; gsp->name != NULL; gsp++) {
1725 PyObject *descr;
1726 if (PyDict_GetItemString(dict, gsp->name))
1727 continue;
1728 descr = PyDescr_NewGetSet(type, gsp);
1729
1730 if (descr == NULL)
1731 return -1;
1732 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1733 return -1;
1734 Py_DECREF(descr);
1735 }
1736 return 0;
1737}
1738
Guido van Rossum13d52f02001-08-10 21:24:08 +00001739static void
1740inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741{
1742 int oldsize, newsize;
1743
Guido van Rossum13d52f02001-08-10 21:24:08 +00001744 /* Special flag magic */
1745 if (!type->tp_as_buffer && base->tp_as_buffer) {
1746 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1747 type->tp_flags |=
1748 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1749 }
1750 if (!type->tp_as_sequence && base->tp_as_sequence) {
1751 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1752 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1753 }
1754 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1755 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1756 if ((!type->tp_as_number && base->tp_as_number) ||
1757 (!type->tp_as_sequence && base->tp_as_sequence)) {
1758 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1759 if (!type->tp_as_number && !type->tp_as_sequence) {
1760 type->tp_flags |= base->tp_flags &
1761 Py_TPFLAGS_HAVE_INPLACEOPS;
1762 }
1763 }
1764 /* Wow */
1765 }
1766 if (!type->tp_as_number && base->tp_as_number) {
1767 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1768 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1769 }
1770
1771 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001772 oldsize = base->tp_basicsize;
1773 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1774 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1775 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001776 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1777 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001778 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001779 if (type->tp_traverse == NULL)
1780 type->tp_traverse = base->tp_traverse;
1781 if (type->tp_clear == NULL)
1782 type->tp_clear = base->tp_clear;
1783 }
1784 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001785 /* The condition below could use some explanation.
1786 It appears that tp_new is not inherited for static types
1787 whose base class is 'object'; this seems to be a precaution
1788 so that old extension types don't suddenly become
1789 callable (object.__new__ wouldn't insure the invariants
1790 that the extension type's own factory function ensures).
1791 Heap types, of course, are under our control, so they do
1792 inherit tp_new; static extension types that specify some
1793 other built-in type as the default are considered
1794 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001795 if (base != &PyBaseObject_Type ||
1796 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1797 if (type->tp_new == NULL)
1798 type->tp_new = base->tp_new;
1799 }
1800 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001801 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001802
1803 /* Copy other non-function slots */
1804
1805#undef COPYVAL
1806#define COPYVAL(SLOT) \
1807 if (type->SLOT == 0) type->SLOT = base->SLOT
1808
1809 COPYVAL(tp_itemsize);
1810 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1811 COPYVAL(tp_weaklistoffset);
1812 }
1813 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1814 COPYVAL(tp_dictoffset);
1815 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001816}
1817
1818static void
1819inherit_slots(PyTypeObject *type, PyTypeObject *base)
1820{
1821 PyTypeObject *basebase;
1822
1823#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824#undef COPYSLOT
1825#undef COPYNUM
1826#undef COPYSEQ
1827#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001828#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001829
1830#define SLOTDEFINED(SLOT) \
1831 (base->SLOT != 0 && \
1832 (basebase == NULL || base->SLOT != basebase->SLOT))
1833
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001835 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836
1837#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1838#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1839#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001840#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841
Guido van Rossum13d52f02001-08-10 21:24:08 +00001842 /* This won't inherit indirect slots (from tp_as_number etc.)
1843 if type doesn't provide the space. */
1844
1845 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1846 basebase = base->tp_base;
1847 if (basebase->tp_as_number == NULL)
1848 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001849 COPYNUM(nb_add);
1850 COPYNUM(nb_subtract);
1851 COPYNUM(nb_multiply);
1852 COPYNUM(nb_divide);
1853 COPYNUM(nb_remainder);
1854 COPYNUM(nb_divmod);
1855 COPYNUM(nb_power);
1856 COPYNUM(nb_negative);
1857 COPYNUM(nb_positive);
1858 COPYNUM(nb_absolute);
1859 COPYNUM(nb_nonzero);
1860 COPYNUM(nb_invert);
1861 COPYNUM(nb_lshift);
1862 COPYNUM(nb_rshift);
1863 COPYNUM(nb_and);
1864 COPYNUM(nb_xor);
1865 COPYNUM(nb_or);
1866 COPYNUM(nb_coerce);
1867 COPYNUM(nb_int);
1868 COPYNUM(nb_long);
1869 COPYNUM(nb_float);
1870 COPYNUM(nb_oct);
1871 COPYNUM(nb_hex);
1872 COPYNUM(nb_inplace_add);
1873 COPYNUM(nb_inplace_subtract);
1874 COPYNUM(nb_inplace_multiply);
1875 COPYNUM(nb_inplace_divide);
1876 COPYNUM(nb_inplace_remainder);
1877 COPYNUM(nb_inplace_power);
1878 COPYNUM(nb_inplace_lshift);
1879 COPYNUM(nb_inplace_rshift);
1880 COPYNUM(nb_inplace_and);
1881 COPYNUM(nb_inplace_xor);
1882 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001883 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1884 COPYNUM(nb_true_divide);
1885 COPYNUM(nb_floor_divide);
1886 COPYNUM(nb_inplace_true_divide);
1887 COPYNUM(nb_inplace_floor_divide);
1888 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889 }
1890
Guido van Rossum13d52f02001-08-10 21:24:08 +00001891 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1892 basebase = base->tp_base;
1893 if (basebase->tp_as_sequence == NULL)
1894 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001895 COPYSEQ(sq_length);
1896 COPYSEQ(sq_concat);
1897 COPYSEQ(sq_repeat);
1898 COPYSEQ(sq_item);
1899 COPYSEQ(sq_slice);
1900 COPYSEQ(sq_ass_item);
1901 COPYSEQ(sq_ass_slice);
1902 COPYSEQ(sq_contains);
1903 COPYSEQ(sq_inplace_concat);
1904 COPYSEQ(sq_inplace_repeat);
1905 }
1906
Guido van Rossum13d52f02001-08-10 21:24:08 +00001907 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1908 basebase = base->tp_base;
1909 if (basebase->tp_as_mapping == NULL)
1910 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001911 COPYMAP(mp_length);
1912 COPYMAP(mp_subscript);
1913 COPYMAP(mp_ass_subscript);
1914 }
1915
Tim Petersfc57ccb2001-10-12 02:38:24 +00001916 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1917 basebase = base->tp_base;
1918 if (basebase->tp_as_buffer == NULL)
1919 basebase = NULL;
1920 COPYBUF(bf_getreadbuffer);
1921 COPYBUF(bf_getwritebuffer);
1922 COPYBUF(bf_getsegcount);
1923 COPYBUF(bf_getcharbuffer);
1924 }
1925
Guido van Rossum13d52f02001-08-10 21:24:08 +00001926 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 COPYSLOT(tp_dealloc);
1929 COPYSLOT(tp_print);
1930 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1931 type->tp_getattr = base->tp_getattr;
1932 type->tp_getattro = base->tp_getattro;
1933 }
1934 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1935 type->tp_setattr = base->tp_setattr;
1936 type->tp_setattro = base->tp_setattro;
1937 }
1938 /* tp_compare see tp_richcompare */
1939 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001940 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941 COPYSLOT(tp_call);
1942 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001943 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001944 if (type->tp_compare == NULL &&
1945 type->tp_richcompare == NULL &&
1946 type->tp_hash == NULL)
1947 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 type->tp_compare = base->tp_compare;
1949 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001950 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951 }
1952 }
1953 else {
1954 COPYSLOT(tp_compare);
1955 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001956 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1957 COPYSLOT(tp_iter);
1958 COPYSLOT(tp_iternext);
1959 }
1960 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1961 COPYSLOT(tp_descr_get);
1962 COPYSLOT(tp_descr_set);
1963 COPYSLOT(tp_dictoffset);
1964 COPYSLOT(tp_init);
1965 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966 COPYSLOT(tp_free);
1967 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968}
1969
Guido van Rossum13d52f02001-08-10 21:24:08 +00001970staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001971staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001972
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001974PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001975{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001976 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001977 PyTypeObject *base;
1978 int i, n;
1979
Guido van Rossumd614f972001-08-10 17:39:49 +00001980 if (type->tp_flags & Py_TPFLAGS_READY) {
1981 assert(type->tp_dict != NULL);
1982 return 0;
1983 }
1984 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00001985
1986 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987
Guido van Rossumf884b742001-12-17 17:14:22 +00001988 /* Initialize ob_type if NULL. This means extensions that want to be
1989 compilable separately on Windows can call PyType_Ready() instead of
1990 initializing the ob_type field of their type objects. */
1991 if (type->ob_type == NULL)
1992 type->ob_type = &PyType_Type;
1993
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1995 base = type->tp_base;
1996 if (base == NULL && type != &PyBaseObject_Type)
1997 base = type->tp_base = &PyBaseObject_Type;
1998
1999 /* Initialize tp_bases */
2000 bases = type->tp_bases;
2001 if (bases == NULL) {
2002 if (base == NULL)
2003 bases = PyTuple_New(0);
2004 else
2005 bases = Py_BuildValue("(O)", base);
2006 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002007 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008 type->tp_bases = bases;
2009 }
2010
2011 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002012 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002013 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002014 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015 }
2016
Guido van Rossum687ae002001-10-15 22:03:32 +00002017 /* Initialize tp_dict */
2018 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 if (dict == NULL) {
2020 dict = PyDict_New();
2021 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002022 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002023 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002024 }
2025
Guido van Rossum687ae002001-10-15 22:03:32 +00002026 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002028 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 if (type->tp_methods != NULL) {
2030 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002031 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032 }
2033 if (type->tp_members != NULL) {
2034 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002035 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036 }
2037 if (type->tp_getset != NULL) {
2038 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002039 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 }
2041
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042 /* Calculate method resolution order */
2043 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002044 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 }
2046
Guido van Rossum13d52f02001-08-10 21:24:08 +00002047 /* Inherit special flags from dominant base */
2048 if (type->tp_base != NULL)
2049 inherit_special(type, type->tp_base);
2050
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002052 bases = type->tp_mro;
2053 assert(bases != NULL);
2054 assert(PyTuple_Check(bases));
2055 n = PyTuple_GET_SIZE(bases);
2056 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002057 PyObject *b = PyTuple_GET_ITEM(bases, i);
2058 if (PyType_Check(b))
2059 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002060 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002062 /* if the type dictionary doesn't contain a __doc__, set it from
2063 the tp_doc slot.
2064 */
2065 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2066 if (type->tp_doc != NULL) {
2067 PyObject *doc = PyString_FromString(type->tp_doc);
2068 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2069 Py_DECREF(doc);
2070 } else {
2071 PyDict_SetItemString(type->tp_dict, "__doc__", Py_None);
2072 }
2073 }
2074
Guido van Rossum13d52f02001-08-10 21:24:08 +00002075 /* Some more special stuff */
2076 base = type->tp_base;
2077 if (base != NULL) {
2078 if (type->tp_as_number == NULL)
2079 type->tp_as_number = base->tp_as_number;
2080 if (type->tp_as_sequence == NULL)
2081 type->tp_as_sequence = base->tp_as_sequence;
2082 if (type->tp_as_mapping == NULL)
2083 type->tp_as_mapping = base->tp_as_mapping;
2084 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002085
Guido van Rossum1c450732001-10-08 15:18:27 +00002086 /* Link into each base class's list of subclasses */
2087 bases = type->tp_bases;
2088 n = PyTuple_GET_SIZE(bases);
2089 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002090 PyObject *b = PyTuple_GET_ITEM(bases, i);
2091 if (PyType_Check(b) &&
2092 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002093 goto error;
2094 }
2095
Guido van Rossum13d52f02001-08-10 21:24:08 +00002096 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002097 assert(type->tp_dict != NULL);
2098 type->tp_flags =
2099 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002100 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002101
2102 error:
2103 type->tp_flags &= ~Py_TPFLAGS_READYING;
2104 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002105}
2106
Guido van Rossum1c450732001-10-08 15:18:27 +00002107static int
2108add_subclass(PyTypeObject *base, PyTypeObject *type)
2109{
2110 int i;
2111 PyObject *list, *ref, *new;
2112
2113 list = base->tp_subclasses;
2114 if (list == NULL) {
2115 base->tp_subclasses = list = PyList_New(0);
2116 if (list == NULL)
2117 return -1;
2118 }
2119 assert(PyList_Check(list));
2120 new = PyWeakref_NewRef((PyObject *)type, NULL);
2121 i = PyList_GET_SIZE(list);
2122 while (--i >= 0) {
2123 ref = PyList_GET_ITEM(list, i);
2124 assert(PyWeakref_CheckRef(ref));
2125 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2126 return PyList_SetItem(list, i, new);
2127 }
2128 i = PyList_Append(list, new);
2129 Py_DECREF(new);
2130 return i;
2131}
2132
Tim Peters6d6c1a32001-08-02 04:15:00 +00002133
2134/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2135
2136/* There's a wrapper *function* for each distinct function typedef used
2137 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2138 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2139 Most tables have only one entry; the tables for binary operators have two
2140 entries, one regular and one with reversed arguments. */
2141
2142static PyObject *
2143wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2144{
2145 inquiry func = (inquiry)wrapped;
2146 int res;
2147
2148 if (!PyArg_ParseTuple(args, ""))
2149 return NULL;
2150 res = (*func)(self);
2151 if (res == -1 && PyErr_Occurred())
2152 return NULL;
2153 return PyInt_FromLong((long)res);
2154}
2155
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156static PyObject *
2157wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2158{
2159 binaryfunc func = (binaryfunc)wrapped;
2160 PyObject *other;
2161
2162 if (!PyArg_ParseTuple(args, "O", &other))
2163 return NULL;
2164 return (*func)(self, other);
2165}
2166
2167static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002168wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2169{
2170 binaryfunc func = (binaryfunc)wrapped;
2171 PyObject *other;
2172
2173 if (!PyArg_ParseTuple(args, "O", &other))
2174 return NULL;
2175 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002176 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002177 Py_INCREF(Py_NotImplemented);
2178 return Py_NotImplemented;
2179 }
2180 return (*func)(self, other);
2181}
2182
2183static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2185{
2186 binaryfunc func = (binaryfunc)wrapped;
2187 PyObject *other;
2188
2189 if (!PyArg_ParseTuple(args, "O", &other))
2190 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002191 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002192 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002193 Py_INCREF(Py_NotImplemented);
2194 return Py_NotImplemented;
2195 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196 return (*func)(other, self);
2197}
2198
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002199static PyObject *
2200wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2201{
2202 coercion func = (coercion)wrapped;
2203 PyObject *other, *res;
2204 int ok;
2205
2206 if (!PyArg_ParseTuple(args, "O", &other))
2207 return NULL;
2208 ok = func(&self, &other);
2209 if (ok < 0)
2210 return NULL;
2211 if (ok > 0) {
2212 Py_INCREF(Py_NotImplemented);
2213 return Py_NotImplemented;
2214 }
2215 res = PyTuple_New(2);
2216 if (res == NULL) {
2217 Py_DECREF(self);
2218 Py_DECREF(other);
2219 return NULL;
2220 }
2221 PyTuple_SET_ITEM(res, 0, self);
2222 PyTuple_SET_ITEM(res, 1, other);
2223 return res;
2224}
2225
Tim Peters6d6c1a32001-08-02 04:15:00 +00002226static PyObject *
2227wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2228{
2229 ternaryfunc func = (ternaryfunc)wrapped;
2230 PyObject *other;
2231 PyObject *third = Py_None;
2232
2233 /* Note: This wrapper only works for __pow__() */
2234
2235 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2236 return NULL;
2237 return (*func)(self, other, third);
2238}
2239
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002240static PyObject *
2241wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2242{
2243 ternaryfunc func = (ternaryfunc)wrapped;
2244 PyObject *other;
2245 PyObject *third = Py_None;
2246
2247 /* Note: This wrapper only works for __pow__() */
2248
2249 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2250 return NULL;
2251 return (*func)(other, self, third);
2252}
2253
Tim Peters6d6c1a32001-08-02 04:15:00 +00002254static PyObject *
2255wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2256{
2257 unaryfunc func = (unaryfunc)wrapped;
2258
2259 if (!PyArg_ParseTuple(args, ""))
2260 return NULL;
2261 return (*func)(self);
2262}
2263
Tim Peters6d6c1a32001-08-02 04:15:00 +00002264static PyObject *
2265wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2266{
2267 intargfunc func = (intargfunc)wrapped;
2268 int i;
2269
2270 if (!PyArg_ParseTuple(args, "i", &i))
2271 return NULL;
2272 return (*func)(self, i);
2273}
2274
Guido van Rossum5d815f32001-08-17 21:57:47 +00002275static int
2276getindex(PyObject *self, PyObject *arg)
2277{
2278 int i;
2279
2280 i = PyInt_AsLong(arg);
2281 if (i == -1 && PyErr_Occurred())
2282 return -1;
2283 if (i < 0) {
2284 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2285 if (sq && sq->sq_length) {
2286 int n = (*sq->sq_length)(self);
2287 if (n < 0)
2288 return -1;
2289 i += n;
2290 }
2291 }
2292 return i;
2293}
2294
2295static PyObject *
2296wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2297{
2298 intargfunc func = (intargfunc)wrapped;
2299 PyObject *arg;
2300 int i;
2301
Guido van Rossumf4593e02001-10-03 12:09:30 +00002302 if (PyTuple_GET_SIZE(args) == 1) {
2303 arg = PyTuple_GET_ITEM(args, 0);
2304 i = getindex(self, arg);
2305 if (i == -1 && PyErr_Occurred())
2306 return NULL;
2307 return (*func)(self, i);
2308 }
2309 PyArg_ParseTuple(args, "O", &arg);
2310 assert(PyErr_Occurred());
2311 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002312}
2313
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314static PyObject *
2315wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2316{
2317 intintargfunc func = (intintargfunc)wrapped;
2318 int i, j;
2319
2320 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2321 return NULL;
2322 return (*func)(self, i, j);
2323}
2324
Tim Peters6d6c1a32001-08-02 04:15:00 +00002325static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002326wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327{
2328 intobjargproc func = (intobjargproc)wrapped;
2329 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002330 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331
Guido van Rossum5d815f32001-08-17 21:57:47 +00002332 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2333 return NULL;
2334 i = getindex(self, arg);
2335 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336 return NULL;
2337 res = (*func)(self, i, value);
2338 if (res == -1 && PyErr_Occurred())
2339 return NULL;
2340 Py_INCREF(Py_None);
2341 return Py_None;
2342}
2343
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002344static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002345wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002346{
2347 intobjargproc func = (intobjargproc)wrapped;
2348 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002349 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002350
Guido van Rossum5d815f32001-08-17 21:57:47 +00002351 if (!PyArg_ParseTuple(args, "O", &arg))
2352 return NULL;
2353 i = getindex(self, arg);
2354 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002355 return NULL;
2356 res = (*func)(self, i, NULL);
2357 if (res == -1 && PyErr_Occurred())
2358 return NULL;
2359 Py_INCREF(Py_None);
2360 return Py_None;
2361}
2362
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363static PyObject *
2364wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2365{
2366 intintobjargproc func = (intintobjargproc)wrapped;
2367 int i, j, res;
2368 PyObject *value;
2369
2370 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2371 return NULL;
2372 res = (*func)(self, i, j, value);
2373 if (res == -1 && PyErr_Occurred())
2374 return NULL;
2375 Py_INCREF(Py_None);
2376 return Py_None;
2377}
2378
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002379static PyObject *
2380wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2381{
2382 intintobjargproc func = (intintobjargproc)wrapped;
2383 int i, j, res;
2384
2385 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2386 return NULL;
2387 res = (*func)(self, i, j, NULL);
2388 if (res == -1 && PyErr_Occurred())
2389 return NULL;
2390 Py_INCREF(Py_None);
2391 return Py_None;
2392}
2393
Tim Peters6d6c1a32001-08-02 04:15:00 +00002394/* XXX objobjproc is a misnomer; should be objargpred */
2395static PyObject *
2396wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2397{
2398 objobjproc func = (objobjproc)wrapped;
2399 int res;
2400 PyObject *value;
2401
2402 if (!PyArg_ParseTuple(args, "O", &value))
2403 return NULL;
2404 res = (*func)(self, value);
2405 if (res == -1 && PyErr_Occurred())
2406 return NULL;
2407 return PyInt_FromLong((long)res);
2408}
2409
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410static PyObject *
2411wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2412{
2413 objobjargproc func = (objobjargproc)wrapped;
2414 int res;
2415 PyObject *key, *value;
2416
2417 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2418 return NULL;
2419 res = (*func)(self, key, value);
2420 if (res == -1 && PyErr_Occurred())
2421 return NULL;
2422 Py_INCREF(Py_None);
2423 return Py_None;
2424}
2425
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002426static PyObject *
2427wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2428{
2429 objobjargproc func = (objobjargproc)wrapped;
2430 int res;
2431 PyObject *key;
2432
2433 if (!PyArg_ParseTuple(args, "O", &key))
2434 return NULL;
2435 res = (*func)(self, key, NULL);
2436 if (res == -1 && PyErr_Occurred())
2437 return NULL;
2438 Py_INCREF(Py_None);
2439 return Py_None;
2440}
2441
Tim Peters6d6c1a32001-08-02 04:15:00 +00002442static PyObject *
2443wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2444{
2445 cmpfunc func = (cmpfunc)wrapped;
2446 int res;
2447 PyObject *other;
2448
2449 if (!PyArg_ParseTuple(args, "O", &other))
2450 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002451 if (other->ob_type->tp_compare != func &&
2452 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002453 PyErr_Format(
2454 PyExc_TypeError,
2455 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2456 self->ob_type->tp_name,
2457 self->ob_type->tp_name,
2458 other->ob_type->tp_name);
2459 return NULL;
2460 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461 res = (*func)(self, other);
2462 if (PyErr_Occurred())
2463 return NULL;
2464 return PyInt_FromLong((long)res);
2465}
2466
Tim Peters6d6c1a32001-08-02 04:15:00 +00002467static PyObject *
2468wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2469{
2470 setattrofunc func = (setattrofunc)wrapped;
2471 int res;
2472 PyObject *name, *value;
2473
2474 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2475 return NULL;
2476 res = (*func)(self, name, value);
2477 if (res < 0)
2478 return NULL;
2479 Py_INCREF(Py_None);
2480 return Py_None;
2481}
2482
2483static PyObject *
2484wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2485{
2486 setattrofunc func = (setattrofunc)wrapped;
2487 int res;
2488 PyObject *name;
2489
2490 if (!PyArg_ParseTuple(args, "O", &name))
2491 return NULL;
2492 res = (*func)(self, name, NULL);
2493 if (res < 0)
2494 return NULL;
2495 Py_INCREF(Py_None);
2496 return Py_None;
2497}
2498
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499static PyObject *
2500wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2501{
2502 hashfunc func = (hashfunc)wrapped;
2503 long res;
2504
2505 if (!PyArg_ParseTuple(args, ""))
2506 return NULL;
2507 res = (*func)(self);
2508 if (res == -1 && PyErr_Occurred())
2509 return NULL;
2510 return PyInt_FromLong(res);
2511}
2512
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002514wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515{
2516 ternaryfunc func = (ternaryfunc)wrapped;
2517
Guido van Rossumc8e56452001-10-22 00:43:43 +00002518 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519}
2520
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521static PyObject *
2522wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2523{
2524 richcmpfunc func = (richcmpfunc)wrapped;
2525 PyObject *other;
2526
2527 if (!PyArg_ParseTuple(args, "O", &other))
2528 return NULL;
2529 return (*func)(self, other, op);
2530}
2531
2532#undef RICHCMP_WRAPPER
2533#define RICHCMP_WRAPPER(NAME, OP) \
2534static PyObject * \
2535richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2536{ \
2537 return wrap_richcmpfunc(self, args, wrapped, OP); \
2538}
2539
Jack Jansen8e938b42001-08-08 15:29:49 +00002540RICHCMP_WRAPPER(lt, Py_LT)
2541RICHCMP_WRAPPER(le, Py_LE)
2542RICHCMP_WRAPPER(eq, Py_EQ)
2543RICHCMP_WRAPPER(ne, Py_NE)
2544RICHCMP_WRAPPER(gt, Py_GT)
2545RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002546
Tim Peters6d6c1a32001-08-02 04:15:00 +00002547static PyObject *
2548wrap_next(PyObject *self, PyObject *args, void *wrapped)
2549{
2550 unaryfunc func = (unaryfunc)wrapped;
2551 PyObject *res;
2552
2553 if (!PyArg_ParseTuple(args, ""))
2554 return NULL;
2555 res = (*func)(self);
2556 if (res == NULL && !PyErr_Occurred())
2557 PyErr_SetNone(PyExc_StopIteration);
2558 return res;
2559}
2560
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561static PyObject *
2562wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2563{
2564 descrgetfunc func = (descrgetfunc)wrapped;
2565 PyObject *obj;
2566 PyObject *type = NULL;
2567
2568 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2569 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570 return (*func)(self, obj, type);
2571}
2572
Tim Peters6d6c1a32001-08-02 04:15:00 +00002573static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002574wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575{
2576 descrsetfunc func = (descrsetfunc)wrapped;
2577 PyObject *obj, *value;
2578 int ret;
2579
2580 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2581 return NULL;
2582 ret = (*func)(self, obj, value);
2583 if (ret < 0)
2584 return NULL;
2585 Py_INCREF(Py_None);
2586 return Py_None;
2587}
2588
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002590wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591{
2592 initproc func = (initproc)wrapped;
2593
Guido van Rossumc8e56452001-10-22 00:43:43 +00002594 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595 return NULL;
2596 Py_INCREF(Py_None);
2597 return Py_None;
2598}
2599
Tim Peters6d6c1a32001-08-02 04:15:00 +00002600static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002601tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602{
Barry Warsaw60f01882001-08-22 19:24:42 +00002603 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002604 PyObject *arg0, *res;
2605
2606 if (self == NULL || !PyType_Check(self))
2607 Py_FatalError("__new__() called with non-type 'self'");
2608 type = (PyTypeObject *)self;
2609 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002610 PyErr_Format(PyExc_TypeError,
2611 "%s.__new__(): not enough arguments",
2612 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002613 return NULL;
2614 }
2615 arg0 = PyTuple_GET_ITEM(args, 0);
2616 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002617 PyErr_Format(PyExc_TypeError,
2618 "%s.__new__(X): X is not a type object (%s)",
2619 type->tp_name,
2620 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002621 return NULL;
2622 }
2623 subtype = (PyTypeObject *)arg0;
2624 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002625 PyErr_Format(PyExc_TypeError,
2626 "%s.__new__(%s): %s is not a subtype of %s",
2627 type->tp_name,
2628 subtype->tp_name,
2629 subtype->tp_name,
2630 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002631 return NULL;
2632 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002633
2634 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002635 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002636 most derived base that's not a heap type is this type. */
2637 staticbase = subtype;
2638 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2639 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002640 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002641 PyErr_Format(PyExc_TypeError,
2642 "%s.__new__(%s) is not safe, use %s.__new__()",
2643 type->tp_name,
2644 subtype->tp_name,
2645 staticbase == NULL ? "?" : staticbase->tp_name);
2646 return NULL;
2647 }
2648
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002649 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2650 if (args == NULL)
2651 return NULL;
2652 res = type->tp_new(subtype, args, kwds);
2653 Py_DECREF(args);
2654 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002655}
2656
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002657static struct PyMethodDef tp_new_methoddef[] = {
2658 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2659 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002660 {0}
2661};
2662
2663static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002664add_tp_new_wrapper(PyTypeObject *type)
2665{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002666 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002667
Guido van Rossum687ae002001-10-15 22:03:32 +00002668 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002669 return 0;
2670 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002671 if (func == NULL)
2672 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002673 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002674}
2675
Guido van Rossumf040ede2001-08-07 16:40:56 +00002676/* Slot wrappers that call the corresponding __foo__ slot. See comments
2677 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002678
Guido van Rossumdc91b992001-08-08 22:26:22 +00002679#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002680static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002681FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002683 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002684 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685}
2686
Guido van Rossumdc91b992001-08-08 22:26:22 +00002687#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002689FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002690{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002691 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002692 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002693}
2694
Guido van Rossumdc91b992001-08-08 22:26:22 +00002695
2696#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002697static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002698FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002699{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002700 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002701 int do_other = self->ob_type != other->ob_type && \
2702 other->ob_type->tp_as_number != NULL && \
2703 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002704 if (self->ob_type->tp_as_number != NULL && \
2705 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2706 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002707 if (do_other && \
2708 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2709 r = call_maybe( \
2710 other, ROPSTR, &rcache_str, "(O)", self); \
2711 if (r != Py_NotImplemented) \
2712 return r; \
2713 Py_DECREF(r); \
2714 do_other = 0; \
2715 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002716 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002717 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002718 if (r != Py_NotImplemented || \
2719 other->ob_type == self->ob_type) \
2720 return r; \
2721 Py_DECREF(r); \
2722 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002723 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002724 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002725 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002726 } \
2727 Py_INCREF(Py_NotImplemented); \
2728 return Py_NotImplemented; \
2729}
2730
2731#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2732 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2733
2734#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2735static PyObject * \
2736FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2737{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002738 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002739 return call_method(self, OPSTR, &cache_str, \
2740 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741}
2742
2743static int
2744slot_sq_length(PyObject *self)
2745{
Guido van Rossum2730b132001-08-28 18:22:14 +00002746 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002747 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002748 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002749
2750 if (res == NULL)
2751 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002752 len = (int)PyInt_AsLong(res);
2753 Py_DECREF(res);
2754 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755}
2756
Guido van Rossumdc91b992001-08-08 22:26:22 +00002757SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2758SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002759
2760/* Super-optimized version of slot_sq_item.
2761 Other slots could do the same... */
2762static PyObject *
2763slot_sq_item(PyObject *self, int i)
2764{
2765 static PyObject *getitem_str;
2766 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2767 descrgetfunc f;
2768
2769 if (getitem_str == NULL) {
2770 getitem_str = PyString_InternFromString("__getitem__");
2771 if (getitem_str == NULL)
2772 return NULL;
2773 }
2774 func = _PyType_Lookup(self->ob_type, getitem_str);
2775 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002776 if ((f = func->ob_type->tp_descr_get) == NULL)
2777 Py_INCREF(func);
2778 else
2779 func = f(func, self, (PyObject *)(self->ob_type));
2780 ival = PyInt_FromLong(i);
2781 if (ival != NULL) {
2782 args = PyTuple_New(1);
2783 if (args != NULL) {
2784 PyTuple_SET_ITEM(args, 0, ival);
2785 retval = PyObject_Call(func, args, NULL);
2786 Py_XDECREF(args);
2787 Py_XDECREF(func);
2788 return retval;
2789 }
2790 }
2791 }
2792 else {
2793 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2794 }
2795 Py_XDECREF(args);
2796 Py_XDECREF(ival);
2797 Py_XDECREF(func);
2798 return NULL;
2799}
2800
Guido van Rossumdc91b992001-08-08 22:26:22 +00002801SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002802
2803static int
2804slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2805{
2806 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002807 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002808
2809 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002810 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002811 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002813 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002814 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002815 if (res == NULL)
2816 return -1;
2817 Py_DECREF(res);
2818 return 0;
2819}
2820
2821static int
2822slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2823{
2824 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002825 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002826
2827 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002828 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002829 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002831 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002832 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002833 if (res == NULL)
2834 return -1;
2835 Py_DECREF(res);
2836 return 0;
2837}
2838
2839static int
2840slot_sq_contains(PyObject *self, PyObject *value)
2841{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002842 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002843 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002844
Guido van Rossum55f20992001-10-01 17:18:22 +00002845 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002846
2847 if (func != NULL) {
2848 args = Py_BuildValue("(O)", value);
2849 if (args == NULL)
2850 res = NULL;
2851 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002852 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002853 Py_DECREF(args);
2854 }
2855 Py_DECREF(func);
2856 if (res == NULL)
2857 return -1;
2858 return PyObject_IsTrue(res);
2859 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002860 else if (PyErr_Occurred())
2861 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002862 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002863 return _PySequence_IterSearch(self, value,
2864 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002865 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002866}
2867
Guido van Rossumdc91b992001-08-08 22:26:22 +00002868SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2869SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002870
2871#define slot_mp_length slot_sq_length
2872
Guido van Rossumdc91b992001-08-08 22:26:22 +00002873SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002874
2875static int
2876slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2877{
2878 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002879 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002880
2881 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002882 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002883 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002885 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002886 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887 if (res == NULL)
2888 return -1;
2889 Py_DECREF(res);
2890 return 0;
2891}
2892
Guido van Rossumdc91b992001-08-08 22:26:22 +00002893SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2894SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2895SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2896SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2897SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2898SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2899
2900staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2901
2902SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2903 nb_power, "__pow__", "__rpow__")
2904
2905static PyObject *
2906slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2907{
Guido van Rossum2730b132001-08-28 18:22:14 +00002908 static PyObject *pow_str;
2909
Guido van Rossumdc91b992001-08-08 22:26:22 +00002910 if (modulus == Py_None)
2911 return slot_nb_power_binary(self, other);
2912 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002913 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002914 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002915}
2916
2917SLOT0(slot_nb_negative, "__neg__")
2918SLOT0(slot_nb_positive, "__pos__")
2919SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920
2921static int
2922slot_nb_nonzero(PyObject *self)
2923{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002924 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002925 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002926
Guido van Rossum55f20992001-10-01 17:18:22 +00002927 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002928 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002929 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002930 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002931 func = lookup_maybe(self, "__len__", &len_str);
2932 if (func == NULL) {
2933 if (PyErr_Occurred())
2934 return -1;
2935 else
2936 return 1;
2937 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002938 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002939 res = PyObject_CallObject(func, NULL);
2940 Py_DECREF(func);
2941 if (res == NULL)
2942 return -1;
2943 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002944}
2945
Guido van Rossumdc91b992001-08-08 22:26:22 +00002946SLOT0(slot_nb_invert, "__invert__")
2947SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2948SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2949SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2950SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2951SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002952
2953static int
2954slot_nb_coerce(PyObject **a, PyObject **b)
2955{
2956 static PyObject *coerce_str;
2957 PyObject *self = *a, *other = *b;
2958
2959 if (self->ob_type->tp_as_number != NULL &&
2960 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2961 PyObject *r;
2962 r = call_maybe(
2963 self, "__coerce__", &coerce_str, "(O)", other);
2964 if (r == NULL)
2965 return -1;
2966 if (r == Py_NotImplemented) {
2967 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002968 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002969 else {
2970 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2971 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002972 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00002973 Py_DECREF(r);
2974 return -1;
2975 }
2976 *a = PyTuple_GET_ITEM(r, 0);
2977 Py_INCREF(*a);
2978 *b = PyTuple_GET_ITEM(r, 1);
2979 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002980 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00002981 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002982 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002983 }
2984 if (other->ob_type->tp_as_number != NULL &&
2985 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2986 PyObject *r;
2987 r = call_maybe(
2988 other, "__coerce__", &coerce_str, "(O)", self);
2989 if (r == NULL)
2990 return -1;
2991 if (r == Py_NotImplemented) {
2992 Py_DECREF(r);
2993 return 1;
2994 }
2995 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2996 PyErr_SetString(PyExc_TypeError,
2997 "__coerce__ didn't return a 2-tuple");
2998 Py_DECREF(r);
2999 return -1;
3000 }
3001 *a = PyTuple_GET_ITEM(r, 1);
3002 Py_INCREF(*a);
3003 *b = PyTuple_GET_ITEM(r, 0);
3004 Py_INCREF(*b);
3005 Py_DECREF(r);
3006 return 0;
3007 }
3008 return 1;
3009}
3010
Guido van Rossumdc91b992001-08-08 22:26:22 +00003011SLOT0(slot_nb_int, "__int__")
3012SLOT0(slot_nb_long, "__long__")
3013SLOT0(slot_nb_float, "__float__")
3014SLOT0(slot_nb_oct, "__oct__")
3015SLOT0(slot_nb_hex, "__hex__")
3016SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3017SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3018SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3019SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3020SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3021SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3022SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3023SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3024SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3025SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3026SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3027SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3028 "__floordiv__", "__rfloordiv__")
3029SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3030SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3031SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032
3033static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003034half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003036 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003037 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003038 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039
Guido van Rossum60718732001-08-28 17:47:51 +00003040 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003041 if (func == NULL) {
3042 PyErr_Clear();
3043 }
3044 else {
3045 args = Py_BuildValue("(O)", other);
3046 if (args == NULL)
3047 res = NULL;
3048 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003049 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003050 Py_DECREF(args);
3051 }
3052 if (res != Py_NotImplemented) {
3053 if (res == NULL)
3054 return -2;
3055 c = PyInt_AsLong(res);
3056 Py_DECREF(res);
3057 if (c == -1 && PyErr_Occurred())
3058 return -2;
3059 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3060 }
3061 Py_DECREF(res);
3062 }
3063 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064}
3065
Guido van Rossumab3b0342001-09-18 20:38:53 +00003066/* This slot is published for the benefit of try_3way_compare in object.c */
3067int
3068_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003069{
3070 int c;
3071
Guido van Rossumab3b0342001-09-18 20:38:53 +00003072 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003073 c = half_compare(self, other);
3074 if (c <= 1)
3075 return c;
3076 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003077 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003078 c = half_compare(other, self);
3079 if (c < -1)
3080 return -2;
3081 if (c <= 1)
3082 return -c;
3083 }
3084 return (void *)self < (void *)other ? -1 :
3085 (void *)self > (void *)other ? 1 : 0;
3086}
3087
3088static PyObject *
3089slot_tp_repr(PyObject *self)
3090{
3091 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003092 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003093
Guido van Rossum60718732001-08-28 17:47:51 +00003094 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003095 if (func != NULL) {
3096 res = PyEval_CallObject(func, NULL);
3097 Py_DECREF(func);
3098 return res;
3099 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003100 PyErr_Clear();
3101 return PyString_FromFormat("<%s object at %p>",
3102 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003103}
3104
3105static PyObject *
3106slot_tp_str(PyObject *self)
3107{
3108 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003109 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003110
Guido van Rossum60718732001-08-28 17:47:51 +00003111 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003112 if (func != NULL) {
3113 res = PyEval_CallObject(func, NULL);
3114 Py_DECREF(func);
3115 return res;
3116 }
3117 else {
3118 PyErr_Clear();
3119 return slot_tp_repr(self);
3120 }
3121}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122
3123static long
3124slot_tp_hash(PyObject *self)
3125{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003126 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003127 static PyObject *hash_str, *eq_str, *cmp_str;
3128
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129 long h;
3130
Guido van Rossum60718732001-08-28 17:47:51 +00003131 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003132
3133 if (func != NULL) {
3134 res = PyEval_CallObject(func, NULL);
3135 Py_DECREF(func);
3136 if (res == NULL)
3137 return -1;
3138 h = PyInt_AsLong(res);
3139 }
3140 else {
3141 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003142 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003143 if (func == NULL) {
3144 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003145 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003146 }
3147 if (func != NULL) {
3148 Py_DECREF(func);
3149 PyErr_SetString(PyExc_TypeError, "unhashable type");
3150 return -1;
3151 }
3152 PyErr_Clear();
3153 h = _Py_HashPointer((void *)self);
3154 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155 if (h == -1 && !PyErr_Occurred())
3156 h = -2;
3157 return h;
3158}
3159
3160static PyObject *
3161slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3162{
Guido van Rossum60718732001-08-28 17:47:51 +00003163 static PyObject *call_str;
3164 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165 PyObject *res;
3166
3167 if (meth == NULL)
3168 return NULL;
3169 res = PyObject_Call(meth, args, kwds);
3170 Py_DECREF(meth);
3171 return res;
3172}
3173
Guido van Rossum14a6f832001-10-17 13:59:09 +00003174/* There are two slot dispatch functions for tp_getattro.
3175
3176 - slot_tp_getattro() is used when __getattribute__ is overridden
3177 but no __getattr__ hook is present;
3178
3179 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3180
3181 The code in update_slot() and fixup_slot_dispatchers() always installs
3182 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3183 installs the simpler slot if necessary. */
3184
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185static PyObject *
3186slot_tp_getattro(PyObject *self, PyObject *name)
3187{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003188 static PyObject *getattribute_str = NULL;
3189 return call_method(self, "__getattribute__", &getattribute_str,
3190 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191}
3192
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003193static PyObject *
3194slot_tp_getattr_hook(PyObject *self, PyObject *name)
3195{
3196 PyTypeObject *tp = self->ob_type;
3197 PyObject *getattr, *getattribute, *res;
3198 static PyObject *getattribute_str = NULL;
3199 static PyObject *getattr_str = NULL;
3200
3201 if (getattr_str == NULL) {
3202 getattr_str = PyString_InternFromString("__getattr__");
3203 if (getattr_str == NULL)
3204 return NULL;
3205 }
3206 if (getattribute_str == NULL) {
3207 getattribute_str =
3208 PyString_InternFromString("__getattribute__");
3209 if (getattribute_str == NULL)
3210 return NULL;
3211 }
3212 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003213 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003214 /* No __getattr__ hook: use a simpler dispatcher */
3215 tp->tp_getattro = slot_tp_getattro;
3216 return slot_tp_getattro(self, name);
3217 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003218 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003219 if (getattribute == NULL ||
3220 (getattribute->ob_type == &PyWrapperDescr_Type &&
3221 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3222 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003223 res = PyObject_GenericGetAttr(self, name);
3224 else
3225 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003226 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003227 PyErr_Clear();
3228 res = PyObject_CallFunction(getattr, "OO", self, name);
3229 }
3230 return res;
3231}
3232
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233static int
3234slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3235{
3236 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003237 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238
3239 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003240 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003241 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003242 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003243 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003244 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245 if (res == NULL)
3246 return -1;
3247 Py_DECREF(res);
3248 return 0;
3249}
3250
3251/* Map rich comparison operators to their __xx__ namesakes */
3252static char *name_op[] = {
3253 "__lt__",
3254 "__le__",
3255 "__eq__",
3256 "__ne__",
3257 "__gt__",
3258 "__ge__",
3259};
3260
3261static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003262half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003263{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003264 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003265 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003266
Guido van Rossum60718732001-08-28 17:47:51 +00003267 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003268 if (func == NULL) {
3269 PyErr_Clear();
3270 Py_INCREF(Py_NotImplemented);
3271 return Py_NotImplemented;
3272 }
3273 args = Py_BuildValue("(O)", other);
3274 if (args == NULL)
3275 res = NULL;
3276 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003277 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278 Py_DECREF(args);
3279 }
3280 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281 return res;
3282}
3283
Guido van Rossumb8f63662001-08-15 23:57:02 +00003284/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3285static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3286
3287static PyObject *
3288slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3289{
3290 PyObject *res;
3291
3292 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3293 res = half_richcompare(self, other, op);
3294 if (res != Py_NotImplemented)
3295 return res;
3296 Py_DECREF(res);
3297 }
3298 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3299 res = half_richcompare(other, self, swapped_op[op]);
3300 if (res != Py_NotImplemented) {
3301 return res;
3302 }
3303 Py_DECREF(res);
3304 }
3305 Py_INCREF(Py_NotImplemented);
3306 return Py_NotImplemented;
3307}
3308
3309static PyObject *
3310slot_tp_iter(PyObject *self)
3311{
3312 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003313 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003314
Guido van Rossum60718732001-08-28 17:47:51 +00003315 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003316 if (func != NULL) {
3317 res = PyObject_CallObject(func, NULL);
3318 Py_DECREF(func);
3319 return res;
3320 }
3321 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003322 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003323 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003324 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003325 return NULL;
3326 }
3327 Py_DECREF(func);
3328 return PySeqIter_New(self);
3329}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003330
3331static PyObject *
3332slot_tp_iternext(PyObject *self)
3333{
Guido van Rossum2730b132001-08-28 18:22:14 +00003334 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003335 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003336}
3337
Guido van Rossum1a493502001-08-17 16:47:50 +00003338static PyObject *
3339slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3340{
3341 PyTypeObject *tp = self->ob_type;
3342 PyObject *get;
3343 static PyObject *get_str = NULL;
3344
3345 if (get_str == NULL) {
3346 get_str = PyString_InternFromString("__get__");
3347 if (get_str == NULL)
3348 return NULL;
3349 }
3350 get = _PyType_Lookup(tp, get_str);
3351 if (get == NULL) {
3352 /* Avoid further slowdowns */
3353 if (tp->tp_descr_get == slot_tp_descr_get)
3354 tp->tp_descr_get = NULL;
3355 Py_INCREF(self);
3356 return self;
3357 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003358 if (obj == NULL)
3359 obj = Py_None;
3360 if (type == NULL)
3361 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003362 return PyObject_CallFunction(get, "OOO", self, obj, type);
3363}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003364
3365static int
3366slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3367{
Guido van Rossum2c252392001-08-24 10:13:31 +00003368 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003369 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003370
3371 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003372 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003373 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003374 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003375 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003376 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377 if (res == NULL)
3378 return -1;
3379 Py_DECREF(res);
3380 return 0;
3381}
3382
3383static int
3384slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3385{
Guido van Rossum60718732001-08-28 17:47:51 +00003386 static PyObject *init_str;
3387 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003388 PyObject *res;
3389
3390 if (meth == NULL)
3391 return -1;
3392 res = PyObject_Call(meth, args, kwds);
3393 Py_DECREF(meth);
3394 if (res == NULL)
3395 return -1;
3396 Py_DECREF(res);
3397 return 0;
3398}
3399
3400static PyObject *
3401slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3402{
3403 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3404 PyObject *newargs, *x;
3405 int i, n;
3406
3407 if (func == NULL)
3408 return NULL;
3409 assert(PyTuple_Check(args));
3410 n = PyTuple_GET_SIZE(args);
3411 newargs = PyTuple_New(n+1);
3412 if (newargs == NULL)
3413 return NULL;
3414 Py_INCREF(type);
3415 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3416 for (i = 0; i < n; i++) {
3417 x = PyTuple_GET_ITEM(args, i);
3418 Py_INCREF(x);
3419 PyTuple_SET_ITEM(newargs, i+1, x);
3420 }
3421 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003422 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 Py_DECREF(func);
3424 return x;
3425}
3426
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003427
3428/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3429 functions. The offsets here are relative to the 'etype' structure, which
3430 incorporates the additional structures used for numbers, sequences and
3431 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3432 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3433 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3434
Guido van Rossum6d204072001-10-21 00:44:31 +00003435typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003436
3437#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003438#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003439#undef ETSLOT
3440#undef SQSLOT
3441#undef MPSLOT
3442#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003443#undef UNSLOT
3444#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003445#undef BINSLOT
3446#undef RBINSLOT
3447
Guido van Rossum6d204072001-10-21 00:44:31 +00003448#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3449 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003450#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3451 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3452 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003453#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3454 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3455#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3456 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3457#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3458 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3459#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3460 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3461#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3462 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3463 "x." NAME "() <==> " DOC)
3464#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3465 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3466 "x." NAME "(y) <==> x" DOC "y")
3467#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3468 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3469 "x." NAME "(y) <==> x" DOC "y")
3470#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3471 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3472 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003473
3474static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003475 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3476 "x.__len__() <==> len(x)"),
3477 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3478 "x.__add__(y) <==> x+y"),
3479 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3480 "x.__mul__(n) <==> x*n"),
3481 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3482 "x.__rmul__(n) <==> n*x"),
3483 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3484 "x.__getitem__(y) <==> x[y]"),
3485 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3486 "x.__getslice__(i, j) <==> x[i:j]"),
3487 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3488 "x.__setitem__(i, y) <==> x[i]=y"),
3489 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3490 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003491 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003492 wrap_intintobjargproc,
3493 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3494 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3495 "x.__delslice__(i, j) <==> del x[i:j]"),
3496 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3497 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003498 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003499 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003500 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003501 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003502
Guido van Rossum6d204072001-10-21 00:44:31 +00003503 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3504 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003505 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003506 wrap_binaryfunc,
3507 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003508 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003509 wrap_objobjargproc,
3510 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003511 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003512 wrap_delitem,
3513 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003514
Guido van Rossum6d204072001-10-21 00:44:31 +00003515 BINSLOT("__add__", nb_add, slot_nb_add,
3516 "+"),
3517 RBINSLOT("__radd__", nb_add, slot_nb_add,
3518 "+"),
3519 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3520 "-"),
3521 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3522 "-"),
3523 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3524 "*"),
3525 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3526 "*"),
3527 BINSLOT("__div__", nb_divide, slot_nb_divide,
3528 "/"),
3529 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3530 "/"),
3531 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3532 "%"),
3533 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3534 "%"),
3535 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3536 "divmod(x, y)"),
3537 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3538 "divmod(y, x)"),
3539 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3540 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3541 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3542 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3543 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3544 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3545 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3546 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003547 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003548 "x != 0"),
3549 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3550 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3551 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3552 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3553 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3554 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3555 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3556 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3557 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3558 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3559 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3560 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3561 "x.__coerce__(y) <==> coerce(x, y)"),
3562 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3563 "int(x)"),
3564 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3565 "long(x)"),
3566 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3567 "float(x)"),
3568 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3569 "oct(x)"),
3570 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3571 "hex(x)"),
3572 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3573 wrap_binaryfunc, "+"),
3574 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3575 wrap_binaryfunc, "-"),
3576 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3577 wrap_binaryfunc, "*"),
3578 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3579 wrap_binaryfunc, "/"),
3580 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3581 wrap_binaryfunc, "%"),
3582 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3583 wrap_ternaryfunc, "**"),
3584 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3585 wrap_binaryfunc, "<<"),
3586 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3587 wrap_binaryfunc, ">>"),
3588 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3589 wrap_binaryfunc, "&"),
3590 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3591 wrap_binaryfunc, "^"),
3592 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3593 wrap_binaryfunc, "|"),
3594 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3595 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3596 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3597 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3598 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3599 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3600 IBSLOT("__itruediv__", nb_inplace_true_divide,
3601 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003602
Guido van Rossum6d204072001-10-21 00:44:31 +00003603 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3604 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003605 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003606 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3607 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003608 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003609 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3610 "x.__cmp__(y) <==> cmp(x,y)"),
3611 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3612 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003613 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3614 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003615 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003616 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3617 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3618 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3619 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3620 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3621 "x.__setattr__('name', value) <==> x.name = value"),
3622 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3623 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3624 "x.__delattr__('name') <==> del x.name"),
3625 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3626 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3627 "x.__lt__(y) <==> x<y"),
3628 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3629 "x.__le__(y) <==> x<=y"),
3630 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3631 "x.__eq__(y) <==> x==y"),
3632 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3633 "x.__ne__(y) <==> x!=y"),
3634 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3635 "x.__gt__(y) <==> x>y"),
3636 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3637 "x.__ge__(y) <==> x>=y"),
3638 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3639 "x.__iter__() <==> iter(x)"),
3640 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3641 "x.next() -> the next value, or raise StopIteration"),
3642 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3643 "descr.__get__(obj[, type]) -> value"),
3644 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3645 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003646 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003647 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003648 "see x.__class__.__doc__ for signature",
3649 PyWrapperFlag_KEYWORDS),
3650 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003651 {NULL}
3652};
3653
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003654static void **
3655slotptr(PyTypeObject *type, int offset)
3656{
3657 char *ptr;
3658
3659 assert(offset >= 0);
3660 assert(offset < offsetof(etype, as_buffer));
3661 if (offset >= offsetof(etype, as_mapping)) {
3662 ptr = (void *)type->tp_as_mapping;
3663 offset -= offsetof(etype, as_mapping);
3664 }
3665 else if (offset >= offsetof(etype, as_sequence)) {
3666 ptr = (void *)type->tp_as_sequence;
3667 offset -= offsetof(etype, as_sequence);
3668 }
3669 else if (offset >= offsetof(etype, as_number)) {
3670 ptr = (void *)type->tp_as_number;
3671 offset -= offsetof(etype, as_number);
3672 }
3673 else {
3674 ptr = (void *)type;
3675 }
3676 if (ptr != NULL)
3677 ptr += offset;
3678 return (void **)ptr;
3679}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003680
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003681staticforward int recurse_down_subclasses(PyTypeObject *type,
3682 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003683
3684static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003685update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003686{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003687 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003688
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003689 for (pp = pp0; *pp; pp++) {
3690 slotdef *p = *pp;
3691 PyObject *descr;
3692 PyWrapperDescrObject *d;
3693 void *generic = NULL, *specific = NULL;
3694 int use_generic = 0;
3695 int offset = p->offset;
3696 void **ptr = slotptr(type, offset);
3697 if (ptr == NULL)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003698 continue;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003699 do {
3700 descr = _PyType_Lookup(type, p->name_strobj);
3701 if (descr == NULL)
3702 continue;
3703 generic = p->function;
3704 if (descr->ob_type == &PyWrapperDescr_Type) {
3705 d = (PyWrapperDescrObject *)descr;
3706 if (d->d_base->wrapper == p->wrapper &&
3707 PyType_IsSubtype(type, d->d_type)) {
3708 if (specific == NULL ||
3709 specific == d->d_wrapped)
3710 specific = d->d_wrapped;
3711 else
3712 use_generic = 1;
3713 }
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003714 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003715 else
3716 use_generic = 1;
3717 } while ((++p)->offset == offset);
3718 if (specific && !use_generic)
3719 *ptr = specific;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003720 else
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003721 *ptr = generic;
3722 }
3723 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003724}
3725
3726static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003727recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003728{
3729 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003730 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003731 int i, n;
3732
3733 subclasses = type->tp_subclasses;
3734 if (subclasses == NULL)
3735 return 0;
3736 assert(PyList_Check(subclasses));
3737 n = PyList_GET_SIZE(subclasses);
3738 for (i = 0; i < n; i++) {
3739 ref = PyList_GET_ITEM(subclasses, i);
3740 assert(PyWeakref_CheckRef(ref));
3741 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3742 if (subclass == NULL)
3743 continue;
3744 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003745 /* Avoid recursing down into unaffected classes */
3746 dict = subclass->tp_dict;
3747 if (dict != NULL && PyDict_Check(dict) &&
3748 PyDict_GetItem(dict, name) != NULL)
3749 continue;
3750 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003751 return -1;
3752 }
3753 return 0;
3754}
3755
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003756static int
3757slotdef_cmp(const void *aa, const void *bb)
3758{
3759 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3760 int c = a->offset - b->offset;
3761 if (c != 0)
3762 return c;
3763 else
3764 return a - b;
3765}
3766
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003767static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003768init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003769{
3770 slotdef *p;
3771 static int initialized = 0;
3772
3773 if (initialized)
3774 return;
3775 for (p = slotdefs; p->name; p++) {
3776 p->name_strobj = PyString_InternFromString(p->name);
3777 if (!p->name_strobj)
3778 Py_FatalError("XXX ouch");
3779 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003780 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3781 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003782 initialized = 1;
3783}
3784
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003785static int
3786update_slot(PyTypeObject *type, PyObject *name)
3787{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003788 slotdef *ptrs[10];
3789 slotdef *p;
3790 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003791 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003792
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003793 init_slotdefs();
3794 pp = ptrs;
3795 for (p = slotdefs; p->name; p++) {
3796 /* XXX assume name is interned! */
3797 if (p->name_strobj == name)
3798 *pp++ = p;
3799 }
3800 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003801 for (pp = ptrs; *pp; pp++) {
3802 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003803 offset = p->offset;
3804 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003805 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003806 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003807 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003808 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003809}
3810
Tim Peters6d6c1a32001-08-02 04:15:00 +00003811static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003812fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003813{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003814 slotdef *p;
3815 PyObject *mro, *descr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003816 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003817 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003818 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003819 void *generic, *specific;
3820 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003822 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003823 mro = type->tp_mro;
3824 assert(PyTuple_Check(mro));
3825 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003826 for (p = slotdefs; p->name; ) {
3827 offset = p->offset;
3828 ptr = slotptr(type, offset);
3829 if (!ptr) {
3830 do {
3831 ++p;
3832 } while (p->offset == offset);
3833 continue;
3834 }
3835 generic = specific = NULL;
3836 use_generic = 0;
3837 do {
3838 descr = NULL;
3839 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003840 PyObject *b = PyTuple_GET_ITEM(mro, i);
3841 PyObject *dict = NULL;
3842 if (PyType_Check(b))
3843 dict = ((PyTypeObject *)b)->tp_dict;
3844 else if (PyClass_Check(b))
3845 dict = ((PyClassObject *)b)->cl_dict;
3846 if (dict != NULL) {
3847 descr = PyDict_GetItem(
3848 dict, p->name_strobj);
3849 if (descr != NULL)
3850 break;
3851 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003852 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003853 if (descr == NULL)
3854 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003855 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003856 if (descr->ob_type == &PyWrapperDescr_Type) {
3857 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003858 if (d->d_base->wrapper == p->wrapper &&
Guido van Rossumcaf59042001-10-17 07:15:43 +00003859 PyType_IsSubtype(type, d->d_type))
3860 {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003861 if (specific == NULL ||
Guido van Rossumcaf59042001-10-17 07:15:43 +00003862 specific == d->d_wrapped)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003863 specific = d->d_wrapped;
3864 else
3865 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003866 }
3867 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003868 else
3869 use_generic = 1;
3870 } while ((++p)->offset == offset);
3871 if (specific && !use_generic)
3872 *ptr = specific;
3873 else
3874 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003875 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003877
Guido van Rossum6d204072001-10-21 00:44:31 +00003878/* This function is called by PyType_Ready() to populate the type's
3879 dictionary with method descriptors for function slots. For each
3880 function slot (like tp_repr) that's defined in the type, one or
3881 more corresponding descriptors are added in the type's tp_dict
3882 dictionary under the appropriate name (like __repr__). Some
3883 function slots cause more than one descriptor to be added (for
3884 example, the nb_add slot adds both __add__ and __radd__
3885 descriptors) and some function slots compete for the same
3886 descriptor (for example both sq_item and mp_subscript generate a
3887 __getitem__ descriptor). This only adds new descriptors and
3888 doesn't overwrite entries in tp_dict that were previously
3889 defined. The descriptors contain a reference to the C function
3890 they must call, so that it's safe if they are copied into a
3891 subtype's __dict__ and the subtype has a different C function in
3892 its slot -- calling the method defined by the descriptor will call
3893 the C function that was used to create it, rather than the C
3894 function present in the slot when it is called. (This is important
3895 because a subtype may have a C function in the slot that calls the
3896 method from the dictionary, and we want to avoid infinite recursion
3897 here.) */
3898
3899static int
3900add_operators(PyTypeObject *type)
3901{
3902 PyObject *dict = type->tp_dict;
3903 slotdef *p;
3904 PyObject *descr;
3905 void **ptr;
3906
3907 init_slotdefs();
3908 for (p = slotdefs; p->name; p++) {
3909 if (p->wrapper == NULL)
3910 continue;
3911 ptr = slotptr(type, p->offset);
3912 if (!ptr || !*ptr)
3913 continue;
3914 if (PyDict_GetItem(dict, p->name_strobj))
3915 continue;
3916 descr = PyDescr_NewWrapper(type, p, *ptr);
3917 if (descr == NULL)
3918 return -1;
3919 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
3920 return -1;
3921 Py_DECREF(descr);
3922 }
3923 if (type->tp_new != NULL) {
3924 if (add_tp_new_wrapper(type) < 0)
3925 return -1;
3926 }
3927 return 0;
3928}
3929
Guido van Rossum705f0f52001-08-24 16:47:00 +00003930
3931/* Cooperative 'super' */
3932
3933typedef struct {
3934 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003935 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003936 PyObject *obj;
3937} superobject;
3938
Guido van Rossum6f799372001-09-20 20:46:19 +00003939static PyMemberDef super_members[] = {
3940 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3941 "the class invoking super()"},
3942 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3943 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003944 {0}
3945};
3946
Guido van Rossum705f0f52001-08-24 16:47:00 +00003947static void
3948super_dealloc(PyObject *self)
3949{
3950 superobject *su = (superobject *)self;
3951
Guido van Rossum048eb752001-10-02 21:24:57 +00003952 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003953 Py_XDECREF(su->obj);
3954 Py_XDECREF(su->type);
3955 self->ob_type->tp_free(self);
3956}
3957
3958static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003959super_repr(PyObject *self)
3960{
3961 superobject *su = (superobject *)self;
3962
3963 if (su->obj)
3964 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003965 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003966 su->type ? su->type->tp_name : "NULL",
3967 su->obj->ob_type->tp_name);
3968 else
3969 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003970 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003971 su->type ? su->type->tp_name : "NULL");
3972}
3973
3974static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003975super_getattro(PyObject *self, PyObject *name)
3976{
3977 superobject *su = (superobject *)self;
3978
3979 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00003980 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003981 descrgetfunc f;
3982 int i, n;
3983
Guido van Rossume705ef12001-08-29 15:47:06 +00003984 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003985 if (mro == NULL)
3986 n = 0;
3987 else {
3988 assert(PyTuple_Check(mro));
3989 n = PyTuple_GET_SIZE(mro);
3990 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003991 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003992 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003993 break;
3994 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003995 if (i >= n && PyType_Check(su->obj)) {
3996 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003997 if (mro == NULL)
3998 n = 0;
3999 else {
4000 assert(PyTuple_Check(mro));
4001 n = PyTuple_GET_SIZE(mro);
4002 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004003 for (i = 0; i < n; i++) {
4004 if ((PyObject *)(su->type) ==
4005 PyTuple_GET_ITEM(mro, i))
4006 break;
4007 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004008 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004009 i++;
4010 res = NULL;
4011 for (; i < n; i++) {
4012 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004013 if (PyType_Check(tmp))
4014 dict = ((PyTypeObject *)tmp)->tp_dict;
4015 else if (PyClass_Check(tmp))
4016 dict = ((PyClassObject *)tmp)->cl_dict;
4017 else
4018 continue;
4019 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004020 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004021 Py_INCREF(res);
4022 f = res->ob_type->tp_descr_get;
4023 if (f != NULL) {
4024 tmp = f(res, su->obj, res);
4025 Py_DECREF(res);
4026 res = tmp;
4027 }
4028 return res;
4029 }
4030 }
4031 }
4032 return PyObject_GenericGetAttr(self, name);
4033}
4034
Guido van Rossum5b443c62001-12-03 15:38:28 +00004035static int
4036supercheck(PyTypeObject *type, PyObject *obj)
4037{
4038 if (!PyType_IsSubtype(obj->ob_type, type) &&
4039 !(PyType_Check(obj) &&
4040 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4041 PyErr_SetString(PyExc_TypeError,
4042 "super(type, obj): "
4043 "obj must be an instance or subtype of type");
4044 return -1;
4045 }
4046 else
4047 return 0;
4048}
4049
Guido van Rossum705f0f52001-08-24 16:47:00 +00004050static PyObject *
4051super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4052{
4053 superobject *su = (superobject *)self;
4054 superobject *new;
4055
4056 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4057 /* Not binding to an object, or already bound */
4058 Py_INCREF(self);
4059 return self;
4060 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004061 if (su->ob_type != &PySuper_Type)
4062 /* If su is an instance of a subclass of super,
4063 call its type */
4064 return PyObject_CallFunction((PyObject *)su->ob_type,
4065 "OO", su->type, obj);
4066 else {
4067 /* Inline the common case */
4068 if (supercheck(su->type, obj) < 0)
4069 return NULL;
4070 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4071 NULL, NULL);
4072 if (new == NULL)
4073 return NULL;
4074 Py_INCREF(su->type);
4075 Py_INCREF(obj);
4076 new->type = su->type;
4077 new->obj = obj;
4078 return (PyObject *)new;
4079 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004080}
4081
4082static int
4083super_init(PyObject *self, PyObject *args, PyObject *kwds)
4084{
4085 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004086 PyTypeObject *type;
4087 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004088
4089 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4090 return -1;
4091 if (obj == Py_None)
4092 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004093 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004094 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004095 Py_INCREF(type);
4096 Py_XINCREF(obj);
4097 su->type = type;
4098 su->obj = obj;
4099 return 0;
4100}
4101
4102static char super_doc[] =
4103"super(type) -> unbound super object\n"
4104"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004105"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004106"Typical use to call a cooperative superclass method:\n"
4107"class C(B):\n"
4108" def meth(self, arg):\n"
4109" super(C, self).meth(arg)";
4110
Guido van Rossum048eb752001-10-02 21:24:57 +00004111static int
4112super_traverse(PyObject *self, visitproc visit, void *arg)
4113{
4114 superobject *su = (superobject *)self;
4115 int err;
4116
4117#define VISIT(SLOT) \
4118 if (SLOT) { \
4119 err = visit((PyObject *)(SLOT), arg); \
4120 if (err) \
4121 return err; \
4122 }
4123
4124 VISIT(su->obj);
4125 VISIT(su->type);
4126
4127#undef VISIT
4128
4129 return 0;
4130}
4131
Guido van Rossum705f0f52001-08-24 16:47:00 +00004132PyTypeObject PySuper_Type = {
4133 PyObject_HEAD_INIT(&PyType_Type)
4134 0, /* ob_size */
4135 "super", /* tp_name */
4136 sizeof(superobject), /* tp_basicsize */
4137 0, /* tp_itemsize */
4138 /* methods */
4139 super_dealloc, /* tp_dealloc */
4140 0, /* tp_print */
4141 0, /* tp_getattr */
4142 0, /* tp_setattr */
4143 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004144 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004145 0, /* tp_as_number */
4146 0, /* tp_as_sequence */
4147 0, /* tp_as_mapping */
4148 0, /* tp_hash */
4149 0, /* tp_call */
4150 0, /* tp_str */
4151 super_getattro, /* tp_getattro */
4152 0, /* tp_setattro */
4153 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004154 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4155 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004156 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004157 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004158 0, /* tp_clear */
4159 0, /* tp_richcompare */
4160 0, /* tp_weaklistoffset */
4161 0, /* tp_iter */
4162 0, /* tp_iternext */
4163 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004164 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004165 0, /* tp_getset */
4166 0, /* tp_base */
4167 0, /* tp_dict */
4168 super_descr_get, /* tp_descr_get */
4169 0, /* tp_descr_set */
4170 0, /* tp_dictoffset */
4171 super_init, /* tp_init */
4172 PyType_GenericAlloc, /* tp_alloc */
4173 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004174 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004175};