blob: c938f524536d527b63e17739ab62a0aa3f4dd95e [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
Tim Peters24008312002-03-17 18:56:20 +000082static PyObject *
83type_get_doc(PyTypeObject *type, void *context)
84{
85 PyObject *result;
86 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
87 if (type->tp_doc == NULL) {
88 Py_INCREF(Py_None);
89 return Py_None;
90 }
91 return PyString_FromString(type->tp_doc);
92 }
93 result = PyDict_GetItemString(type->tp_dict, "__doc__");
94 Py_INCREF(result);
95 return result;
96}
97
Neil Schemenauerf23473f2001-10-21 22:28:58 +000098static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000099 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000100 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000102 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000103 {0}
104};
105
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000106static int
107type_compare(PyObject *v, PyObject *w)
108{
109 /* This is called with type objects only. So we
110 can just compare the addresses. */
111 Py_uintptr_t vv = (Py_uintptr_t)v;
112 Py_uintptr_t ww = (Py_uintptr_t)w;
113 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
114}
115
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000117type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000118{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000119 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000120 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000121
122 mod = type_module(type, NULL);
123 if (mod == NULL)
124 PyErr_Clear();
125 else if (!PyString_Check(mod)) {
126 Py_DECREF(mod);
127 mod = NULL;
128 }
129 name = type_name(type, NULL);
130 if (name == NULL)
131 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000132
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000133 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
134 kind = "class";
135 else
136 kind = "type";
137
Barry Warsaw7ce36942001-08-24 18:34:26 +0000138 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000139 rtn = PyString_FromFormat("<%s '%s.%s'>",
140 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000141 PyString_AS_STRING(mod),
142 PyString_AS_STRING(name));
143 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000144 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000145 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000146
Guido van Rossumc3542212001-08-16 09:18:56 +0000147 Py_XDECREF(mod);
148 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000149 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150}
151
Tim Peters6d6c1a32001-08-02 04:15:00 +0000152static PyObject *
153type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
154{
155 PyObject *obj;
156
157 if (type->tp_new == NULL) {
158 PyErr_Format(PyExc_TypeError,
159 "cannot create '%.100s' instances",
160 type->tp_name);
161 return NULL;
162 }
163
Tim Peters3f996e72001-09-13 19:18:27 +0000164 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000165 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000166 /* Ugly exception: when the call was type(something),
167 don't call tp_init on the result. */
168 if (type == &PyType_Type &&
169 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
170 (kwds == NULL ||
171 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
172 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000173 type = obj->ob_type;
174 if (type->tp_init != NULL &&
175 type->tp_init(obj, args, kwds) < 0) {
176 Py_DECREF(obj);
177 obj = NULL;
178 }
179 }
180 return obj;
181}
182
183PyObject *
184PyType_GenericAlloc(PyTypeObject *type, int nitems)
185{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000186 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000187 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000188
189 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000190 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000191 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000192 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000193
Neil Schemenauerc806c882001-08-29 23:54:54 +0000194 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000195 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000196
Neil Schemenauerc806c882001-08-29 23:54:54 +0000197 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000198
Tim Peters6d6c1a32001-08-02 04:15:00 +0000199 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
200 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000201
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202 if (type->tp_itemsize == 0)
203 PyObject_INIT(obj, type);
204 else
205 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000206
Tim Peters6d6c1a32001-08-02 04:15:00 +0000207 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000208 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000209 return obj;
210}
211
212PyObject *
213PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
214{
215 return type->tp_alloc(type, 0);
216}
217
Guido van Rossum9475a232001-10-05 20:51:39 +0000218/* Helpers for subtyping */
219
220static int
221subtype_traverse(PyObject *self, visitproc visit, void *arg)
222{
223 PyTypeObject *type, *base;
224 traverseproc f;
225 int err;
226
227 /* Find the nearest base with a different tp_traverse */
228 type = self->ob_type;
229 base = type->tp_base;
230 while ((f = base->tp_traverse) == subtype_traverse) {
231 base = base->tp_base;
232 assert(base);
233 }
234
235 if (type->tp_dictoffset != base->tp_dictoffset) {
236 PyObject **dictptr = _PyObject_GetDictPtr(self);
237 if (dictptr && *dictptr) {
238 err = visit(*dictptr, arg);
239 if (err)
240 return err;
241 }
242 }
243
244 if (f)
245 return f(self, visit, arg);
246 return 0;
247}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000248
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000249staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
250
251static int
252call_finalizer(PyObject *self)
253{
254 static PyObject *del_str = NULL;
255 PyObject *del, *res;
256 PyObject *error_type, *error_value, *error_traceback;
257
258 /* Temporarily resurrect the object. */
259#ifdef Py_TRACE_REFS
260#ifndef Py_REF_DEBUG
261# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
262#endif
263 /* much too complicated if Py_TRACE_REFS defined */
264 _Py_NewReference((PyObject *)self);
265#ifdef COUNT_ALLOCS
266 /* compensate for boost in _Py_NewReference; note that
267 * _Py_RefTotal was also boosted; we'll knock that down later.
268 */
269 self->ob_type->tp_allocs--;
270#endif
271#else /* !Py_TRACE_REFS */
272 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
273 Py_INCREF(self);
274#endif /* !Py_TRACE_REFS */
275
276 /* Save the current exception, if any. */
277 PyErr_Fetch(&error_type, &error_value, &error_traceback);
278
279 /* Execute __del__ method, if any. */
280 del = lookup_maybe(self, "__del__", &del_str);
281 if (del != NULL) {
282 res = PyEval_CallObject(del, NULL);
283 if (res == NULL)
284 PyErr_WriteUnraisable(del);
285 else
286 Py_DECREF(res);
287 Py_DECREF(del);
288 }
289
290 /* Restore the saved exception. */
291 PyErr_Restore(error_type, error_value, error_traceback);
292
293 /* Undo the temporary resurrection; can't use DECREF here, it would
294 * cause a recursive call.
295 */
296#ifdef Py_REF_DEBUG
297 /* _Py_RefTotal was boosted either by _Py_NewReference or
298 * Py_INCREF above.
299 */
300 _Py_RefTotal--;
301#endif
302 if (--self->ob_refcnt > 0) {
303#ifdef COUNT_ALLOCS
304 self->ob_type->tp_frees--;
305#endif
306 _PyObject_GC_TRACK(self);
307 return -1; /* __del__ added a reference; don't delete now */
308 }
309#ifdef Py_TRACE_REFS
310 _Py_ForgetReference((PyObject *)self);
311#ifdef COUNT_ALLOCS
312 /* compensate for increment in _Py_ForgetReference */
313 self->ob_type->tp_frees--;
314#endif
315#endif
316
317 return 0;
318}
319
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320static void
321subtype_dealloc(PyObject *self)
322{
Guido van Rossum14227b42001-12-06 02:35:58 +0000323 PyTypeObject *type, *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000324 destructor f;
325
326 /* This exists so we can DECREF self->ob_type */
327
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000328 if (call_finalizer(self) < 0)
329 return;
330
Tim Peters6d6c1a32001-08-02 04:15:00 +0000331 /* Find the nearest base with a different tp_dealloc */
332 type = self->ob_type;
Guido van Rossum14227b42001-12-06 02:35:58 +0000333 base = type->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000334 while ((f = base->tp_dealloc) == subtype_dealloc) {
335 base = base->tp_base;
336 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000337 }
338
339 /* Clear __slots__ variables */
340 if (type->tp_basicsize != base->tp_basicsize &&
341 type->tp_itemsize == 0)
342 {
343 char *addr = ((char *)self);
344 char *p = addr + base->tp_basicsize;
345 char *q = addr + type->tp_basicsize;
346 for (; p < q; p += sizeof(PyObject *)) {
347 PyObject **pp;
348 if (p == addr + type->tp_dictoffset ||
349 p == addr + type->tp_weaklistoffset)
350 continue;
351 pp = (PyObject **)p;
352 if (*pp != NULL) {
353 Py_DECREF(*pp);
354 *pp = NULL;
Guido van Rossum33bab012001-12-05 22:45:48 +0000355 }
356 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000357 }
358
359 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000360 if (type->tp_dictoffset && !base->tp_dictoffset) {
361 PyObject **dictptr = _PyObject_GetDictPtr(self);
362 if (dictptr != NULL) {
363 PyObject *dict = *dictptr;
364 if (dict != NULL) {
365 Py_DECREF(dict);
366 *dictptr = NULL;
367 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368 }
369 }
370
Guido van Rossum9676b222001-08-17 20:32:36 +0000371 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000372 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000373 PyObject_ClearWeakRefs(self);
374
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375 /* Finalize GC if the base doesn't do GC and we do */
376 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000377 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000378
379 /* Call the base tp_dealloc() */
380 assert(f);
381 f(self);
382
383 /* Can't reference self beyond this point */
384 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
385 Py_DECREF(type);
386 }
387}
388
Tim Peters6d6c1a32001-08-02 04:15:00 +0000389staticforward PyTypeObject *solid_base(PyTypeObject *type);
390
391typedef struct {
392 PyTypeObject type;
393 PyNumberMethods as_number;
394 PySequenceMethods as_sequence;
395 PyMappingMethods as_mapping;
396 PyBufferProcs as_buffer;
397 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000398 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000399} etype;
400
401/* type test with subclassing support */
402
403int
404PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
405{
406 PyObject *mro;
407
Guido van Rossum9478d072001-09-07 18:52:13 +0000408 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
409 return b == a || b == &PyBaseObject_Type;
410
Tim Peters6d6c1a32001-08-02 04:15:00 +0000411 mro = a->tp_mro;
412 if (mro != NULL) {
413 /* Deal with multiple inheritance without recursion
414 by walking the MRO tuple */
415 int i, n;
416 assert(PyTuple_Check(mro));
417 n = PyTuple_GET_SIZE(mro);
418 for (i = 0; i < n; i++) {
419 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
420 return 1;
421 }
422 return 0;
423 }
424 else {
425 /* a is not completely initilized yet; follow tp_base */
426 do {
427 if (a == b)
428 return 1;
429 a = a->tp_base;
430 } while (a != NULL);
431 return b == &PyBaseObject_Type;
432 }
433}
434
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000435/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000436 without looking in the instance dictionary
437 (so we can't use PyObject_GetAttr) but still binding
438 it to the instance. The arguments are the object,
439 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000440 static variable used to cache the interned Python string.
441
442 Two variants:
443
444 - lookup_maybe() returns NULL without raising an exception
445 when the _PyType_Lookup() call fails;
446
447 - lookup_method() always raises an exception upon errors.
448*/
Guido van Rossum60718732001-08-28 17:47:51 +0000449
450static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000451lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000452{
453 PyObject *res;
454
455 if (*attrobj == NULL) {
456 *attrobj = PyString_InternFromString(attrstr);
457 if (*attrobj == NULL)
458 return NULL;
459 }
460 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000461 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000462 descrgetfunc f;
463 if ((f = res->ob_type->tp_descr_get) == NULL)
464 Py_INCREF(res);
465 else
466 res = f(res, self, (PyObject *)(self->ob_type));
467 }
468 return res;
469}
470
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000471static PyObject *
472lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
473{
474 PyObject *res = lookup_maybe(self, attrstr, attrobj);
475 if (res == NULL && !PyErr_Occurred())
476 PyErr_SetObject(PyExc_AttributeError, *attrobj);
477 return res;
478}
479
Guido van Rossum2730b132001-08-28 18:22:14 +0000480/* A variation of PyObject_CallMethod that uses lookup_method()
481 instead of PyObject_GetAttrString(). This uses the same convention
482 as lookup_method to cache the interned name string object. */
483
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000484static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000485call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
486{
487 va_list va;
488 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000489 va_start(va, format);
490
Guido van Rossumda21c012001-10-03 00:50:18 +0000491 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000492 if (func == NULL) {
493 va_end(va);
494 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000495 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000496 return NULL;
497 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000498
499 if (format && *format)
500 args = Py_VaBuildValue(format, va);
501 else
502 args = PyTuple_New(0);
503
504 va_end(va);
505
506 if (args == NULL)
507 return NULL;
508
509 assert(PyTuple_Check(args));
510 retval = PyObject_Call(func, args, NULL);
511
512 Py_DECREF(args);
513 Py_DECREF(func);
514
515 return retval;
516}
517
518/* Clone of call_method() that returns NotImplemented when the lookup fails. */
519
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000520static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000521call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
522{
523 va_list va;
524 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000525 va_start(va, format);
526
Guido van Rossumda21c012001-10-03 00:50:18 +0000527 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000528 if (func == NULL) {
529 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000530 if (!PyErr_Occurred()) {
531 Py_INCREF(Py_NotImplemented);
532 return Py_NotImplemented;
533 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000534 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000535 }
536
537 if (format && *format)
538 args = Py_VaBuildValue(format, va);
539 else
540 args = PyTuple_New(0);
541
542 va_end(va);
543
Guido van Rossum717ce002001-09-14 16:58:08 +0000544 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000545 return NULL;
546
Guido van Rossum717ce002001-09-14 16:58:08 +0000547 assert(PyTuple_Check(args));
548 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000549
550 Py_DECREF(args);
551 Py_DECREF(func);
552
553 return retval;
554}
555
Tim Peters6d6c1a32001-08-02 04:15:00 +0000556/* Method resolution order algorithm from "Putting Metaclasses to Work"
557 by Forman and Danforth (Addison-Wesley 1999). */
558
559static int
560conservative_merge(PyObject *left, PyObject *right)
561{
562 int left_size;
563 int right_size;
564 int i, j, r, ok;
565 PyObject *temp, *rr;
566
567 assert(PyList_Check(left));
568 assert(PyList_Check(right));
569
570 again:
571 left_size = PyList_GET_SIZE(left);
572 right_size = PyList_GET_SIZE(right);
573 for (i = 0; i < left_size; i++) {
574 for (j = 0; j < right_size; j++) {
575 if (PyList_GET_ITEM(left, i) ==
576 PyList_GET_ITEM(right, j)) {
577 /* found a merge point */
578 temp = PyList_New(0);
579 if (temp == NULL)
580 return -1;
581 for (r = 0; r < j; r++) {
582 rr = PyList_GET_ITEM(right, r);
583 ok = PySequence_Contains(left, rr);
584 if (ok < 0) {
585 Py_DECREF(temp);
586 return -1;
587 }
588 if (!ok) {
589 ok = PyList_Append(temp, rr);
590 if (ok < 0) {
591 Py_DECREF(temp);
592 return -1;
593 }
594 }
595 }
596 ok = PyList_SetSlice(left, i, i, temp);
597 Py_DECREF(temp);
598 if (ok < 0)
599 return -1;
600 ok = PyList_SetSlice(right, 0, j+1, NULL);
601 if (ok < 0)
602 return -1;
603 goto again;
604 }
605 }
606 }
607 return PyList_SetSlice(left, left_size, left_size, right);
608}
609
610static int
611serious_order_disagreements(PyObject *left, PyObject *right)
612{
613 return 0; /* XXX later -- for now, we cheat: "don't do that" */
614}
615
Tim Petersa91e9642001-11-14 23:32:33 +0000616static int
617fill_classic_mro(PyObject *mro, PyObject *cls)
618{
619 PyObject *bases, *base;
620 int i, n;
621
622 assert(PyList_Check(mro));
623 assert(PyClass_Check(cls));
624 i = PySequence_Contains(mro, cls);
625 if (i < 0)
626 return -1;
627 if (!i) {
628 if (PyList_Append(mro, cls) < 0)
629 return -1;
630 }
631 bases = ((PyClassObject *)cls)->cl_bases;
632 assert(bases && PyTuple_Check(bases));
633 n = PyTuple_GET_SIZE(bases);
634 for (i = 0; i < n; i++) {
635 base = PyTuple_GET_ITEM(bases, i);
636 if (fill_classic_mro(mro, base) < 0)
637 return -1;
638 }
639 return 0;
640}
641
642static PyObject *
643classic_mro(PyObject *cls)
644{
645 PyObject *mro;
646
647 assert(PyClass_Check(cls));
648 mro = PyList_New(0);
649 if (mro != NULL) {
650 if (fill_classic_mro(mro, cls) == 0)
651 return mro;
652 Py_DECREF(mro);
653 }
654 return NULL;
655}
656
Tim Peters6d6c1a32001-08-02 04:15:00 +0000657static PyObject *
658mro_implementation(PyTypeObject *type)
659{
660 int i, n, ok;
661 PyObject *bases, *result;
662
663 bases = type->tp_bases;
664 n = PyTuple_GET_SIZE(bases);
665 result = Py_BuildValue("[O]", (PyObject *)type);
666 if (result == NULL)
667 return NULL;
668 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000669 PyObject *base = PyTuple_GET_ITEM(bases, i);
670 PyObject *parentMRO;
671 if (PyType_Check(base))
672 parentMRO = PySequence_List(
673 ((PyTypeObject*)base)->tp_mro);
674 else
675 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000676 if (parentMRO == NULL) {
677 Py_DECREF(result);
678 return NULL;
679 }
680 if (serious_order_disagreements(result, parentMRO)) {
681 Py_DECREF(result);
682 return NULL;
683 }
684 ok = conservative_merge(result, parentMRO);
685 Py_DECREF(parentMRO);
686 if (ok < 0) {
687 Py_DECREF(result);
688 return NULL;
689 }
690 }
691 return result;
692}
693
694static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000695mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696{
697 PyTypeObject *type = (PyTypeObject *)self;
698
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699 return mro_implementation(type);
700}
701
702static int
703mro_internal(PyTypeObject *type)
704{
705 PyObject *mro, *result, *tuple;
706
707 if (type->ob_type == &PyType_Type) {
708 result = mro_implementation(type);
709 }
710 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000711 static PyObject *mro_str;
712 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713 if (mro == NULL)
714 return -1;
715 result = PyObject_CallObject(mro, NULL);
716 Py_DECREF(mro);
717 }
718 if (result == NULL)
719 return -1;
720 tuple = PySequence_Tuple(result);
721 Py_DECREF(result);
722 type->tp_mro = tuple;
723 return 0;
724}
725
726
727/* Calculate the best base amongst multiple base classes.
728 This is the first one that's on the path to the "solid base". */
729
730static PyTypeObject *
731best_base(PyObject *bases)
732{
733 int i, n;
734 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000735 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000736
737 assert(PyTuple_Check(bases));
738 n = PyTuple_GET_SIZE(bases);
739 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000740 base = NULL;
741 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000742 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000743 base_proto = PyTuple_GET_ITEM(bases, i);
744 if (PyClass_Check(base_proto))
745 continue;
746 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000747 PyErr_SetString(
748 PyExc_TypeError,
749 "bases must be types");
750 return NULL;
751 }
Tim Petersa91e9642001-11-14 23:32:33 +0000752 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000753 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000754 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755 return NULL;
756 }
757 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000758 if (winner == NULL) {
759 winner = candidate;
760 base = base_i;
761 }
762 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000763 ;
764 else if (PyType_IsSubtype(candidate, winner)) {
765 winner = candidate;
766 base = base_i;
767 }
768 else {
769 PyErr_SetString(
770 PyExc_TypeError,
771 "multiple bases have "
772 "instance lay-out conflict");
773 return NULL;
774 }
775 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000776 if (base == NULL)
777 PyErr_SetString(PyExc_TypeError,
778 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000779 return base;
780}
781
782static int
783extra_ivars(PyTypeObject *type, PyTypeObject *base)
784{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000785 size_t t_size = type->tp_basicsize;
786 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000787
Guido van Rossum9676b222001-08-17 20:32:36 +0000788 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789 if (type->tp_itemsize || base->tp_itemsize) {
790 /* If itemsize is involved, stricter rules */
791 return t_size != b_size ||
792 type->tp_itemsize != base->tp_itemsize;
793 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000794 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
795 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
796 t_size -= sizeof(PyObject *);
797 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
798 type->tp_dictoffset + sizeof(PyObject *) == t_size)
799 t_size -= sizeof(PyObject *);
800
801 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000802}
803
804static PyTypeObject *
805solid_base(PyTypeObject *type)
806{
807 PyTypeObject *base;
808
809 if (type->tp_base)
810 base = solid_base(type->tp_base);
811 else
812 base = &PyBaseObject_Type;
813 if (extra_ivars(type, base))
814 return type;
815 else
816 return base;
817}
818
819staticforward void object_dealloc(PyObject *);
820staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000821staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000822staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823
824static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000825subtype_dict(PyObject *obj, void *context)
826{
827 PyObject **dictptr = _PyObject_GetDictPtr(obj);
828 PyObject *dict;
829
830 if (dictptr == NULL) {
831 PyErr_SetString(PyExc_AttributeError,
832 "This object has no __dict__");
833 return NULL;
834 }
835 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000836 if (dict == NULL)
837 *dictptr = dict = PyDict_New();
838 Py_XINCREF(dict);
839 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000840}
841
Guido van Rossum6661be32001-10-26 04:26:12 +0000842static int
843subtype_setdict(PyObject *obj, PyObject *value, void *context)
844{
845 PyObject **dictptr = _PyObject_GetDictPtr(obj);
846 PyObject *dict;
847
848 if (dictptr == NULL) {
849 PyErr_SetString(PyExc_AttributeError,
850 "This object has no __dict__");
851 return -1;
852 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000853 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000854 PyErr_SetString(PyExc_TypeError,
855 "__dict__ must be set to a dictionary");
856 return -1;
857 }
858 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000859 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000860 *dictptr = value;
861 Py_XDECREF(dict);
862 return 0;
863}
864
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000865static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000866 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000867 {0},
868};
869
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000870/* bozo: __getstate__ that raises TypeError */
871
872static PyObject *
873bozo_func(PyObject *self, PyObject *args)
874{
875 PyErr_SetString(PyExc_TypeError,
876 "a class that defines __slots__ without "
877 "defining __getstate__ cannot be pickled");
878 return NULL;
879}
880
881static PyMethodDef bozo_ml = {"__getstate__", bozo_func};
882
883static PyObject *bozo_obj = NULL;
884
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000885static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
887{
888 PyObject *name, *bases, *dict;
889 static char *kwlist[] = {"name", "bases", "dict", 0};
890 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000891 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000892 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000893 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000894 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895
Tim Peters3abca122001-10-27 19:37:48 +0000896 assert(args != NULL && PyTuple_Check(args));
897 assert(kwds == NULL || PyDict_Check(kwds));
898
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000899 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000900 {
901 const int nargs = PyTuple_GET_SIZE(args);
902 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
903
904 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
905 PyObject *x = PyTuple_GET_ITEM(args, 0);
906 Py_INCREF(x->ob_type);
907 return (PyObject *) x->ob_type;
908 }
909
910 /* SF bug 475327 -- if that didn't trigger, we need 3
911 arguments. but PyArg_ParseTupleAndKeywords below may give
912 a msg saying type() needs exactly 3. */
913 if (nargs + nkwds != 3) {
914 PyErr_SetString(PyExc_TypeError,
915 "type() takes 1 or 3 arguments");
916 return NULL;
917 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000918 }
919
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000920 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000921 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
922 &name,
923 &PyTuple_Type, &bases,
924 &PyDict_Type, &dict))
925 return NULL;
926
927 /* Determine the proper metatype to deal with this,
928 and check for metatype conflicts while we're at it.
929 Note that if some other metatype wins to contract,
930 it's possible that its instances are not types. */
931 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000932 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000933 for (i = 0; i < nbases; i++) {
934 tmp = PyTuple_GET_ITEM(bases, i);
935 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000936 if (tmptype == &PyClass_Type)
937 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000938 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000939 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000940 if (PyType_IsSubtype(tmptype, winner)) {
941 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000942 continue;
943 }
944 PyErr_SetString(PyExc_TypeError,
945 "metatype conflict among bases");
946 return NULL;
947 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000948 if (winner != metatype) {
949 if (winner->tp_new != type_new) /* Pass it to the winner */
950 return winner->tp_new(winner, args, kwds);
951 metatype = winner;
952 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953
954 /* Adjust for empty tuple bases */
955 if (nbases == 0) {
956 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
957 if (bases == NULL)
958 return NULL;
959 nbases = 1;
960 }
961 else
962 Py_INCREF(bases);
963
964 /* XXX From here until type is allocated, "return NULL" leaks bases! */
965
966 /* Calculate best base, and check that all bases are type objects */
967 base = best_base(bases);
968 if (base == NULL)
969 return NULL;
970 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
971 PyErr_Format(PyExc_TypeError,
972 "type '%.100s' is not an acceptable base type",
973 base->tp_name);
974 return NULL;
975 }
976
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977 /* Check for a __slots__ sequence variable in dict, and count it */
978 slots = PyDict_GetItemString(dict, "__slots__");
979 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000980 add_dict = 0;
981 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000982 if (slots != NULL) {
983 /* Make it into a tuple */
984 if (PyString_Check(slots))
985 slots = Py_BuildValue("(O)", slots);
986 else
987 slots = PySequence_Tuple(slots);
988 if (slots == NULL)
989 return NULL;
990 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000991 if (nslots > 0 && base->tp_itemsize != 0) {
992 PyErr_Format(PyExc_TypeError,
993 "nonempty __slots__ "
994 "not supported for subtype of '%s'",
995 base->tp_name);
996 return NULL;
997 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998 for (i = 0; i < nslots; i++) {
999 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
1000 PyErr_SetString(PyExc_TypeError,
1001 "__slots__ must be a sequence of strings");
1002 Py_DECREF(slots);
1003 return NULL;
1004 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001005 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006 }
1007 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001008 if (slots != NULL) {
1009 /* See if *this* class defines __getstate__ */
1010 PyObject *getstate = PyDict_GetItemString(dict,
1011 "__getstate__");
1012 if (getstate == NULL) {
1013 /* If not, provide a bozo that raises TypeError */
1014 if (bozo_obj == NULL) {
1015 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1016 if (bozo_obj == NULL) {
1017 /* XXX decref various things */
1018 return NULL;
1019 }
1020 }
1021 if (PyDict_SetItemString(dict,
1022 "__getstate__",
1023 bozo_obj) < 0) {
1024 /* XXX decref various things */
1025 return NULL;
1026 }
1027 }
1028 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029 if (slots == NULL && base->tp_dictoffset == 0 &&
1030 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001031 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001032 add_dict++;
1033 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001034 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1035 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001036 nslots++;
1037 add_weak++;
1038 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039
1040 /* XXX From here until type is safely allocated,
1041 "return NULL" may leak slots! */
1042
1043 /* Allocate the type object */
1044 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1045 if (type == NULL)
1046 return NULL;
1047
1048 /* Keep name and slots alive in the extended type object */
1049 et = (etype *)type;
1050 Py_INCREF(name);
1051 et->name = name;
1052 et->slots = slots;
1053
Guido van Rossumdc91b992001-08-08 22:26:22 +00001054 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001055 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1056 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001057 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1058 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001059
1060 /* It's a new-style number unless it specifically inherits any
1061 old-style numeric behavior */
1062 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1063 (base->tp_as_number == NULL))
1064 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1065
1066 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001067 type->tp_as_number = &et->as_number;
1068 type->tp_as_sequence = &et->as_sequence;
1069 type->tp_as_mapping = &et->as_mapping;
1070 type->tp_as_buffer = &et->as_buffer;
1071 type->tp_name = PyString_AS_STRING(name);
1072
1073 /* Set tp_base and tp_bases */
1074 type->tp_bases = bases;
1075 Py_INCREF(base);
1076 type->tp_base = base;
1077
Guido van Rossum687ae002001-10-15 22:03:32 +00001078 /* Initialize tp_dict from passed-in dict */
1079 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080 if (dict == NULL) {
1081 Py_DECREF(type);
1082 return NULL;
1083 }
1084
Guido van Rossumc3542212001-08-16 09:18:56 +00001085 /* Set __module__ in the dict */
1086 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1087 tmp = PyEval_GetGlobals();
1088 if (tmp != NULL) {
1089 tmp = PyDict_GetItemString(tmp, "__name__");
1090 if (tmp != NULL) {
1091 if (PyDict_SetItemString(dict, "__module__",
1092 tmp) < 0)
1093 return NULL;
1094 }
1095 }
1096 }
1097
Tim Peters2f93e282001-10-04 05:27:00 +00001098 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001099 and is a string. The __doc__ accessor will first look for tp_doc;
1100 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001101 */
1102 {
1103 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1104 if (doc != NULL && PyString_Check(doc)) {
1105 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001106 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001107 if (type->tp_doc == NULL) {
1108 Py_DECREF(type);
1109 return NULL;
1110 }
1111 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1112 }
1113 }
1114
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115 /* Special-case __new__: if it's a plain function,
1116 make it a static function */
1117 tmp = PyDict_GetItemString(dict, "__new__");
1118 if (tmp != NULL && PyFunction_Check(tmp)) {
1119 tmp = PyStaticMethod_New(tmp);
1120 if (tmp == NULL) {
1121 Py_DECREF(type);
1122 return NULL;
1123 }
1124 PyDict_SetItemString(dict, "__new__", tmp);
1125 Py_DECREF(tmp);
1126 }
1127
1128 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1129 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001130 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131 if (slots != NULL) {
1132 for (i = 0; i < nslots; i++, mp++) {
1133 mp->name = PyString_AS_STRING(
1134 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001135 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001136 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001137 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001138 strcmp(mp->name, "__weakref__") == 0) {
1139 mp->type = T_OBJECT;
Guido van Rossum9676b222001-08-17 20:32:36 +00001140 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001141 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001142 slotoffset += sizeof(PyObject *);
1143 }
1144 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001145 else {
1146 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001147 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001148 type->tp_dictoffset =
1149 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001150 else
1151 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001152 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001153 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001154 }
1155 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001156 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001157 type->tp_weaklistoffset = slotoffset;
1158 mp->name = "__weakref__";
1159 mp->type = T_OBJECT;
1160 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001161 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001162 mp++;
1163 slotoffset += sizeof(PyObject *);
1164 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 }
1166 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001167 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001168 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169
1170 /* Special case some slots */
1171 if (type->tp_dictoffset != 0 || nslots > 0) {
1172 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1173 type->tp_getattro = PyObject_GenericGetAttr;
1174 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1175 type->tp_setattro = PyObject_GenericSetAttr;
1176 }
1177 type->tp_dealloc = subtype_dealloc;
1178
Guido van Rossum9475a232001-10-05 20:51:39 +00001179 /* Enable GC unless there are really no instance variables possible */
1180 if (!(type->tp_basicsize == sizeof(PyObject) &&
1181 type->tp_itemsize == 0))
1182 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1183
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184 /* Always override allocation strategy to use regular heap */
1185 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001186 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1187 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001188 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001189 type->tp_clear = base->tp_clear;
1190 }
1191 else
1192 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193
1194 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001195 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 Py_DECREF(type);
1197 return NULL;
1198 }
1199
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001200 /* Put the proper slots in place */
1201 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001202
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 return (PyObject *)type;
1204}
1205
1206/* Internal API to look for a name through the MRO.
1207 This returns a borrowed reference, and doesn't set an exception! */
1208PyObject *
1209_PyType_Lookup(PyTypeObject *type, PyObject *name)
1210{
1211 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001212 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213
Guido van Rossum687ae002001-10-15 22:03:32 +00001214 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 mro = type->tp_mro;
1216 assert(PyTuple_Check(mro));
1217 n = PyTuple_GET_SIZE(mro);
1218 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001219 base = PyTuple_GET_ITEM(mro, i);
1220 if (PyClass_Check(base))
1221 dict = ((PyClassObject *)base)->cl_dict;
1222 else {
1223 assert(PyType_Check(base));
1224 dict = ((PyTypeObject *)base)->tp_dict;
1225 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226 assert(dict && PyDict_Check(dict));
1227 res = PyDict_GetItem(dict, name);
1228 if (res != NULL)
1229 return res;
1230 }
1231 return NULL;
1232}
1233
1234/* This is similar to PyObject_GenericGetAttr(),
1235 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1236static PyObject *
1237type_getattro(PyTypeObject *type, PyObject *name)
1238{
1239 PyTypeObject *metatype = type->ob_type;
1240 PyObject *descr, *res;
1241 descrgetfunc f;
1242
1243 /* Initialize this type (we'll assume the metatype is initialized) */
1244 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001245 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 return NULL;
1247 }
1248
1249 /* Get a descriptor from the metatype */
1250 descr = _PyType_Lookup(metatype, name);
1251 f = NULL;
1252 if (descr != NULL) {
1253 f = descr->ob_type->tp_descr_get;
1254 if (f != NULL && PyDescr_IsData(descr))
1255 return f(descr,
1256 (PyObject *)type, (PyObject *)metatype);
1257 }
1258
Guido van Rossum687ae002001-10-15 22:03:32 +00001259 /* Look in tp_dict of this type and its bases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 res = _PyType_Lookup(type, name);
1261 if (res != NULL) {
1262 f = res->ob_type->tp_descr_get;
1263 if (f != NULL)
1264 return f(res, (PyObject *)NULL, (PyObject *)type);
1265 Py_INCREF(res);
1266 return res;
1267 }
1268
1269 /* Use the descriptor from the metatype */
1270 if (f != NULL) {
1271 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1272 return res;
1273 }
1274 if (descr != NULL) {
1275 Py_INCREF(descr);
1276 return descr;
1277 }
1278
1279 /* Give up */
1280 PyErr_Format(PyExc_AttributeError,
1281 "type object '%.50s' has no attribute '%.400s'",
1282 type->tp_name, PyString_AS_STRING(name));
1283 return NULL;
1284}
1285
1286static int
1287type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1288{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001289 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1290 PyErr_Format(
1291 PyExc_TypeError,
1292 "can't set attributes of built-in/extension type '%s'",
1293 type->tp_name);
1294 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001295 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001296 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1297 return -1;
1298 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299}
1300
1301static void
1302type_dealloc(PyTypeObject *type)
1303{
1304 etype *et;
1305
1306 /* Assert this is a heap-allocated type object */
1307 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001308 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001309 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001310 et = (etype *)type;
1311 Py_XDECREF(type->tp_base);
1312 Py_XDECREF(type->tp_dict);
1313 Py_XDECREF(type->tp_bases);
1314 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001315 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001316 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317 Py_XDECREF(et->name);
1318 Py_XDECREF(et->slots);
1319 type->ob_type->tp_free((PyObject *)type);
1320}
1321
Guido van Rossum1c450732001-10-08 15:18:27 +00001322static PyObject *
1323type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1324{
1325 PyObject *list, *raw, *ref;
1326 int i, n;
1327
1328 list = PyList_New(0);
1329 if (list == NULL)
1330 return NULL;
1331 raw = type->tp_subclasses;
1332 if (raw == NULL)
1333 return list;
1334 assert(PyList_Check(raw));
1335 n = PyList_GET_SIZE(raw);
1336 for (i = 0; i < n; i++) {
1337 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001338 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001339 ref = PyWeakref_GET_OBJECT(ref);
1340 if (ref != Py_None) {
1341 if (PyList_Append(list, ref) < 0) {
1342 Py_DECREF(list);
1343 return NULL;
1344 }
1345 }
1346 }
1347 return list;
1348}
1349
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001351 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001353 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1354 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355 {0}
1356};
1357
1358static char type_doc[] =
1359"type(object) -> the object's type\n"
1360"type(name, bases, dict) -> a new type";
1361
Guido van Rossum048eb752001-10-02 21:24:57 +00001362static int
1363type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1364{
1365 etype *et;
1366 int err;
1367
1368 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1369 return 0;
1370
1371 et = (etype *)type;
1372
1373#define VISIT(SLOT) \
1374 if (SLOT) { \
1375 err = visit((PyObject *)(SLOT), arg); \
1376 if (err) \
1377 return err; \
1378 }
1379
1380 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001381 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001382 VISIT(type->tp_mro);
1383 VISIT(type->tp_bases);
1384 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001385 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001386 VISIT(et->slots);
1387
1388#undef VISIT
1389
1390 return 0;
1391}
1392
1393static int
1394type_clear(PyTypeObject *type)
1395{
1396 etype *et;
1397 PyObject *tmp;
1398
1399 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1400 return 0;
1401
1402 et = (etype *)type;
1403
1404#define CLEAR(SLOT) \
1405 if (SLOT) { \
1406 tmp = (PyObject *)(SLOT); \
1407 SLOT = NULL; \
1408 Py_DECREF(tmp); \
1409 }
1410
1411 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001412 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001413 CLEAR(type->tp_mro);
1414 CLEAR(type->tp_bases);
1415 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001416 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001417 CLEAR(et->slots);
1418
Tim Peters2f93e282001-10-04 05:27:00 +00001419 if (type->tp_doc != NULL) {
1420 PyObject_FREE(type->tp_doc);
1421 type->tp_doc = NULL;
1422 }
1423
Guido van Rossum048eb752001-10-02 21:24:57 +00001424#undef CLEAR
1425
1426 return 0;
1427}
1428
1429static int
1430type_is_gc(PyTypeObject *type)
1431{
1432 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1433}
1434
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001435PyTypeObject PyType_Type = {
1436 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437 0, /* ob_size */
1438 "type", /* tp_name */
1439 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001440 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441 (destructor)type_dealloc, /* tp_dealloc */
1442 0, /* tp_print */
1443 0, /* tp_getattr */
1444 0, /* tp_setattr */
1445 type_compare, /* tp_compare */
1446 (reprfunc)type_repr, /* tp_repr */
1447 0, /* tp_as_number */
1448 0, /* tp_as_sequence */
1449 0, /* tp_as_mapping */
1450 (hashfunc)_Py_HashPointer, /* tp_hash */
1451 (ternaryfunc)type_call, /* tp_call */
1452 0, /* tp_str */
1453 (getattrofunc)type_getattro, /* tp_getattro */
1454 (setattrofunc)type_setattro, /* tp_setattro */
1455 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001456 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1457 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001459 (traverseproc)type_traverse, /* tp_traverse */
1460 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001461 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001462 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 0, /* tp_iter */
1464 0, /* tp_iternext */
1465 type_methods, /* tp_methods */
1466 type_members, /* tp_members */
1467 type_getsets, /* tp_getset */
1468 0, /* tp_base */
1469 0, /* tp_dict */
1470 0, /* tp_descr_get */
1471 0, /* tp_descr_set */
1472 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1473 0, /* tp_init */
1474 0, /* tp_alloc */
1475 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001476 _PyObject_GC_Del, /* tp_free */
1477 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001478};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479
1480
1481/* The base type of all types (eventually)... except itself. */
1482
1483static int
1484object_init(PyObject *self, PyObject *args, PyObject *kwds)
1485{
1486 return 0;
1487}
1488
1489static void
1490object_dealloc(PyObject *self)
1491{
1492 self->ob_type->tp_free(self);
1493}
1494
Guido van Rossum8e248182001-08-12 05:17:56 +00001495static PyObject *
1496object_repr(PyObject *self)
1497{
Guido van Rossum76e69632001-08-16 18:52:43 +00001498 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001499 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001500
Guido van Rossum76e69632001-08-16 18:52:43 +00001501 type = self->ob_type;
1502 mod = type_module(type, NULL);
1503 if (mod == NULL)
1504 PyErr_Clear();
1505 else if (!PyString_Check(mod)) {
1506 Py_DECREF(mod);
1507 mod = NULL;
1508 }
1509 name = type_name(type, NULL);
1510 if (name == NULL)
1511 return NULL;
1512 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001513 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001514 PyString_AS_STRING(mod),
1515 PyString_AS_STRING(name),
1516 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001517 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001518 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001519 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001520 Py_XDECREF(mod);
1521 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001522 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001523}
1524
Guido van Rossumb8f63662001-08-15 23:57:02 +00001525static PyObject *
1526object_str(PyObject *self)
1527{
1528 unaryfunc f;
1529
1530 f = self->ob_type->tp_repr;
1531 if (f == NULL)
1532 f = object_repr;
1533 return f(self);
1534}
1535
Guido van Rossum8e248182001-08-12 05:17:56 +00001536static long
1537object_hash(PyObject *self)
1538{
1539 return _Py_HashPointer(self);
1540}
Guido van Rossum8e248182001-08-12 05:17:56 +00001541
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001542static PyObject *
1543object_get_class(PyObject *self, void *closure)
1544{
1545 Py_INCREF(self->ob_type);
1546 return (PyObject *)(self->ob_type);
1547}
1548
1549static int
1550equiv_structs(PyTypeObject *a, PyTypeObject *b)
1551{
1552 return a == b ||
1553 (a != NULL &&
1554 b != NULL &&
1555 a->tp_basicsize == b->tp_basicsize &&
1556 a->tp_itemsize == b->tp_itemsize &&
1557 a->tp_dictoffset == b->tp_dictoffset &&
1558 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1559 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1560 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1561}
1562
1563static int
1564same_slots_added(PyTypeObject *a, PyTypeObject *b)
1565{
1566 PyTypeObject *base = a->tp_base;
1567 int size;
1568
1569 if (base != b->tp_base)
1570 return 0;
1571 if (equiv_structs(a, base) && equiv_structs(b, base))
1572 return 1;
1573 size = base->tp_basicsize;
1574 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1575 size += sizeof(PyObject *);
1576 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1577 size += sizeof(PyObject *);
1578 return size == a->tp_basicsize && size == b->tp_basicsize;
1579}
1580
1581static int
1582object_set_class(PyObject *self, PyObject *value, void *closure)
1583{
1584 PyTypeObject *old = self->ob_type;
1585 PyTypeObject *new, *newbase, *oldbase;
1586
1587 if (!PyType_Check(value)) {
1588 PyErr_Format(PyExc_TypeError,
1589 "__class__ must be set to new-style class, not '%s' object",
1590 value->ob_type->tp_name);
1591 return -1;
1592 }
1593 new = (PyTypeObject *)value;
1594 newbase = new;
1595 oldbase = old;
1596 while (equiv_structs(newbase, newbase->tp_base))
1597 newbase = newbase->tp_base;
1598 while (equiv_structs(oldbase, oldbase->tp_base))
1599 oldbase = oldbase->tp_base;
1600 if (newbase != oldbase &&
1601 (newbase->tp_base != oldbase->tp_base ||
1602 !same_slots_added(newbase, oldbase))) {
1603 PyErr_Format(PyExc_TypeError,
1604 "__class__ assignment: "
1605 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001606 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001607 old->tp_name);
1608 return -1;
1609 }
1610 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1611 Py_INCREF(new);
1612 }
1613 self->ob_type = new;
1614 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1615 Py_DECREF(old);
1616 }
1617 return 0;
1618}
1619
1620static PyGetSetDef object_getsets[] = {
1621 {"__class__", object_get_class, object_set_class,
1622 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623 {0}
1624};
1625
Guido van Rossum3926a632001-09-25 16:25:58 +00001626static PyObject *
1627object_reduce(PyObject *self, PyObject *args)
1628{
1629 /* Call copy_reg._reduce(self) */
1630 static PyObject *copy_reg_str;
1631 PyObject *copy_reg, *res;
1632
1633 if (!copy_reg_str) {
1634 copy_reg_str = PyString_InternFromString("copy_reg");
1635 if (copy_reg_str == NULL)
1636 return NULL;
1637 }
1638 copy_reg = PyImport_Import(copy_reg_str);
1639 if (!copy_reg)
1640 return NULL;
1641 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1642 Py_DECREF(copy_reg);
1643 return res;
1644}
1645
1646static PyMethodDef object_methods[] = {
1647 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1648 {0}
1649};
1650
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651PyTypeObject PyBaseObject_Type = {
1652 PyObject_HEAD_INIT(&PyType_Type)
1653 0, /* ob_size */
1654 "object", /* tp_name */
1655 sizeof(PyObject), /* tp_basicsize */
1656 0, /* tp_itemsize */
1657 (destructor)object_dealloc, /* tp_dealloc */
1658 0, /* tp_print */
1659 0, /* tp_getattr */
1660 0, /* tp_setattr */
1661 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001662 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 0, /* tp_as_number */
1664 0, /* tp_as_sequence */
1665 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001666 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001668 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001670 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671 0, /* tp_as_buffer */
1672 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1673 "The most base type", /* tp_doc */
1674 0, /* tp_traverse */
1675 0, /* tp_clear */
1676 0, /* tp_richcompare */
1677 0, /* tp_weaklistoffset */
1678 0, /* tp_iter */
1679 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001680 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001681 0, /* tp_members */
1682 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683 0, /* tp_base */
1684 0, /* tp_dict */
1685 0, /* tp_descr_get */
1686 0, /* tp_descr_set */
1687 0, /* tp_dictoffset */
1688 object_init, /* tp_init */
1689 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001690 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001691 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001692};
1693
1694
1695/* Initialize the __dict__ in a type object */
1696
1697static int
1698add_methods(PyTypeObject *type, PyMethodDef *meth)
1699{
Guido van Rossum687ae002001-10-15 22:03:32 +00001700 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701
1702 for (; meth->ml_name != NULL; meth++) {
1703 PyObject *descr;
1704 if (PyDict_GetItemString(dict, meth->ml_name))
1705 continue;
1706 descr = PyDescr_NewMethod(type, meth);
1707 if (descr == NULL)
1708 return -1;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001709 if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710 return -1;
1711 Py_DECREF(descr);
1712 }
1713 return 0;
1714}
1715
1716static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001717add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718{
Guido van Rossum687ae002001-10-15 22:03:32 +00001719 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720
1721 for (; memb->name != NULL; memb++) {
1722 PyObject *descr;
1723 if (PyDict_GetItemString(dict, memb->name))
1724 continue;
1725 descr = PyDescr_NewMember(type, memb);
1726 if (descr == NULL)
1727 return -1;
1728 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1729 return -1;
1730 Py_DECREF(descr);
1731 }
1732 return 0;
1733}
1734
1735static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001736add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737{
Guido van Rossum687ae002001-10-15 22:03:32 +00001738 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739
1740 for (; gsp->name != NULL; gsp++) {
1741 PyObject *descr;
1742 if (PyDict_GetItemString(dict, gsp->name))
1743 continue;
1744 descr = PyDescr_NewGetSet(type, gsp);
1745
1746 if (descr == NULL)
1747 return -1;
1748 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1749 return -1;
1750 Py_DECREF(descr);
1751 }
1752 return 0;
1753}
1754
Guido van Rossum13d52f02001-08-10 21:24:08 +00001755static void
1756inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001757{
1758 int oldsize, newsize;
1759
Guido van Rossum13d52f02001-08-10 21:24:08 +00001760 /* Special flag magic */
1761 if (!type->tp_as_buffer && base->tp_as_buffer) {
1762 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1763 type->tp_flags |=
1764 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1765 }
1766 if (!type->tp_as_sequence && base->tp_as_sequence) {
1767 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1768 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1769 }
1770 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1771 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1772 if ((!type->tp_as_number && base->tp_as_number) ||
1773 (!type->tp_as_sequence && base->tp_as_sequence)) {
1774 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1775 if (!type->tp_as_number && !type->tp_as_sequence) {
1776 type->tp_flags |= base->tp_flags &
1777 Py_TPFLAGS_HAVE_INPLACEOPS;
1778 }
1779 }
1780 /* Wow */
1781 }
1782 if (!type->tp_as_number && base->tp_as_number) {
1783 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1784 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1785 }
1786
1787 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001788 oldsize = base->tp_basicsize;
1789 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1790 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1791 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001792 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1793 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001794 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001795 if (type->tp_traverse == NULL)
1796 type->tp_traverse = base->tp_traverse;
1797 if (type->tp_clear == NULL)
1798 type->tp_clear = base->tp_clear;
1799 }
1800 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001801 /* The condition below could use some explanation.
1802 It appears that tp_new is not inherited for static types
1803 whose base class is 'object'; this seems to be a precaution
1804 so that old extension types don't suddenly become
1805 callable (object.__new__ wouldn't insure the invariants
1806 that the extension type's own factory function ensures).
1807 Heap types, of course, are under our control, so they do
1808 inherit tp_new; static extension types that specify some
1809 other built-in type as the default are considered
1810 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001811 if (base != &PyBaseObject_Type ||
1812 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1813 if (type->tp_new == NULL)
1814 type->tp_new = base->tp_new;
1815 }
1816 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001817 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001818
1819 /* Copy other non-function slots */
1820
1821#undef COPYVAL
1822#define COPYVAL(SLOT) \
1823 if (type->SLOT == 0) type->SLOT = base->SLOT
1824
1825 COPYVAL(tp_itemsize);
1826 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1827 COPYVAL(tp_weaklistoffset);
1828 }
1829 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1830 COPYVAL(tp_dictoffset);
1831 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001832}
1833
1834static void
1835inherit_slots(PyTypeObject *type, PyTypeObject *base)
1836{
1837 PyTypeObject *basebase;
1838
1839#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840#undef COPYSLOT
1841#undef COPYNUM
1842#undef COPYSEQ
1843#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001844#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001845
1846#define SLOTDEFINED(SLOT) \
1847 (base->SLOT != 0 && \
1848 (basebase == NULL || base->SLOT != basebase->SLOT))
1849
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001851 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852
1853#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1854#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1855#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001856#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857
Guido van Rossum13d52f02001-08-10 21:24:08 +00001858 /* This won't inherit indirect slots (from tp_as_number etc.)
1859 if type doesn't provide the space. */
1860
1861 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1862 basebase = base->tp_base;
1863 if (basebase->tp_as_number == NULL)
1864 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 COPYNUM(nb_add);
1866 COPYNUM(nb_subtract);
1867 COPYNUM(nb_multiply);
1868 COPYNUM(nb_divide);
1869 COPYNUM(nb_remainder);
1870 COPYNUM(nb_divmod);
1871 COPYNUM(nb_power);
1872 COPYNUM(nb_negative);
1873 COPYNUM(nb_positive);
1874 COPYNUM(nb_absolute);
1875 COPYNUM(nb_nonzero);
1876 COPYNUM(nb_invert);
1877 COPYNUM(nb_lshift);
1878 COPYNUM(nb_rshift);
1879 COPYNUM(nb_and);
1880 COPYNUM(nb_xor);
1881 COPYNUM(nb_or);
1882 COPYNUM(nb_coerce);
1883 COPYNUM(nb_int);
1884 COPYNUM(nb_long);
1885 COPYNUM(nb_float);
1886 COPYNUM(nb_oct);
1887 COPYNUM(nb_hex);
1888 COPYNUM(nb_inplace_add);
1889 COPYNUM(nb_inplace_subtract);
1890 COPYNUM(nb_inplace_multiply);
1891 COPYNUM(nb_inplace_divide);
1892 COPYNUM(nb_inplace_remainder);
1893 COPYNUM(nb_inplace_power);
1894 COPYNUM(nb_inplace_lshift);
1895 COPYNUM(nb_inplace_rshift);
1896 COPYNUM(nb_inplace_and);
1897 COPYNUM(nb_inplace_xor);
1898 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001899 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1900 COPYNUM(nb_true_divide);
1901 COPYNUM(nb_floor_divide);
1902 COPYNUM(nb_inplace_true_divide);
1903 COPYNUM(nb_inplace_floor_divide);
1904 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905 }
1906
Guido van Rossum13d52f02001-08-10 21:24:08 +00001907 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1908 basebase = base->tp_base;
1909 if (basebase->tp_as_sequence == NULL)
1910 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001911 COPYSEQ(sq_length);
1912 COPYSEQ(sq_concat);
1913 COPYSEQ(sq_repeat);
1914 COPYSEQ(sq_item);
1915 COPYSEQ(sq_slice);
1916 COPYSEQ(sq_ass_item);
1917 COPYSEQ(sq_ass_slice);
1918 COPYSEQ(sq_contains);
1919 COPYSEQ(sq_inplace_concat);
1920 COPYSEQ(sq_inplace_repeat);
1921 }
1922
Guido van Rossum13d52f02001-08-10 21:24:08 +00001923 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1924 basebase = base->tp_base;
1925 if (basebase->tp_as_mapping == NULL)
1926 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927 COPYMAP(mp_length);
1928 COPYMAP(mp_subscript);
1929 COPYMAP(mp_ass_subscript);
1930 }
1931
Tim Petersfc57ccb2001-10-12 02:38:24 +00001932 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1933 basebase = base->tp_base;
1934 if (basebase->tp_as_buffer == NULL)
1935 basebase = NULL;
1936 COPYBUF(bf_getreadbuffer);
1937 COPYBUF(bf_getwritebuffer);
1938 COPYBUF(bf_getsegcount);
1939 COPYBUF(bf_getcharbuffer);
1940 }
1941
Guido van Rossum13d52f02001-08-10 21:24:08 +00001942 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001943
Tim Peters6d6c1a32001-08-02 04:15:00 +00001944 COPYSLOT(tp_dealloc);
1945 COPYSLOT(tp_print);
1946 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1947 type->tp_getattr = base->tp_getattr;
1948 type->tp_getattro = base->tp_getattro;
1949 }
1950 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1951 type->tp_setattr = base->tp_setattr;
1952 type->tp_setattro = base->tp_setattro;
1953 }
1954 /* tp_compare see tp_richcompare */
1955 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001956 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001957 COPYSLOT(tp_call);
1958 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001960 if (type->tp_compare == NULL &&
1961 type->tp_richcompare == NULL &&
1962 type->tp_hash == NULL)
1963 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964 type->tp_compare = base->tp_compare;
1965 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001966 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001967 }
1968 }
1969 else {
1970 COPYSLOT(tp_compare);
1971 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1973 COPYSLOT(tp_iter);
1974 COPYSLOT(tp_iternext);
1975 }
1976 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1977 COPYSLOT(tp_descr_get);
1978 COPYSLOT(tp_descr_set);
1979 COPYSLOT(tp_dictoffset);
1980 COPYSLOT(tp_init);
1981 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001982 COPYSLOT(tp_free);
1983 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984}
1985
Guido van Rossum13d52f02001-08-10 21:24:08 +00001986staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001987staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001988
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001990PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001992 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993 PyTypeObject *base;
1994 int i, n;
1995
Guido van Rossumd614f972001-08-10 17:39:49 +00001996 if (type->tp_flags & Py_TPFLAGS_READY) {
1997 assert(type->tp_dict != NULL);
1998 return 0;
1999 }
2000 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002001
2002 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003
Guido van Rossumf884b742001-12-17 17:14:22 +00002004 /* Initialize ob_type if NULL. This means extensions that want to be
2005 compilable separately on Windows can call PyType_Ready() instead of
2006 initializing the ob_type field of their type objects. */
2007 if (type->ob_type == NULL)
2008 type->ob_type = &PyType_Type;
2009
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2011 base = type->tp_base;
2012 if (base == NULL && type != &PyBaseObject_Type)
2013 base = type->tp_base = &PyBaseObject_Type;
2014
2015 /* Initialize tp_bases */
2016 bases = type->tp_bases;
2017 if (bases == NULL) {
2018 if (base == NULL)
2019 bases = PyTuple_New(0);
2020 else
2021 bases = Py_BuildValue("(O)", base);
2022 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002023 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002024 type->tp_bases = bases;
2025 }
2026
2027 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002028 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002029 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002030 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 }
2032
Guido van Rossum687ae002001-10-15 22:03:32 +00002033 /* Initialize tp_dict */
2034 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 if (dict == NULL) {
2036 dict = PyDict_New();
2037 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002038 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002039 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 }
2041
Guido van Rossum687ae002001-10-15 22:03:32 +00002042 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002044 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 if (type->tp_methods != NULL) {
2046 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002047 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048 }
2049 if (type->tp_members != NULL) {
2050 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002051 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052 }
2053 if (type->tp_getset != NULL) {
2054 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002055 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 }
2057
Tim Peters6d6c1a32001-08-02 04:15:00 +00002058 /* Calculate method resolution order */
2059 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002060 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061 }
2062
Guido van Rossum13d52f02001-08-10 21:24:08 +00002063 /* Inherit special flags from dominant base */
2064 if (type->tp_base != NULL)
2065 inherit_special(type, type->tp_base);
2066
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002068 bases = type->tp_mro;
2069 assert(bases != NULL);
2070 assert(PyTuple_Check(bases));
2071 n = PyTuple_GET_SIZE(bases);
2072 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002073 PyObject *b = PyTuple_GET_ITEM(bases, i);
2074 if (PyType_Check(b))
2075 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002076 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002078 /* if the type dictionary doesn't contain a __doc__, set it from
2079 the tp_doc slot.
2080 */
2081 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2082 if (type->tp_doc != NULL) {
2083 PyObject *doc = PyString_FromString(type->tp_doc);
2084 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2085 Py_DECREF(doc);
2086 } else {
2087 PyDict_SetItemString(type->tp_dict, "__doc__", Py_None);
2088 }
2089 }
2090
Guido van Rossum13d52f02001-08-10 21:24:08 +00002091 /* Some more special stuff */
2092 base = type->tp_base;
2093 if (base != NULL) {
2094 if (type->tp_as_number == NULL)
2095 type->tp_as_number = base->tp_as_number;
2096 if (type->tp_as_sequence == NULL)
2097 type->tp_as_sequence = base->tp_as_sequence;
2098 if (type->tp_as_mapping == NULL)
2099 type->tp_as_mapping = base->tp_as_mapping;
2100 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101
Guido van Rossum1c450732001-10-08 15:18:27 +00002102 /* Link into each base class's list of subclasses */
2103 bases = type->tp_bases;
2104 n = PyTuple_GET_SIZE(bases);
2105 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002106 PyObject *b = PyTuple_GET_ITEM(bases, i);
2107 if (PyType_Check(b) &&
2108 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002109 goto error;
2110 }
2111
Guido van Rossum13d52f02001-08-10 21:24:08 +00002112 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002113 assert(type->tp_dict != NULL);
2114 type->tp_flags =
2115 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002117
2118 error:
2119 type->tp_flags &= ~Py_TPFLAGS_READYING;
2120 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121}
2122
Guido van Rossum1c450732001-10-08 15:18:27 +00002123static int
2124add_subclass(PyTypeObject *base, PyTypeObject *type)
2125{
2126 int i;
2127 PyObject *list, *ref, *new;
2128
2129 list = base->tp_subclasses;
2130 if (list == NULL) {
2131 base->tp_subclasses = list = PyList_New(0);
2132 if (list == NULL)
2133 return -1;
2134 }
2135 assert(PyList_Check(list));
2136 new = PyWeakref_NewRef((PyObject *)type, NULL);
2137 i = PyList_GET_SIZE(list);
2138 while (--i >= 0) {
2139 ref = PyList_GET_ITEM(list, i);
2140 assert(PyWeakref_CheckRef(ref));
2141 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2142 return PyList_SetItem(list, i, new);
2143 }
2144 i = PyList_Append(list, new);
2145 Py_DECREF(new);
2146 return i;
2147}
2148
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149
2150/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2151
2152/* There's a wrapper *function* for each distinct function typedef used
2153 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2154 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2155 Most tables have only one entry; the tables for binary operators have two
2156 entries, one regular and one with reversed arguments. */
2157
2158static PyObject *
2159wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2160{
2161 inquiry func = (inquiry)wrapped;
2162 int res;
2163
2164 if (!PyArg_ParseTuple(args, ""))
2165 return NULL;
2166 res = (*func)(self);
2167 if (res == -1 && PyErr_Occurred())
2168 return NULL;
2169 return PyInt_FromLong((long)res);
2170}
2171
Tim Peters6d6c1a32001-08-02 04:15:00 +00002172static PyObject *
2173wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2174{
2175 binaryfunc func = (binaryfunc)wrapped;
2176 PyObject *other;
2177
2178 if (!PyArg_ParseTuple(args, "O", &other))
2179 return NULL;
2180 return (*func)(self, other);
2181}
2182
2183static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002184wrap_binaryfunc_l(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;
2191 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 }
2196 return (*func)(self, other);
2197}
2198
2199static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002200wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2201{
2202 binaryfunc func = (binaryfunc)wrapped;
2203 PyObject *other;
2204
2205 if (!PyArg_ParseTuple(args, "O", &other))
2206 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002207 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002208 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002209 Py_INCREF(Py_NotImplemented);
2210 return Py_NotImplemented;
2211 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212 return (*func)(other, self);
2213}
2214
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002215static PyObject *
2216wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2217{
2218 coercion func = (coercion)wrapped;
2219 PyObject *other, *res;
2220 int ok;
2221
2222 if (!PyArg_ParseTuple(args, "O", &other))
2223 return NULL;
2224 ok = func(&self, &other);
2225 if (ok < 0)
2226 return NULL;
2227 if (ok > 0) {
2228 Py_INCREF(Py_NotImplemented);
2229 return Py_NotImplemented;
2230 }
2231 res = PyTuple_New(2);
2232 if (res == NULL) {
2233 Py_DECREF(self);
2234 Py_DECREF(other);
2235 return NULL;
2236 }
2237 PyTuple_SET_ITEM(res, 0, self);
2238 PyTuple_SET_ITEM(res, 1, other);
2239 return res;
2240}
2241
Tim Peters6d6c1a32001-08-02 04:15:00 +00002242static PyObject *
2243wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2244{
2245 ternaryfunc func = (ternaryfunc)wrapped;
2246 PyObject *other;
2247 PyObject *third = Py_None;
2248
2249 /* Note: This wrapper only works for __pow__() */
2250
2251 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2252 return NULL;
2253 return (*func)(self, other, third);
2254}
2255
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002256static PyObject *
2257wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2258{
2259 ternaryfunc func = (ternaryfunc)wrapped;
2260 PyObject *other;
2261 PyObject *third = Py_None;
2262
2263 /* Note: This wrapper only works for __pow__() */
2264
2265 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2266 return NULL;
2267 return (*func)(other, self, third);
2268}
2269
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270static PyObject *
2271wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2272{
2273 unaryfunc func = (unaryfunc)wrapped;
2274
2275 if (!PyArg_ParseTuple(args, ""))
2276 return NULL;
2277 return (*func)(self);
2278}
2279
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280static PyObject *
2281wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2282{
2283 intargfunc func = (intargfunc)wrapped;
2284 int i;
2285
2286 if (!PyArg_ParseTuple(args, "i", &i))
2287 return NULL;
2288 return (*func)(self, i);
2289}
2290
Guido van Rossum5d815f32001-08-17 21:57:47 +00002291static int
2292getindex(PyObject *self, PyObject *arg)
2293{
2294 int i;
2295
2296 i = PyInt_AsLong(arg);
2297 if (i == -1 && PyErr_Occurred())
2298 return -1;
2299 if (i < 0) {
2300 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2301 if (sq && sq->sq_length) {
2302 int n = (*sq->sq_length)(self);
2303 if (n < 0)
2304 return -1;
2305 i += n;
2306 }
2307 }
2308 return i;
2309}
2310
2311static PyObject *
2312wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2313{
2314 intargfunc func = (intargfunc)wrapped;
2315 PyObject *arg;
2316 int i;
2317
Guido van Rossumf4593e02001-10-03 12:09:30 +00002318 if (PyTuple_GET_SIZE(args) == 1) {
2319 arg = PyTuple_GET_ITEM(args, 0);
2320 i = getindex(self, arg);
2321 if (i == -1 && PyErr_Occurred())
2322 return NULL;
2323 return (*func)(self, i);
2324 }
2325 PyArg_ParseTuple(args, "O", &arg);
2326 assert(PyErr_Occurred());
2327 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002328}
2329
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330static PyObject *
2331wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2332{
2333 intintargfunc func = (intintargfunc)wrapped;
2334 int i, j;
2335
2336 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2337 return NULL;
2338 return (*func)(self, i, j);
2339}
2340
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002342wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343{
2344 intobjargproc func = (intobjargproc)wrapped;
2345 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002346 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347
Guido van Rossum5d815f32001-08-17 21:57:47 +00002348 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2349 return NULL;
2350 i = getindex(self, arg);
2351 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352 return NULL;
2353 res = (*func)(self, i, value);
2354 if (res == -1 && PyErr_Occurred())
2355 return NULL;
2356 Py_INCREF(Py_None);
2357 return Py_None;
2358}
2359
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002360static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002361wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002362{
2363 intobjargproc func = (intobjargproc)wrapped;
2364 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002365 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002366
Guido van Rossum5d815f32001-08-17 21:57:47 +00002367 if (!PyArg_ParseTuple(args, "O", &arg))
2368 return NULL;
2369 i = getindex(self, arg);
2370 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002371 return NULL;
2372 res = (*func)(self, i, NULL);
2373 if (res == -1 && PyErr_Occurred())
2374 return NULL;
2375 Py_INCREF(Py_None);
2376 return Py_None;
2377}
2378
Tim Peters6d6c1a32001-08-02 04:15:00 +00002379static PyObject *
2380wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2381{
2382 intintobjargproc func = (intintobjargproc)wrapped;
2383 int i, j, res;
2384 PyObject *value;
2385
2386 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2387 return NULL;
2388 res = (*func)(self, i, j, value);
2389 if (res == -1 && PyErr_Occurred())
2390 return NULL;
2391 Py_INCREF(Py_None);
2392 return Py_None;
2393}
2394
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002395static PyObject *
2396wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2397{
2398 intintobjargproc func = (intintobjargproc)wrapped;
2399 int i, j, res;
2400
2401 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2402 return NULL;
2403 res = (*func)(self, i, j, NULL);
2404 if (res == -1 && PyErr_Occurred())
2405 return NULL;
2406 Py_INCREF(Py_None);
2407 return Py_None;
2408}
2409
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410/* XXX objobjproc is a misnomer; should be objargpred */
2411static PyObject *
2412wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2413{
2414 objobjproc func = (objobjproc)wrapped;
2415 int res;
2416 PyObject *value;
2417
2418 if (!PyArg_ParseTuple(args, "O", &value))
2419 return NULL;
2420 res = (*func)(self, value);
2421 if (res == -1 && PyErr_Occurred())
2422 return NULL;
2423 return PyInt_FromLong((long)res);
2424}
2425
Tim Peters6d6c1a32001-08-02 04:15:00 +00002426static PyObject *
2427wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2428{
2429 objobjargproc func = (objobjargproc)wrapped;
2430 int res;
2431 PyObject *key, *value;
2432
2433 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2434 return NULL;
2435 res = (*func)(self, key, value);
2436 if (res == -1 && PyErr_Occurred())
2437 return NULL;
2438 Py_INCREF(Py_None);
2439 return Py_None;
2440}
2441
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002442static PyObject *
2443wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2444{
2445 objobjargproc func = (objobjargproc)wrapped;
2446 int res;
2447 PyObject *key;
2448
2449 if (!PyArg_ParseTuple(args, "O", &key))
2450 return NULL;
2451 res = (*func)(self, key, NULL);
2452 if (res == -1 && PyErr_Occurred())
2453 return NULL;
2454 Py_INCREF(Py_None);
2455 return Py_None;
2456}
2457
Tim Peters6d6c1a32001-08-02 04:15:00 +00002458static PyObject *
2459wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2460{
2461 cmpfunc func = (cmpfunc)wrapped;
2462 int res;
2463 PyObject *other;
2464
2465 if (!PyArg_ParseTuple(args, "O", &other))
2466 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002467 if (other->ob_type->tp_compare != func &&
2468 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002469 PyErr_Format(
2470 PyExc_TypeError,
2471 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2472 self->ob_type->tp_name,
2473 self->ob_type->tp_name,
2474 other->ob_type->tp_name);
2475 return NULL;
2476 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477 res = (*func)(self, other);
2478 if (PyErr_Occurred())
2479 return NULL;
2480 return PyInt_FromLong((long)res);
2481}
2482
Tim Peters6d6c1a32001-08-02 04:15:00 +00002483static PyObject *
2484wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2485{
2486 setattrofunc func = (setattrofunc)wrapped;
2487 int res;
2488 PyObject *name, *value;
2489
2490 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2491 return NULL;
2492 res = (*func)(self, name, value);
2493 if (res < 0)
2494 return NULL;
2495 Py_INCREF(Py_None);
2496 return Py_None;
2497}
2498
2499static PyObject *
2500wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2501{
2502 setattrofunc func = (setattrofunc)wrapped;
2503 int res;
2504 PyObject *name;
2505
2506 if (!PyArg_ParseTuple(args, "O", &name))
2507 return NULL;
2508 res = (*func)(self, name, NULL);
2509 if (res < 0)
2510 return NULL;
2511 Py_INCREF(Py_None);
2512 return Py_None;
2513}
2514
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515static PyObject *
2516wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2517{
2518 hashfunc func = (hashfunc)wrapped;
2519 long res;
2520
2521 if (!PyArg_ParseTuple(args, ""))
2522 return NULL;
2523 res = (*func)(self);
2524 if (res == -1 && PyErr_Occurred())
2525 return NULL;
2526 return PyInt_FromLong(res);
2527}
2528
Tim Peters6d6c1a32001-08-02 04:15:00 +00002529static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002530wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531{
2532 ternaryfunc func = (ternaryfunc)wrapped;
2533
Guido van Rossumc8e56452001-10-22 00:43:43 +00002534 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002535}
2536
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537static PyObject *
2538wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2539{
2540 richcmpfunc func = (richcmpfunc)wrapped;
2541 PyObject *other;
2542
2543 if (!PyArg_ParseTuple(args, "O", &other))
2544 return NULL;
2545 return (*func)(self, other, op);
2546}
2547
2548#undef RICHCMP_WRAPPER
2549#define RICHCMP_WRAPPER(NAME, OP) \
2550static PyObject * \
2551richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2552{ \
2553 return wrap_richcmpfunc(self, args, wrapped, OP); \
2554}
2555
Jack Jansen8e938b42001-08-08 15:29:49 +00002556RICHCMP_WRAPPER(lt, Py_LT)
2557RICHCMP_WRAPPER(le, Py_LE)
2558RICHCMP_WRAPPER(eq, Py_EQ)
2559RICHCMP_WRAPPER(ne, Py_NE)
2560RICHCMP_WRAPPER(gt, Py_GT)
2561RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002562
Tim Peters6d6c1a32001-08-02 04:15:00 +00002563static PyObject *
2564wrap_next(PyObject *self, PyObject *args, void *wrapped)
2565{
2566 unaryfunc func = (unaryfunc)wrapped;
2567 PyObject *res;
2568
2569 if (!PyArg_ParseTuple(args, ""))
2570 return NULL;
2571 res = (*func)(self);
2572 if (res == NULL && !PyErr_Occurred())
2573 PyErr_SetNone(PyExc_StopIteration);
2574 return res;
2575}
2576
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577static PyObject *
2578wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2579{
2580 descrgetfunc func = (descrgetfunc)wrapped;
2581 PyObject *obj;
2582 PyObject *type = NULL;
2583
2584 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2585 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586 return (*func)(self, obj, type);
2587}
2588
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002590wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591{
2592 descrsetfunc func = (descrsetfunc)wrapped;
2593 PyObject *obj, *value;
2594 int ret;
2595
2596 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2597 return NULL;
2598 ret = (*func)(self, obj, value);
2599 if (ret < 0)
2600 return NULL;
2601 Py_INCREF(Py_None);
2602 return Py_None;
2603}
2604
Tim Peters6d6c1a32001-08-02 04:15:00 +00002605static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002606wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607{
2608 initproc func = (initproc)wrapped;
2609
Guido van Rossumc8e56452001-10-22 00:43:43 +00002610 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002611 return NULL;
2612 Py_INCREF(Py_None);
2613 return Py_None;
2614}
2615
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002617tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618{
Barry Warsaw60f01882001-08-22 19:24:42 +00002619 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002620 PyObject *arg0, *res;
2621
2622 if (self == NULL || !PyType_Check(self))
2623 Py_FatalError("__new__() called with non-type 'self'");
2624 type = (PyTypeObject *)self;
2625 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002626 PyErr_Format(PyExc_TypeError,
2627 "%s.__new__(): not enough arguments",
2628 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002629 return NULL;
2630 }
2631 arg0 = PyTuple_GET_ITEM(args, 0);
2632 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002633 PyErr_Format(PyExc_TypeError,
2634 "%s.__new__(X): X is not a type object (%s)",
2635 type->tp_name,
2636 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002637 return NULL;
2638 }
2639 subtype = (PyTypeObject *)arg0;
2640 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002641 PyErr_Format(PyExc_TypeError,
2642 "%s.__new__(%s): %s is not a subtype of %s",
2643 type->tp_name,
2644 subtype->tp_name,
2645 subtype->tp_name,
2646 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002647 return NULL;
2648 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002649
2650 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002651 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002652 most derived base that's not a heap type is this type. */
2653 staticbase = subtype;
2654 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2655 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002656 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002657 PyErr_Format(PyExc_TypeError,
2658 "%s.__new__(%s) is not safe, use %s.__new__()",
2659 type->tp_name,
2660 subtype->tp_name,
2661 staticbase == NULL ? "?" : staticbase->tp_name);
2662 return NULL;
2663 }
2664
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002665 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2666 if (args == NULL)
2667 return NULL;
2668 res = type->tp_new(subtype, args, kwds);
2669 Py_DECREF(args);
2670 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671}
2672
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002673static struct PyMethodDef tp_new_methoddef[] = {
2674 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2675 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676 {0}
2677};
2678
2679static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002680add_tp_new_wrapper(PyTypeObject *type)
2681{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002682 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002683
Guido van Rossum687ae002001-10-15 22:03:32 +00002684 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002685 return 0;
2686 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002687 if (func == NULL)
2688 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002689 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002690}
2691
Guido van Rossumf040ede2001-08-07 16:40:56 +00002692/* Slot wrappers that call the corresponding __foo__ slot. See comments
2693 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694
Guido van Rossumdc91b992001-08-08 22:26:22 +00002695#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002697FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002699 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002700 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002701}
2702
Guido van Rossumdc91b992001-08-08 22:26:22 +00002703#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002704static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002705FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002707 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002708 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709}
2710
Guido van Rossumdc91b992001-08-08 22:26:22 +00002711
2712#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002713static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002714FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002715{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002716 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002717 int do_other = self->ob_type != other->ob_type && \
2718 other->ob_type->tp_as_number != NULL && \
2719 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002720 if (self->ob_type->tp_as_number != NULL && \
2721 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2722 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002723 if (do_other && \
2724 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2725 r = call_maybe( \
2726 other, ROPSTR, &rcache_str, "(O)", self); \
2727 if (r != Py_NotImplemented) \
2728 return r; \
2729 Py_DECREF(r); \
2730 do_other = 0; \
2731 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002732 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002733 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002734 if (r != Py_NotImplemented || \
2735 other->ob_type == self->ob_type) \
2736 return r; \
2737 Py_DECREF(r); \
2738 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002739 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002740 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002741 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002742 } \
2743 Py_INCREF(Py_NotImplemented); \
2744 return Py_NotImplemented; \
2745}
2746
2747#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2748 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2749
2750#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2751static PyObject * \
2752FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2753{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002754 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002755 return call_method(self, OPSTR, &cache_str, \
2756 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757}
2758
2759static int
2760slot_sq_length(PyObject *self)
2761{
Guido van Rossum2730b132001-08-28 18:22:14 +00002762 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002763 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002764 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765
2766 if (res == NULL)
2767 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002768 len = (int)PyInt_AsLong(res);
2769 Py_DECREF(res);
2770 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771}
2772
Guido van Rossumdc91b992001-08-08 22:26:22 +00002773SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2774SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002775
2776/* Super-optimized version of slot_sq_item.
2777 Other slots could do the same... */
2778static PyObject *
2779slot_sq_item(PyObject *self, int i)
2780{
2781 static PyObject *getitem_str;
2782 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2783 descrgetfunc f;
2784
2785 if (getitem_str == NULL) {
2786 getitem_str = PyString_InternFromString("__getitem__");
2787 if (getitem_str == NULL)
2788 return NULL;
2789 }
2790 func = _PyType_Lookup(self->ob_type, getitem_str);
2791 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002792 if ((f = func->ob_type->tp_descr_get) == NULL)
2793 Py_INCREF(func);
2794 else
2795 func = f(func, self, (PyObject *)(self->ob_type));
2796 ival = PyInt_FromLong(i);
2797 if (ival != NULL) {
2798 args = PyTuple_New(1);
2799 if (args != NULL) {
2800 PyTuple_SET_ITEM(args, 0, ival);
2801 retval = PyObject_Call(func, args, NULL);
2802 Py_XDECREF(args);
2803 Py_XDECREF(func);
2804 return retval;
2805 }
2806 }
2807 }
2808 else {
2809 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2810 }
2811 Py_XDECREF(args);
2812 Py_XDECREF(ival);
2813 Py_XDECREF(func);
2814 return NULL;
2815}
2816
Guido van Rossumdc91b992001-08-08 22:26:22 +00002817SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002818
2819static int
2820slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2821{
2822 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002823 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824
2825 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002826 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002827 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002828 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002829 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002830 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002831 if (res == NULL)
2832 return -1;
2833 Py_DECREF(res);
2834 return 0;
2835}
2836
2837static int
2838slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2839{
2840 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002841 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002842
2843 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002844 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002845 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002846 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002847 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002848 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849 if (res == NULL)
2850 return -1;
2851 Py_DECREF(res);
2852 return 0;
2853}
2854
2855static int
2856slot_sq_contains(PyObject *self, PyObject *value)
2857{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002858 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002859 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002860
Guido van Rossum55f20992001-10-01 17:18:22 +00002861 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002862
2863 if (func != NULL) {
2864 args = Py_BuildValue("(O)", value);
2865 if (args == NULL)
2866 res = NULL;
2867 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002868 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002869 Py_DECREF(args);
2870 }
2871 Py_DECREF(func);
2872 if (res == NULL)
2873 return -1;
2874 return PyObject_IsTrue(res);
2875 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002876 else if (PyErr_Occurred())
2877 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002878 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002879 return _PySequence_IterSearch(self, value,
2880 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002881 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002882}
2883
Guido van Rossumdc91b992001-08-08 22:26:22 +00002884SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2885SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002886
2887#define slot_mp_length slot_sq_length
2888
Guido van Rossumdc91b992001-08-08 22:26:22 +00002889SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890
2891static int
2892slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2893{
2894 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002895 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002896
2897 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002898 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002899 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002901 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002902 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903 if (res == NULL)
2904 return -1;
2905 Py_DECREF(res);
2906 return 0;
2907}
2908
Guido van Rossumdc91b992001-08-08 22:26:22 +00002909SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2910SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2911SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2912SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2913SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2914SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2915
2916staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2917
2918SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2919 nb_power, "__pow__", "__rpow__")
2920
2921static PyObject *
2922slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2923{
Guido van Rossum2730b132001-08-28 18:22:14 +00002924 static PyObject *pow_str;
2925
Guido van Rossumdc91b992001-08-08 22:26:22 +00002926 if (modulus == Py_None)
2927 return slot_nb_power_binary(self, other);
2928 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002929 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002930 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002931}
2932
2933SLOT0(slot_nb_negative, "__neg__")
2934SLOT0(slot_nb_positive, "__pos__")
2935SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002936
2937static int
2938slot_nb_nonzero(PyObject *self)
2939{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002940 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002941 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942
Guido van Rossum55f20992001-10-01 17:18:22 +00002943 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002944 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002945 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002946 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002947 func = lookup_maybe(self, "__len__", &len_str);
2948 if (func == NULL) {
2949 if (PyErr_Occurred())
2950 return -1;
2951 else
2952 return 1;
2953 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002954 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002955 res = PyObject_CallObject(func, NULL);
2956 Py_DECREF(func);
2957 if (res == NULL)
2958 return -1;
2959 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960}
2961
Guido van Rossumdc91b992001-08-08 22:26:22 +00002962SLOT0(slot_nb_invert, "__invert__")
2963SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2964SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2965SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2966SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2967SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002968
2969static int
2970slot_nb_coerce(PyObject **a, PyObject **b)
2971{
2972 static PyObject *coerce_str;
2973 PyObject *self = *a, *other = *b;
2974
2975 if (self->ob_type->tp_as_number != NULL &&
2976 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2977 PyObject *r;
2978 r = call_maybe(
2979 self, "__coerce__", &coerce_str, "(O)", other);
2980 if (r == NULL)
2981 return -1;
2982 if (r == Py_NotImplemented) {
2983 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002984 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002985 else {
2986 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2987 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002988 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00002989 Py_DECREF(r);
2990 return -1;
2991 }
2992 *a = PyTuple_GET_ITEM(r, 0);
2993 Py_INCREF(*a);
2994 *b = PyTuple_GET_ITEM(r, 1);
2995 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002996 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00002997 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002998 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002999 }
3000 if (other->ob_type->tp_as_number != NULL &&
3001 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3002 PyObject *r;
3003 r = call_maybe(
3004 other, "__coerce__", &coerce_str, "(O)", self);
3005 if (r == NULL)
3006 return -1;
3007 if (r == Py_NotImplemented) {
3008 Py_DECREF(r);
3009 return 1;
3010 }
3011 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3012 PyErr_SetString(PyExc_TypeError,
3013 "__coerce__ didn't return a 2-tuple");
3014 Py_DECREF(r);
3015 return -1;
3016 }
3017 *a = PyTuple_GET_ITEM(r, 1);
3018 Py_INCREF(*a);
3019 *b = PyTuple_GET_ITEM(r, 0);
3020 Py_INCREF(*b);
3021 Py_DECREF(r);
3022 return 0;
3023 }
3024 return 1;
3025}
3026
Guido van Rossumdc91b992001-08-08 22:26:22 +00003027SLOT0(slot_nb_int, "__int__")
3028SLOT0(slot_nb_long, "__long__")
3029SLOT0(slot_nb_float, "__float__")
3030SLOT0(slot_nb_oct, "__oct__")
3031SLOT0(slot_nb_hex, "__hex__")
3032SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3033SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3034SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3035SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3036SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3037SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3038SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3039SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3040SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3041SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3042SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3043SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3044 "__floordiv__", "__rfloordiv__")
3045SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3046SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3047SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048
3049static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003050half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003052 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003053 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003054 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055
Guido van Rossum60718732001-08-28 17:47:51 +00003056 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003057 if (func == NULL) {
3058 PyErr_Clear();
3059 }
3060 else {
3061 args = Py_BuildValue("(O)", other);
3062 if (args == NULL)
3063 res = NULL;
3064 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003065 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003066 Py_DECREF(args);
3067 }
3068 if (res != Py_NotImplemented) {
3069 if (res == NULL)
3070 return -2;
3071 c = PyInt_AsLong(res);
3072 Py_DECREF(res);
3073 if (c == -1 && PyErr_Occurred())
3074 return -2;
3075 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3076 }
3077 Py_DECREF(res);
3078 }
3079 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003080}
3081
Guido van Rossumab3b0342001-09-18 20:38:53 +00003082/* This slot is published for the benefit of try_3way_compare in object.c */
3083int
3084_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003085{
3086 int c;
3087
Guido van Rossumab3b0342001-09-18 20:38:53 +00003088 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003089 c = half_compare(self, other);
3090 if (c <= 1)
3091 return c;
3092 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003093 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003094 c = half_compare(other, self);
3095 if (c < -1)
3096 return -2;
3097 if (c <= 1)
3098 return -c;
3099 }
3100 return (void *)self < (void *)other ? -1 :
3101 (void *)self > (void *)other ? 1 : 0;
3102}
3103
3104static PyObject *
3105slot_tp_repr(PyObject *self)
3106{
3107 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003108 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003109
Guido van Rossum60718732001-08-28 17:47:51 +00003110 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003111 if (func != NULL) {
3112 res = PyEval_CallObject(func, NULL);
3113 Py_DECREF(func);
3114 return res;
3115 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003116 PyErr_Clear();
3117 return PyString_FromFormat("<%s object at %p>",
3118 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003119}
3120
3121static PyObject *
3122slot_tp_str(PyObject *self)
3123{
3124 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003125 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003126
Guido van Rossum60718732001-08-28 17:47:51 +00003127 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003128 if (func != NULL) {
3129 res = PyEval_CallObject(func, NULL);
3130 Py_DECREF(func);
3131 return res;
3132 }
3133 else {
3134 PyErr_Clear();
3135 return slot_tp_repr(self);
3136 }
3137}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003138
3139static long
3140slot_tp_hash(PyObject *self)
3141{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003142 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003143 static PyObject *hash_str, *eq_str, *cmp_str;
3144
Tim Peters6d6c1a32001-08-02 04:15:00 +00003145 long h;
3146
Guido van Rossum60718732001-08-28 17:47:51 +00003147 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003148
3149 if (func != NULL) {
3150 res = PyEval_CallObject(func, NULL);
3151 Py_DECREF(func);
3152 if (res == NULL)
3153 return -1;
3154 h = PyInt_AsLong(res);
3155 }
3156 else {
3157 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003158 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003159 if (func == NULL) {
3160 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003161 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003162 }
3163 if (func != NULL) {
3164 Py_DECREF(func);
3165 PyErr_SetString(PyExc_TypeError, "unhashable type");
3166 return -1;
3167 }
3168 PyErr_Clear();
3169 h = _Py_HashPointer((void *)self);
3170 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171 if (h == -1 && !PyErr_Occurred())
3172 h = -2;
3173 return h;
3174}
3175
3176static PyObject *
3177slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3178{
Guido van Rossum60718732001-08-28 17:47:51 +00003179 static PyObject *call_str;
3180 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181 PyObject *res;
3182
3183 if (meth == NULL)
3184 return NULL;
3185 res = PyObject_Call(meth, args, kwds);
3186 Py_DECREF(meth);
3187 return res;
3188}
3189
Guido van Rossum14a6f832001-10-17 13:59:09 +00003190/* There are two slot dispatch functions for tp_getattro.
3191
3192 - slot_tp_getattro() is used when __getattribute__ is overridden
3193 but no __getattr__ hook is present;
3194
3195 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3196
3197 The code in update_slot() and fixup_slot_dispatchers() always installs
3198 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3199 installs the simpler slot if necessary. */
3200
Tim Peters6d6c1a32001-08-02 04:15:00 +00003201static PyObject *
3202slot_tp_getattro(PyObject *self, PyObject *name)
3203{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003204 static PyObject *getattribute_str = NULL;
3205 return call_method(self, "__getattribute__", &getattribute_str,
3206 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003207}
3208
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003209static PyObject *
3210slot_tp_getattr_hook(PyObject *self, PyObject *name)
3211{
3212 PyTypeObject *tp = self->ob_type;
3213 PyObject *getattr, *getattribute, *res;
3214 static PyObject *getattribute_str = NULL;
3215 static PyObject *getattr_str = NULL;
3216
3217 if (getattr_str == NULL) {
3218 getattr_str = PyString_InternFromString("__getattr__");
3219 if (getattr_str == NULL)
3220 return NULL;
3221 }
3222 if (getattribute_str == NULL) {
3223 getattribute_str =
3224 PyString_InternFromString("__getattribute__");
3225 if (getattribute_str == NULL)
3226 return NULL;
3227 }
3228 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003229 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003230 /* No __getattr__ hook: use a simpler dispatcher */
3231 tp->tp_getattro = slot_tp_getattro;
3232 return slot_tp_getattro(self, name);
3233 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003234 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003235 if (getattribute == NULL ||
3236 (getattribute->ob_type == &PyWrapperDescr_Type &&
3237 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3238 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003239 res = PyObject_GenericGetAttr(self, name);
3240 else
3241 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003242 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003243 PyErr_Clear();
3244 res = PyObject_CallFunction(getattr, "OO", self, name);
3245 }
3246 return res;
3247}
3248
Tim Peters6d6c1a32001-08-02 04:15:00 +00003249static int
3250slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3251{
3252 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003253 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003254
3255 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003256 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003257 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003258 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003259 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003260 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261 if (res == NULL)
3262 return -1;
3263 Py_DECREF(res);
3264 return 0;
3265}
3266
3267/* Map rich comparison operators to their __xx__ namesakes */
3268static char *name_op[] = {
3269 "__lt__",
3270 "__le__",
3271 "__eq__",
3272 "__ne__",
3273 "__gt__",
3274 "__ge__",
3275};
3276
3277static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003279{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003280 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003281 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003282
Guido van Rossum60718732001-08-28 17:47:51 +00003283 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003284 if (func == NULL) {
3285 PyErr_Clear();
3286 Py_INCREF(Py_NotImplemented);
3287 return Py_NotImplemented;
3288 }
3289 args = Py_BuildValue("(O)", other);
3290 if (args == NULL)
3291 res = NULL;
3292 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003293 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003294 Py_DECREF(args);
3295 }
3296 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003297 return res;
3298}
3299
Guido van Rossumb8f63662001-08-15 23:57:02 +00003300/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3301static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3302
3303static PyObject *
3304slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3305{
3306 PyObject *res;
3307
3308 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3309 res = half_richcompare(self, other, op);
3310 if (res != Py_NotImplemented)
3311 return res;
3312 Py_DECREF(res);
3313 }
3314 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3315 res = half_richcompare(other, self, swapped_op[op]);
3316 if (res != Py_NotImplemented) {
3317 return res;
3318 }
3319 Py_DECREF(res);
3320 }
3321 Py_INCREF(Py_NotImplemented);
3322 return Py_NotImplemented;
3323}
3324
3325static PyObject *
3326slot_tp_iter(PyObject *self)
3327{
3328 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003329 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003330
Guido van Rossum60718732001-08-28 17:47:51 +00003331 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003332 if (func != NULL) {
3333 res = PyObject_CallObject(func, NULL);
3334 Py_DECREF(func);
3335 return res;
3336 }
3337 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003338 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003339 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003340 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003341 return NULL;
3342 }
3343 Py_DECREF(func);
3344 return PySeqIter_New(self);
3345}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003346
3347static PyObject *
3348slot_tp_iternext(PyObject *self)
3349{
Guido van Rossum2730b132001-08-28 18:22:14 +00003350 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003351 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352}
3353
Guido van Rossum1a493502001-08-17 16:47:50 +00003354static PyObject *
3355slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3356{
3357 PyTypeObject *tp = self->ob_type;
3358 PyObject *get;
3359 static PyObject *get_str = NULL;
3360
3361 if (get_str == NULL) {
3362 get_str = PyString_InternFromString("__get__");
3363 if (get_str == NULL)
3364 return NULL;
3365 }
3366 get = _PyType_Lookup(tp, get_str);
3367 if (get == NULL) {
3368 /* Avoid further slowdowns */
3369 if (tp->tp_descr_get == slot_tp_descr_get)
3370 tp->tp_descr_get = NULL;
3371 Py_INCREF(self);
3372 return self;
3373 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003374 if (obj == NULL)
3375 obj = Py_None;
3376 if (type == NULL)
3377 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003378 return PyObject_CallFunction(get, "OOO", self, obj, type);
3379}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003380
3381static int
3382slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3383{
Guido van Rossum2c252392001-08-24 10:13:31 +00003384 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003385 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003386
3387 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003388 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003389 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003390 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003391 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003392 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393 if (res == NULL)
3394 return -1;
3395 Py_DECREF(res);
3396 return 0;
3397}
3398
3399static int
3400slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3401{
Guido van Rossum60718732001-08-28 17:47:51 +00003402 static PyObject *init_str;
3403 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404 PyObject *res;
3405
3406 if (meth == NULL)
3407 return -1;
3408 res = PyObject_Call(meth, args, kwds);
3409 Py_DECREF(meth);
3410 if (res == NULL)
3411 return -1;
3412 Py_DECREF(res);
3413 return 0;
3414}
3415
3416static PyObject *
3417slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3418{
3419 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3420 PyObject *newargs, *x;
3421 int i, n;
3422
3423 if (func == NULL)
3424 return NULL;
3425 assert(PyTuple_Check(args));
3426 n = PyTuple_GET_SIZE(args);
3427 newargs = PyTuple_New(n+1);
3428 if (newargs == NULL)
3429 return NULL;
3430 Py_INCREF(type);
3431 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3432 for (i = 0; i < n; i++) {
3433 x = PyTuple_GET_ITEM(args, i);
3434 Py_INCREF(x);
3435 PyTuple_SET_ITEM(newargs, i+1, x);
3436 }
3437 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003438 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439 Py_DECREF(func);
3440 return x;
3441}
3442
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003443
3444/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3445 functions. The offsets here are relative to the 'etype' structure, which
3446 incorporates the additional structures used for numbers, sequences and
3447 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3448 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3449 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3450
Guido van Rossum6d204072001-10-21 00:44:31 +00003451typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003452
3453#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003454#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003455#undef ETSLOT
3456#undef SQSLOT
3457#undef MPSLOT
3458#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003459#undef UNSLOT
3460#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003461#undef BINSLOT
3462#undef RBINSLOT
3463
Guido van Rossum6d204072001-10-21 00:44:31 +00003464#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3465 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003466#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3467 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3468 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003469#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3470 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3471#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3472 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3473#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3474 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3475#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3476 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3477#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3478 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3479 "x." NAME "() <==> " DOC)
3480#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3481 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3482 "x." NAME "(y) <==> x" DOC "y")
3483#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3484 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3485 "x." NAME "(y) <==> x" DOC "y")
3486#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3487 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3488 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003489
3490static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003491 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3492 "x.__len__() <==> len(x)"),
3493 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3494 "x.__add__(y) <==> x+y"),
3495 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3496 "x.__mul__(n) <==> x*n"),
3497 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3498 "x.__rmul__(n) <==> n*x"),
3499 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3500 "x.__getitem__(y) <==> x[y]"),
3501 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3502 "x.__getslice__(i, j) <==> x[i:j]"),
3503 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3504 "x.__setitem__(i, y) <==> x[i]=y"),
3505 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3506 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003507 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003508 wrap_intintobjargproc,
3509 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3510 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3511 "x.__delslice__(i, j) <==> del x[i:j]"),
3512 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3513 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003514 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003515 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003516 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003517 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003518
Guido van Rossum6d204072001-10-21 00:44:31 +00003519 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3520 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003521 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003522 wrap_binaryfunc,
3523 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003524 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003525 wrap_objobjargproc,
3526 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003527 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003528 wrap_delitem,
3529 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003530
Guido van Rossum6d204072001-10-21 00:44:31 +00003531 BINSLOT("__add__", nb_add, slot_nb_add,
3532 "+"),
3533 RBINSLOT("__radd__", nb_add, slot_nb_add,
3534 "+"),
3535 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3536 "-"),
3537 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3538 "-"),
3539 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3540 "*"),
3541 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3542 "*"),
3543 BINSLOT("__div__", nb_divide, slot_nb_divide,
3544 "/"),
3545 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3546 "/"),
3547 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3548 "%"),
3549 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3550 "%"),
3551 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3552 "divmod(x, y)"),
3553 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3554 "divmod(y, x)"),
3555 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3556 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3557 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3558 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3559 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3560 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3561 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3562 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003563 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003564 "x != 0"),
3565 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3566 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3567 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3568 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3569 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3570 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3571 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3572 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3573 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3574 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3575 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3576 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3577 "x.__coerce__(y) <==> coerce(x, y)"),
3578 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3579 "int(x)"),
3580 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3581 "long(x)"),
3582 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3583 "float(x)"),
3584 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3585 "oct(x)"),
3586 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3587 "hex(x)"),
3588 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3589 wrap_binaryfunc, "+"),
3590 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3591 wrap_binaryfunc, "-"),
3592 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3593 wrap_binaryfunc, "*"),
3594 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3595 wrap_binaryfunc, "/"),
3596 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3597 wrap_binaryfunc, "%"),
3598 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3599 wrap_ternaryfunc, "**"),
3600 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3601 wrap_binaryfunc, "<<"),
3602 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3603 wrap_binaryfunc, ">>"),
3604 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3605 wrap_binaryfunc, "&"),
3606 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3607 wrap_binaryfunc, "^"),
3608 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3609 wrap_binaryfunc, "|"),
3610 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3611 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3612 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3613 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3614 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3615 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3616 IBSLOT("__itruediv__", nb_inplace_true_divide,
3617 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003618
Guido van Rossum6d204072001-10-21 00:44:31 +00003619 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3620 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003621 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003622 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3623 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003624 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003625 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3626 "x.__cmp__(y) <==> cmp(x,y)"),
3627 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3628 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003629 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3630 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003631 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003632 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3633 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3634 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3635 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3636 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3637 "x.__setattr__('name', value) <==> x.name = value"),
3638 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3639 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3640 "x.__delattr__('name') <==> del x.name"),
3641 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3642 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3643 "x.__lt__(y) <==> x<y"),
3644 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3645 "x.__le__(y) <==> x<=y"),
3646 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3647 "x.__eq__(y) <==> x==y"),
3648 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3649 "x.__ne__(y) <==> x!=y"),
3650 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3651 "x.__gt__(y) <==> x>y"),
3652 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3653 "x.__ge__(y) <==> x>=y"),
3654 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3655 "x.__iter__() <==> iter(x)"),
3656 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3657 "x.next() -> the next value, or raise StopIteration"),
3658 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3659 "descr.__get__(obj[, type]) -> value"),
3660 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3661 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003662 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003663 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003664 "see x.__class__.__doc__ for signature",
3665 PyWrapperFlag_KEYWORDS),
3666 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003667 {NULL}
3668};
3669
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003670static void **
3671slotptr(PyTypeObject *type, int offset)
3672{
3673 char *ptr;
3674
3675 assert(offset >= 0);
3676 assert(offset < offsetof(etype, as_buffer));
3677 if (offset >= offsetof(etype, as_mapping)) {
3678 ptr = (void *)type->tp_as_mapping;
3679 offset -= offsetof(etype, as_mapping);
3680 }
3681 else if (offset >= offsetof(etype, as_sequence)) {
3682 ptr = (void *)type->tp_as_sequence;
3683 offset -= offsetof(etype, as_sequence);
3684 }
3685 else if (offset >= offsetof(etype, as_number)) {
3686 ptr = (void *)type->tp_as_number;
3687 offset -= offsetof(etype, as_number);
3688 }
3689 else {
3690 ptr = (void *)type;
3691 }
3692 if (ptr != NULL)
3693 ptr += offset;
3694 return (void **)ptr;
3695}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003696
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003697staticforward int recurse_down_subclasses(PyTypeObject *type,
3698 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003699
3700static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003701update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003702{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003703 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003704
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003705 for (pp = pp0; *pp; pp++) {
3706 slotdef *p = *pp;
3707 PyObject *descr;
3708 PyWrapperDescrObject *d;
3709 void *generic = NULL, *specific = NULL;
3710 int use_generic = 0;
3711 int offset = p->offset;
3712 void **ptr = slotptr(type, offset);
3713 if (ptr == NULL)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003714 continue;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003715 do {
3716 descr = _PyType_Lookup(type, p->name_strobj);
3717 if (descr == NULL)
3718 continue;
3719 generic = p->function;
3720 if (descr->ob_type == &PyWrapperDescr_Type) {
3721 d = (PyWrapperDescrObject *)descr;
3722 if (d->d_base->wrapper == p->wrapper &&
3723 PyType_IsSubtype(type, d->d_type)) {
3724 if (specific == NULL ||
3725 specific == d->d_wrapped)
3726 specific = d->d_wrapped;
3727 else
3728 use_generic = 1;
3729 }
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003730 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003731 else
3732 use_generic = 1;
3733 } while ((++p)->offset == offset);
3734 if (specific && !use_generic)
3735 *ptr = specific;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003736 else
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003737 *ptr = generic;
3738 }
3739 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003740}
3741
3742static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003743recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003744{
3745 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003746 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003747 int i, n;
3748
3749 subclasses = type->tp_subclasses;
3750 if (subclasses == NULL)
3751 return 0;
3752 assert(PyList_Check(subclasses));
3753 n = PyList_GET_SIZE(subclasses);
3754 for (i = 0; i < n; i++) {
3755 ref = PyList_GET_ITEM(subclasses, i);
3756 assert(PyWeakref_CheckRef(ref));
3757 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3758 if (subclass == NULL)
3759 continue;
3760 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003761 /* Avoid recursing down into unaffected classes */
3762 dict = subclass->tp_dict;
3763 if (dict != NULL && PyDict_Check(dict) &&
3764 PyDict_GetItem(dict, name) != NULL)
3765 continue;
3766 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003767 return -1;
3768 }
3769 return 0;
3770}
3771
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003772static int
3773slotdef_cmp(const void *aa, const void *bb)
3774{
3775 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3776 int c = a->offset - b->offset;
3777 if (c != 0)
3778 return c;
3779 else
3780 return a - b;
3781}
3782
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003783static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003784init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003785{
3786 slotdef *p;
3787 static int initialized = 0;
3788
3789 if (initialized)
3790 return;
3791 for (p = slotdefs; p->name; p++) {
3792 p->name_strobj = PyString_InternFromString(p->name);
3793 if (!p->name_strobj)
3794 Py_FatalError("XXX ouch");
3795 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003796 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3797 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003798 initialized = 1;
3799}
3800
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003801static int
3802update_slot(PyTypeObject *type, PyObject *name)
3803{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003804 slotdef *ptrs[10];
3805 slotdef *p;
3806 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003807 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003808
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003809 init_slotdefs();
3810 pp = ptrs;
3811 for (p = slotdefs; p->name; p++) {
3812 /* XXX assume name is interned! */
3813 if (p->name_strobj == name)
3814 *pp++ = p;
3815 }
3816 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003817 for (pp = ptrs; *pp; pp++) {
3818 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003819 offset = p->offset;
3820 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003821 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003822 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003823 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003824 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003825}
3826
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003828fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003829{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003830 slotdef *p;
3831 PyObject *mro, *descr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003832 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003833 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003834 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003835 void *generic, *specific;
3836 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003838 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003839 mro = type->tp_mro;
3840 assert(PyTuple_Check(mro));
3841 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003842 for (p = slotdefs; p->name; ) {
3843 offset = p->offset;
3844 ptr = slotptr(type, offset);
3845 if (!ptr) {
3846 do {
3847 ++p;
3848 } while (p->offset == offset);
3849 continue;
3850 }
3851 generic = specific = NULL;
3852 use_generic = 0;
3853 do {
3854 descr = NULL;
3855 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003856 PyObject *b = PyTuple_GET_ITEM(mro, i);
3857 PyObject *dict = NULL;
3858 if (PyType_Check(b))
3859 dict = ((PyTypeObject *)b)->tp_dict;
3860 else if (PyClass_Check(b))
3861 dict = ((PyClassObject *)b)->cl_dict;
3862 if (dict != NULL) {
3863 descr = PyDict_GetItem(
3864 dict, p->name_strobj);
3865 if (descr != NULL)
3866 break;
3867 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003868 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003869 if (descr == NULL)
3870 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003871 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003872 if (descr->ob_type == &PyWrapperDescr_Type) {
3873 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003874 if (d->d_base->wrapper == p->wrapper &&
Guido van Rossumcaf59042001-10-17 07:15:43 +00003875 PyType_IsSubtype(type, d->d_type))
3876 {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003877 if (specific == NULL ||
Guido van Rossumcaf59042001-10-17 07:15:43 +00003878 specific == d->d_wrapped)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003879 specific = d->d_wrapped;
3880 else
3881 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003882 }
3883 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003884 else
3885 use_generic = 1;
3886 } while ((++p)->offset == offset);
3887 if (specific && !use_generic)
3888 *ptr = specific;
3889 else
3890 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003892}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003893
Guido van Rossum6d204072001-10-21 00:44:31 +00003894/* This function is called by PyType_Ready() to populate the type's
3895 dictionary with method descriptors for function slots. For each
3896 function slot (like tp_repr) that's defined in the type, one or
3897 more corresponding descriptors are added in the type's tp_dict
3898 dictionary under the appropriate name (like __repr__). Some
3899 function slots cause more than one descriptor to be added (for
3900 example, the nb_add slot adds both __add__ and __radd__
3901 descriptors) and some function slots compete for the same
3902 descriptor (for example both sq_item and mp_subscript generate a
3903 __getitem__ descriptor). This only adds new descriptors and
3904 doesn't overwrite entries in tp_dict that were previously
3905 defined. The descriptors contain a reference to the C function
3906 they must call, so that it's safe if they are copied into a
3907 subtype's __dict__ and the subtype has a different C function in
3908 its slot -- calling the method defined by the descriptor will call
3909 the C function that was used to create it, rather than the C
3910 function present in the slot when it is called. (This is important
3911 because a subtype may have a C function in the slot that calls the
3912 method from the dictionary, and we want to avoid infinite recursion
3913 here.) */
3914
3915static int
3916add_operators(PyTypeObject *type)
3917{
3918 PyObject *dict = type->tp_dict;
3919 slotdef *p;
3920 PyObject *descr;
3921 void **ptr;
3922
3923 init_slotdefs();
3924 for (p = slotdefs; p->name; p++) {
3925 if (p->wrapper == NULL)
3926 continue;
3927 ptr = slotptr(type, p->offset);
3928 if (!ptr || !*ptr)
3929 continue;
3930 if (PyDict_GetItem(dict, p->name_strobj))
3931 continue;
3932 descr = PyDescr_NewWrapper(type, p, *ptr);
3933 if (descr == NULL)
3934 return -1;
3935 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
3936 return -1;
3937 Py_DECREF(descr);
3938 }
3939 if (type->tp_new != NULL) {
3940 if (add_tp_new_wrapper(type) < 0)
3941 return -1;
3942 }
3943 return 0;
3944}
3945
Guido van Rossum705f0f52001-08-24 16:47:00 +00003946
3947/* Cooperative 'super' */
3948
3949typedef struct {
3950 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003951 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003952 PyObject *obj;
3953} superobject;
3954
Guido van Rossum6f799372001-09-20 20:46:19 +00003955static PyMemberDef super_members[] = {
3956 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3957 "the class invoking super()"},
3958 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3959 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003960 {0}
3961};
3962
Guido van Rossum705f0f52001-08-24 16:47:00 +00003963static void
3964super_dealloc(PyObject *self)
3965{
3966 superobject *su = (superobject *)self;
3967
Guido van Rossum048eb752001-10-02 21:24:57 +00003968 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003969 Py_XDECREF(su->obj);
3970 Py_XDECREF(su->type);
3971 self->ob_type->tp_free(self);
3972}
3973
3974static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003975super_repr(PyObject *self)
3976{
3977 superobject *su = (superobject *)self;
3978
3979 if (su->obj)
3980 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003981 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003982 su->type ? su->type->tp_name : "NULL",
3983 su->obj->ob_type->tp_name);
3984 else
3985 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003986 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003987 su->type ? su->type->tp_name : "NULL");
3988}
3989
3990static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003991super_getattro(PyObject *self, PyObject *name)
3992{
3993 superobject *su = (superobject *)self;
3994
3995 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00003996 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003997 descrgetfunc f;
3998 int i, n;
3999
Guido van Rossume705ef12001-08-29 15:47:06 +00004000 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004001 if (mro == NULL)
4002 n = 0;
4003 else {
4004 assert(PyTuple_Check(mro));
4005 n = PyTuple_GET_SIZE(mro);
4006 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004007 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004008 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004009 break;
4010 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004011 if (i >= n && PyType_Check(su->obj)) {
4012 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004013 if (mro == NULL)
4014 n = 0;
4015 else {
4016 assert(PyTuple_Check(mro));
4017 n = PyTuple_GET_SIZE(mro);
4018 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004019 for (i = 0; i < n; i++) {
4020 if ((PyObject *)(su->type) ==
4021 PyTuple_GET_ITEM(mro, i))
4022 break;
4023 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004024 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004025 i++;
4026 res = NULL;
4027 for (; i < n; i++) {
4028 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004029 if (PyType_Check(tmp))
4030 dict = ((PyTypeObject *)tmp)->tp_dict;
4031 else if (PyClass_Check(tmp))
4032 dict = ((PyClassObject *)tmp)->cl_dict;
4033 else
4034 continue;
4035 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004036 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004037 Py_INCREF(res);
4038 f = res->ob_type->tp_descr_get;
4039 if (f != NULL) {
4040 tmp = f(res, su->obj, res);
4041 Py_DECREF(res);
4042 res = tmp;
4043 }
4044 return res;
4045 }
4046 }
4047 }
4048 return PyObject_GenericGetAttr(self, name);
4049}
4050
Guido van Rossum5b443c62001-12-03 15:38:28 +00004051static int
4052supercheck(PyTypeObject *type, PyObject *obj)
4053{
4054 if (!PyType_IsSubtype(obj->ob_type, type) &&
4055 !(PyType_Check(obj) &&
4056 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4057 PyErr_SetString(PyExc_TypeError,
4058 "super(type, obj): "
4059 "obj must be an instance or subtype of type");
4060 return -1;
4061 }
4062 else
4063 return 0;
4064}
4065
Guido van Rossum705f0f52001-08-24 16:47:00 +00004066static PyObject *
4067super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4068{
4069 superobject *su = (superobject *)self;
4070 superobject *new;
4071
4072 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4073 /* Not binding to an object, or already bound */
4074 Py_INCREF(self);
4075 return self;
4076 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004077 if (su->ob_type != &PySuper_Type)
4078 /* If su is an instance of a subclass of super,
4079 call its type */
4080 return PyObject_CallFunction((PyObject *)su->ob_type,
4081 "OO", su->type, obj);
4082 else {
4083 /* Inline the common case */
4084 if (supercheck(su->type, obj) < 0)
4085 return NULL;
4086 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4087 NULL, NULL);
4088 if (new == NULL)
4089 return NULL;
4090 Py_INCREF(su->type);
4091 Py_INCREF(obj);
4092 new->type = su->type;
4093 new->obj = obj;
4094 return (PyObject *)new;
4095 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004096}
4097
4098static int
4099super_init(PyObject *self, PyObject *args, PyObject *kwds)
4100{
4101 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004102 PyTypeObject *type;
4103 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004104
4105 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4106 return -1;
4107 if (obj == Py_None)
4108 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004109 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004110 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004111 Py_INCREF(type);
4112 Py_XINCREF(obj);
4113 su->type = type;
4114 su->obj = obj;
4115 return 0;
4116}
4117
4118static char super_doc[] =
4119"super(type) -> unbound super object\n"
4120"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004121"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004122"Typical use to call a cooperative superclass method:\n"
4123"class C(B):\n"
4124" def meth(self, arg):\n"
4125" super(C, self).meth(arg)";
4126
Guido van Rossum048eb752001-10-02 21:24:57 +00004127static int
4128super_traverse(PyObject *self, visitproc visit, void *arg)
4129{
4130 superobject *su = (superobject *)self;
4131 int err;
4132
4133#define VISIT(SLOT) \
4134 if (SLOT) { \
4135 err = visit((PyObject *)(SLOT), arg); \
4136 if (err) \
4137 return err; \
4138 }
4139
4140 VISIT(su->obj);
4141 VISIT(su->type);
4142
4143#undef VISIT
4144
4145 return 0;
4146}
4147
Guido van Rossum705f0f52001-08-24 16:47:00 +00004148PyTypeObject PySuper_Type = {
4149 PyObject_HEAD_INIT(&PyType_Type)
4150 0, /* ob_size */
4151 "super", /* tp_name */
4152 sizeof(superobject), /* tp_basicsize */
4153 0, /* tp_itemsize */
4154 /* methods */
4155 super_dealloc, /* tp_dealloc */
4156 0, /* tp_print */
4157 0, /* tp_getattr */
4158 0, /* tp_setattr */
4159 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004160 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004161 0, /* tp_as_number */
4162 0, /* tp_as_sequence */
4163 0, /* tp_as_mapping */
4164 0, /* tp_hash */
4165 0, /* tp_call */
4166 0, /* tp_str */
4167 super_getattro, /* tp_getattro */
4168 0, /* tp_setattro */
4169 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004170 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4171 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004172 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004173 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004174 0, /* tp_clear */
4175 0, /* tp_richcompare */
4176 0, /* tp_weaklistoffset */
4177 0, /* tp_iter */
4178 0, /* tp_iternext */
4179 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004180 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004181 0, /* tp_getset */
4182 0, /* tp_base */
4183 0, /* tp_dict */
4184 super_descr_get, /* tp_descr_get */
4185 0, /* tp_descr_set */
4186 0, /* tp_dictoffset */
4187 super_init, /* tp_init */
4188 PyType_GenericAlloc, /* tp_alloc */
4189 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004190 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004191};