blob: a5967210cbf0e5a8077ccc3daf6e3516569b8c3a [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
Fred Drake7bf97152002-03-28 05:33:33 +00001697static PyObject *
1698create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1699{
1700 PyObject *cfunc;
1701 PyObject *result;
1702
1703 cfunc = PyCFunction_New(meth, NULL);
1704 if (cfunc == NULL)
1705 return NULL;
1706 result = func(cfunc);
1707 Py_DECREF(cfunc);
1708 return result;
1709}
1710
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711static int
1712add_methods(PyTypeObject *type, PyMethodDef *meth)
1713{
Guido van Rossum687ae002001-10-15 22:03:32 +00001714 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715
1716 for (; meth->ml_name != NULL; meth++) {
1717 PyObject *descr;
1718 if (PyDict_GetItemString(dict, meth->ml_name))
1719 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001720 if (meth->ml_flags & METH_CLASS) {
1721 if (meth->ml_flags & METH_STATIC) {
1722 PyErr_SetString(PyExc_ValueError,
1723 "method cannot be both class and static");
1724 return -1;
1725 }
1726 descr = create_specialmethod(meth, PyClassMethod_New);
1727 }
1728 else if (meth->ml_flags & METH_STATIC) {
1729 descr = create_specialmethod(meth, PyStaticMethod_New);
1730 }
1731 else {
1732 descr = PyDescr_NewMethod(type, meth);
1733 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001734 if (descr == NULL)
1735 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001736 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737 return -1;
1738 Py_DECREF(descr);
1739 }
1740 return 0;
1741}
1742
1743static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001744add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001745{
Guido van Rossum687ae002001-10-15 22:03:32 +00001746 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747
1748 for (; memb->name != NULL; memb++) {
1749 PyObject *descr;
1750 if (PyDict_GetItemString(dict, memb->name))
1751 continue;
1752 descr = PyDescr_NewMember(type, memb);
1753 if (descr == NULL)
1754 return -1;
1755 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1756 return -1;
1757 Py_DECREF(descr);
1758 }
1759 return 0;
1760}
1761
1762static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001763add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764{
Guido van Rossum687ae002001-10-15 22:03:32 +00001765 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766
1767 for (; gsp->name != NULL; gsp++) {
1768 PyObject *descr;
1769 if (PyDict_GetItemString(dict, gsp->name))
1770 continue;
1771 descr = PyDescr_NewGetSet(type, gsp);
1772
1773 if (descr == NULL)
1774 return -1;
1775 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1776 return -1;
1777 Py_DECREF(descr);
1778 }
1779 return 0;
1780}
1781
Guido van Rossum13d52f02001-08-10 21:24:08 +00001782static void
1783inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001784{
1785 int oldsize, newsize;
1786
Guido van Rossum13d52f02001-08-10 21:24:08 +00001787 /* Special flag magic */
1788 if (!type->tp_as_buffer && base->tp_as_buffer) {
1789 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1790 type->tp_flags |=
1791 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1792 }
1793 if (!type->tp_as_sequence && base->tp_as_sequence) {
1794 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1795 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1796 }
1797 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1798 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1799 if ((!type->tp_as_number && base->tp_as_number) ||
1800 (!type->tp_as_sequence && base->tp_as_sequence)) {
1801 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1802 if (!type->tp_as_number && !type->tp_as_sequence) {
1803 type->tp_flags |= base->tp_flags &
1804 Py_TPFLAGS_HAVE_INPLACEOPS;
1805 }
1806 }
1807 /* Wow */
1808 }
1809 if (!type->tp_as_number && base->tp_as_number) {
1810 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1811 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1812 }
1813
1814 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001815 oldsize = base->tp_basicsize;
1816 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1817 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1818 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001819 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1820 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001821 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001822 if (type->tp_traverse == NULL)
1823 type->tp_traverse = base->tp_traverse;
1824 if (type->tp_clear == NULL)
1825 type->tp_clear = base->tp_clear;
1826 }
1827 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001828 /* The condition below could use some explanation.
1829 It appears that tp_new is not inherited for static types
1830 whose base class is 'object'; this seems to be a precaution
1831 so that old extension types don't suddenly become
1832 callable (object.__new__ wouldn't insure the invariants
1833 that the extension type's own factory function ensures).
1834 Heap types, of course, are under our control, so they do
1835 inherit tp_new; static extension types that specify some
1836 other built-in type as the default are considered
1837 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001838 if (base != &PyBaseObject_Type ||
1839 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1840 if (type->tp_new == NULL)
1841 type->tp_new = base->tp_new;
1842 }
1843 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001844 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001845
1846 /* Copy other non-function slots */
1847
1848#undef COPYVAL
1849#define COPYVAL(SLOT) \
1850 if (type->SLOT == 0) type->SLOT = base->SLOT
1851
1852 COPYVAL(tp_itemsize);
1853 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1854 COPYVAL(tp_weaklistoffset);
1855 }
1856 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1857 COPYVAL(tp_dictoffset);
1858 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001859}
1860
1861static void
1862inherit_slots(PyTypeObject *type, PyTypeObject *base)
1863{
1864 PyTypeObject *basebase;
1865
1866#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867#undef COPYSLOT
1868#undef COPYNUM
1869#undef COPYSEQ
1870#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001871#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001872
1873#define SLOTDEFINED(SLOT) \
1874 (base->SLOT != 0 && \
1875 (basebase == NULL || base->SLOT != basebase->SLOT))
1876
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001878 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879
1880#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1881#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1882#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001883#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884
Guido van Rossum13d52f02001-08-10 21:24:08 +00001885 /* This won't inherit indirect slots (from tp_as_number etc.)
1886 if type doesn't provide the space. */
1887
1888 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1889 basebase = base->tp_base;
1890 if (basebase->tp_as_number == NULL)
1891 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001892 COPYNUM(nb_add);
1893 COPYNUM(nb_subtract);
1894 COPYNUM(nb_multiply);
1895 COPYNUM(nb_divide);
1896 COPYNUM(nb_remainder);
1897 COPYNUM(nb_divmod);
1898 COPYNUM(nb_power);
1899 COPYNUM(nb_negative);
1900 COPYNUM(nb_positive);
1901 COPYNUM(nb_absolute);
1902 COPYNUM(nb_nonzero);
1903 COPYNUM(nb_invert);
1904 COPYNUM(nb_lshift);
1905 COPYNUM(nb_rshift);
1906 COPYNUM(nb_and);
1907 COPYNUM(nb_xor);
1908 COPYNUM(nb_or);
1909 COPYNUM(nb_coerce);
1910 COPYNUM(nb_int);
1911 COPYNUM(nb_long);
1912 COPYNUM(nb_float);
1913 COPYNUM(nb_oct);
1914 COPYNUM(nb_hex);
1915 COPYNUM(nb_inplace_add);
1916 COPYNUM(nb_inplace_subtract);
1917 COPYNUM(nb_inplace_multiply);
1918 COPYNUM(nb_inplace_divide);
1919 COPYNUM(nb_inplace_remainder);
1920 COPYNUM(nb_inplace_power);
1921 COPYNUM(nb_inplace_lshift);
1922 COPYNUM(nb_inplace_rshift);
1923 COPYNUM(nb_inplace_and);
1924 COPYNUM(nb_inplace_xor);
1925 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001926 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1927 COPYNUM(nb_true_divide);
1928 COPYNUM(nb_floor_divide);
1929 COPYNUM(nb_inplace_true_divide);
1930 COPYNUM(nb_inplace_floor_divide);
1931 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932 }
1933
Guido van Rossum13d52f02001-08-10 21:24:08 +00001934 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1935 basebase = base->tp_base;
1936 if (basebase->tp_as_sequence == NULL)
1937 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938 COPYSEQ(sq_length);
1939 COPYSEQ(sq_concat);
1940 COPYSEQ(sq_repeat);
1941 COPYSEQ(sq_item);
1942 COPYSEQ(sq_slice);
1943 COPYSEQ(sq_ass_item);
1944 COPYSEQ(sq_ass_slice);
1945 COPYSEQ(sq_contains);
1946 COPYSEQ(sq_inplace_concat);
1947 COPYSEQ(sq_inplace_repeat);
1948 }
1949
Guido van Rossum13d52f02001-08-10 21:24:08 +00001950 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1951 basebase = base->tp_base;
1952 if (basebase->tp_as_mapping == NULL)
1953 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954 COPYMAP(mp_length);
1955 COPYMAP(mp_subscript);
1956 COPYMAP(mp_ass_subscript);
1957 }
1958
Tim Petersfc57ccb2001-10-12 02:38:24 +00001959 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1960 basebase = base->tp_base;
1961 if (basebase->tp_as_buffer == NULL)
1962 basebase = NULL;
1963 COPYBUF(bf_getreadbuffer);
1964 COPYBUF(bf_getwritebuffer);
1965 COPYBUF(bf_getsegcount);
1966 COPYBUF(bf_getcharbuffer);
1967 }
1968
Guido van Rossum13d52f02001-08-10 21:24:08 +00001969 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001970
Tim Peters6d6c1a32001-08-02 04:15:00 +00001971 COPYSLOT(tp_dealloc);
1972 COPYSLOT(tp_print);
1973 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1974 type->tp_getattr = base->tp_getattr;
1975 type->tp_getattro = base->tp_getattro;
1976 }
1977 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1978 type->tp_setattr = base->tp_setattr;
1979 type->tp_setattro = base->tp_setattro;
1980 }
1981 /* tp_compare see tp_richcompare */
1982 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001983 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984 COPYSLOT(tp_call);
1985 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001987 if (type->tp_compare == NULL &&
1988 type->tp_richcompare == NULL &&
1989 type->tp_hash == NULL)
1990 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991 type->tp_compare = base->tp_compare;
1992 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001993 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994 }
1995 }
1996 else {
1997 COPYSLOT(tp_compare);
1998 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2000 COPYSLOT(tp_iter);
2001 COPYSLOT(tp_iternext);
2002 }
2003 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2004 COPYSLOT(tp_descr_get);
2005 COPYSLOT(tp_descr_set);
2006 COPYSLOT(tp_dictoffset);
2007 COPYSLOT(tp_init);
2008 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009 COPYSLOT(tp_free);
2010 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011}
2012
Guido van Rossum13d52f02001-08-10 21:24:08 +00002013staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002014staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002015
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002017PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002019 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020 PyTypeObject *base;
2021 int i, n;
2022
Guido van Rossumd614f972001-08-10 17:39:49 +00002023 if (type->tp_flags & Py_TPFLAGS_READY) {
2024 assert(type->tp_dict != NULL);
2025 return 0;
2026 }
2027 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002028
2029 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030
Guido van Rossumf884b742001-12-17 17:14:22 +00002031 /* Initialize ob_type if NULL. This means extensions that want to be
2032 compilable separately on Windows can call PyType_Ready() instead of
2033 initializing the ob_type field of their type objects. */
2034 if (type->ob_type == NULL)
2035 type->ob_type = &PyType_Type;
2036
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2038 base = type->tp_base;
2039 if (base == NULL && type != &PyBaseObject_Type)
2040 base = type->tp_base = &PyBaseObject_Type;
2041
2042 /* Initialize tp_bases */
2043 bases = type->tp_bases;
2044 if (bases == NULL) {
2045 if (base == NULL)
2046 bases = PyTuple_New(0);
2047 else
2048 bases = Py_BuildValue("(O)", base);
2049 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002050 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051 type->tp_bases = bases;
2052 }
2053
2054 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002055 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002056 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002057 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002058 }
2059
Guido van Rossum687ae002001-10-15 22:03:32 +00002060 /* Initialize tp_dict */
2061 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002062 if (dict == NULL) {
2063 dict = PyDict_New();
2064 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002065 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002066 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 }
2068
Guido van Rossum687ae002001-10-15 22:03:32 +00002069 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002071 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002072 if (type->tp_methods != NULL) {
2073 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002074 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002075 }
2076 if (type->tp_members != NULL) {
2077 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002078 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079 }
2080 if (type->tp_getset != NULL) {
2081 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002082 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083 }
2084
Tim Peters6d6c1a32001-08-02 04:15:00 +00002085 /* Calculate method resolution order */
2086 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002087 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002088 }
2089
Guido van Rossum13d52f02001-08-10 21:24:08 +00002090 /* Inherit special flags from dominant base */
2091 if (type->tp_base != NULL)
2092 inherit_special(type, type->tp_base);
2093
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002095 bases = type->tp_mro;
2096 assert(bases != NULL);
2097 assert(PyTuple_Check(bases));
2098 n = PyTuple_GET_SIZE(bases);
2099 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002100 PyObject *b = PyTuple_GET_ITEM(bases, i);
2101 if (PyType_Check(b))
2102 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002105 /* if the type dictionary doesn't contain a __doc__, set it from
2106 the tp_doc slot.
2107 */
2108 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2109 if (type->tp_doc != NULL) {
2110 PyObject *doc = PyString_FromString(type->tp_doc);
2111 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2112 Py_DECREF(doc);
2113 } else {
2114 PyDict_SetItemString(type->tp_dict, "__doc__", Py_None);
2115 }
2116 }
2117
Guido van Rossum13d52f02001-08-10 21:24:08 +00002118 /* Some more special stuff */
2119 base = type->tp_base;
2120 if (base != NULL) {
2121 if (type->tp_as_number == NULL)
2122 type->tp_as_number = base->tp_as_number;
2123 if (type->tp_as_sequence == NULL)
2124 type->tp_as_sequence = base->tp_as_sequence;
2125 if (type->tp_as_mapping == NULL)
2126 type->tp_as_mapping = base->tp_as_mapping;
2127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002128
Guido van Rossum1c450732001-10-08 15:18:27 +00002129 /* Link into each base class's list of subclasses */
2130 bases = type->tp_bases;
2131 n = PyTuple_GET_SIZE(bases);
2132 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002133 PyObject *b = PyTuple_GET_ITEM(bases, i);
2134 if (PyType_Check(b) &&
2135 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002136 goto error;
2137 }
2138
Guido van Rossum13d52f02001-08-10 21:24:08 +00002139 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002140 assert(type->tp_dict != NULL);
2141 type->tp_flags =
2142 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002143 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002144
2145 error:
2146 type->tp_flags &= ~Py_TPFLAGS_READYING;
2147 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002148}
2149
Guido van Rossum1c450732001-10-08 15:18:27 +00002150static int
2151add_subclass(PyTypeObject *base, PyTypeObject *type)
2152{
2153 int i;
2154 PyObject *list, *ref, *new;
2155
2156 list = base->tp_subclasses;
2157 if (list == NULL) {
2158 base->tp_subclasses = list = PyList_New(0);
2159 if (list == NULL)
2160 return -1;
2161 }
2162 assert(PyList_Check(list));
2163 new = PyWeakref_NewRef((PyObject *)type, NULL);
2164 i = PyList_GET_SIZE(list);
2165 while (--i >= 0) {
2166 ref = PyList_GET_ITEM(list, i);
2167 assert(PyWeakref_CheckRef(ref));
2168 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2169 return PyList_SetItem(list, i, new);
2170 }
2171 i = PyList_Append(list, new);
2172 Py_DECREF(new);
2173 return i;
2174}
2175
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176
2177/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2178
2179/* There's a wrapper *function* for each distinct function typedef used
2180 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2181 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2182 Most tables have only one entry; the tables for binary operators have two
2183 entries, one regular and one with reversed arguments. */
2184
2185static PyObject *
2186wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2187{
2188 inquiry func = (inquiry)wrapped;
2189 int res;
2190
2191 if (!PyArg_ParseTuple(args, ""))
2192 return NULL;
2193 res = (*func)(self);
2194 if (res == -1 && PyErr_Occurred())
2195 return NULL;
2196 return PyInt_FromLong((long)res);
2197}
2198
Tim Peters6d6c1a32001-08-02 04:15:00 +00002199static PyObject *
2200wrap_binaryfunc(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;
2207 return (*func)(self, other);
2208}
2209
2210static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002211wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2212{
2213 binaryfunc func = (binaryfunc)wrapped;
2214 PyObject *other;
2215
2216 if (!PyArg_ParseTuple(args, "O", &other))
2217 return NULL;
2218 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002219 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002220 Py_INCREF(Py_NotImplemented);
2221 return Py_NotImplemented;
2222 }
2223 return (*func)(self, other);
2224}
2225
2226static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2228{
2229 binaryfunc func = (binaryfunc)wrapped;
2230 PyObject *other;
2231
2232 if (!PyArg_ParseTuple(args, "O", &other))
2233 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002234 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002235 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002236 Py_INCREF(Py_NotImplemented);
2237 return Py_NotImplemented;
2238 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239 return (*func)(other, self);
2240}
2241
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002242static PyObject *
2243wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2244{
2245 coercion func = (coercion)wrapped;
2246 PyObject *other, *res;
2247 int ok;
2248
2249 if (!PyArg_ParseTuple(args, "O", &other))
2250 return NULL;
2251 ok = func(&self, &other);
2252 if (ok < 0)
2253 return NULL;
2254 if (ok > 0) {
2255 Py_INCREF(Py_NotImplemented);
2256 return Py_NotImplemented;
2257 }
2258 res = PyTuple_New(2);
2259 if (res == NULL) {
2260 Py_DECREF(self);
2261 Py_DECREF(other);
2262 return NULL;
2263 }
2264 PyTuple_SET_ITEM(res, 0, self);
2265 PyTuple_SET_ITEM(res, 1, other);
2266 return res;
2267}
2268
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269static PyObject *
2270wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2271{
2272 ternaryfunc func = (ternaryfunc)wrapped;
2273 PyObject *other;
2274 PyObject *third = Py_None;
2275
2276 /* Note: This wrapper only works for __pow__() */
2277
2278 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2279 return NULL;
2280 return (*func)(self, other, third);
2281}
2282
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002283static PyObject *
2284wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2285{
2286 ternaryfunc func = (ternaryfunc)wrapped;
2287 PyObject *other;
2288 PyObject *third = Py_None;
2289
2290 /* Note: This wrapper only works for __pow__() */
2291
2292 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2293 return NULL;
2294 return (*func)(other, self, third);
2295}
2296
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297static PyObject *
2298wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2299{
2300 unaryfunc func = (unaryfunc)wrapped;
2301
2302 if (!PyArg_ParseTuple(args, ""))
2303 return NULL;
2304 return (*func)(self);
2305}
2306
Tim Peters6d6c1a32001-08-02 04:15:00 +00002307static PyObject *
2308wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2309{
2310 intargfunc func = (intargfunc)wrapped;
2311 int i;
2312
2313 if (!PyArg_ParseTuple(args, "i", &i))
2314 return NULL;
2315 return (*func)(self, i);
2316}
2317
Guido van Rossum5d815f32001-08-17 21:57:47 +00002318static int
2319getindex(PyObject *self, PyObject *arg)
2320{
2321 int i;
2322
2323 i = PyInt_AsLong(arg);
2324 if (i == -1 && PyErr_Occurred())
2325 return -1;
2326 if (i < 0) {
2327 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2328 if (sq && sq->sq_length) {
2329 int n = (*sq->sq_length)(self);
2330 if (n < 0)
2331 return -1;
2332 i += n;
2333 }
2334 }
2335 return i;
2336}
2337
2338static PyObject *
2339wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2340{
2341 intargfunc func = (intargfunc)wrapped;
2342 PyObject *arg;
2343 int i;
2344
Guido van Rossumf4593e02001-10-03 12:09:30 +00002345 if (PyTuple_GET_SIZE(args) == 1) {
2346 arg = PyTuple_GET_ITEM(args, 0);
2347 i = getindex(self, arg);
2348 if (i == -1 && PyErr_Occurred())
2349 return NULL;
2350 return (*func)(self, i);
2351 }
2352 PyArg_ParseTuple(args, "O", &arg);
2353 assert(PyErr_Occurred());
2354 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002355}
2356
Tim Peters6d6c1a32001-08-02 04:15:00 +00002357static PyObject *
2358wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2359{
2360 intintargfunc func = (intintargfunc)wrapped;
2361 int i, j;
2362
2363 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2364 return NULL;
2365 return (*func)(self, i, j);
2366}
2367
Tim Peters6d6c1a32001-08-02 04:15:00 +00002368static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002369wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370{
2371 intobjargproc func = (intobjargproc)wrapped;
2372 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002373 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374
Guido van Rossum5d815f32001-08-17 21:57:47 +00002375 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2376 return NULL;
2377 i = getindex(self, arg);
2378 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002379 return NULL;
2380 res = (*func)(self, i, value);
2381 if (res == -1 && PyErr_Occurred())
2382 return NULL;
2383 Py_INCREF(Py_None);
2384 return Py_None;
2385}
2386
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002387static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002388wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002389{
2390 intobjargproc func = (intobjargproc)wrapped;
2391 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002392 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002393
Guido van Rossum5d815f32001-08-17 21:57:47 +00002394 if (!PyArg_ParseTuple(args, "O", &arg))
2395 return NULL;
2396 i = getindex(self, arg);
2397 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002398 return NULL;
2399 res = (*func)(self, i, NULL);
2400 if (res == -1 && PyErr_Occurred())
2401 return NULL;
2402 Py_INCREF(Py_None);
2403 return Py_None;
2404}
2405
Tim Peters6d6c1a32001-08-02 04:15:00 +00002406static PyObject *
2407wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2408{
2409 intintobjargproc func = (intintobjargproc)wrapped;
2410 int i, j, res;
2411 PyObject *value;
2412
2413 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2414 return NULL;
2415 res = (*func)(self, i, j, value);
2416 if (res == -1 && PyErr_Occurred())
2417 return NULL;
2418 Py_INCREF(Py_None);
2419 return Py_None;
2420}
2421
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002422static PyObject *
2423wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2424{
2425 intintobjargproc func = (intintobjargproc)wrapped;
2426 int i, j, res;
2427
2428 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2429 return NULL;
2430 res = (*func)(self, i, j, NULL);
2431 if (res == -1 && PyErr_Occurred())
2432 return NULL;
2433 Py_INCREF(Py_None);
2434 return Py_None;
2435}
2436
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437/* XXX objobjproc is a misnomer; should be objargpred */
2438static PyObject *
2439wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2440{
2441 objobjproc func = (objobjproc)wrapped;
2442 int res;
2443 PyObject *value;
2444
2445 if (!PyArg_ParseTuple(args, "O", &value))
2446 return NULL;
2447 res = (*func)(self, value);
2448 if (res == -1 && PyErr_Occurred())
2449 return NULL;
2450 return PyInt_FromLong((long)res);
2451}
2452
Tim Peters6d6c1a32001-08-02 04:15:00 +00002453static PyObject *
2454wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2455{
2456 objobjargproc func = (objobjargproc)wrapped;
2457 int res;
2458 PyObject *key, *value;
2459
2460 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2461 return NULL;
2462 res = (*func)(self, key, value);
2463 if (res == -1 && PyErr_Occurred())
2464 return NULL;
2465 Py_INCREF(Py_None);
2466 return Py_None;
2467}
2468
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002469static PyObject *
2470wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2471{
2472 objobjargproc func = (objobjargproc)wrapped;
2473 int res;
2474 PyObject *key;
2475
2476 if (!PyArg_ParseTuple(args, "O", &key))
2477 return NULL;
2478 res = (*func)(self, key, NULL);
2479 if (res == -1 && PyErr_Occurred())
2480 return NULL;
2481 Py_INCREF(Py_None);
2482 return Py_None;
2483}
2484
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485static PyObject *
2486wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2487{
2488 cmpfunc func = (cmpfunc)wrapped;
2489 int res;
2490 PyObject *other;
2491
2492 if (!PyArg_ParseTuple(args, "O", &other))
2493 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002494 if (other->ob_type->tp_compare != func &&
2495 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002496 PyErr_Format(
2497 PyExc_TypeError,
2498 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2499 self->ob_type->tp_name,
2500 self->ob_type->tp_name,
2501 other->ob_type->tp_name);
2502 return NULL;
2503 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002504 res = (*func)(self, other);
2505 if (PyErr_Occurred())
2506 return NULL;
2507 return PyInt_FromLong((long)res);
2508}
2509
Tim Peters6d6c1a32001-08-02 04:15:00 +00002510static PyObject *
2511wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2512{
2513 setattrofunc func = (setattrofunc)wrapped;
2514 int res;
2515 PyObject *name, *value;
2516
2517 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2518 return NULL;
2519 res = (*func)(self, name, value);
2520 if (res < 0)
2521 return NULL;
2522 Py_INCREF(Py_None);
2523 return Py_None;
2524}
2525
2526static PyObject *
2527wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2528{
2529 setattrofunc func = (setattrofunc)wrapped;
2530 int res;
2531 PyObject *name;
2532
2533 if (!PyArg_ParseTuple(args, "O", &name))
2534 return NULL;
2535 res = (*func)(self, name, NULL);
2536 if (res < 0)
2537 return NULL;
2538 Py_INCREF(Py_None);
2539 return Py_None;
2540}
2541
Tim Peters6d6c1a32001-08-02 04:15:00 +00002542static PyObject *
2543wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2544{
2545 hashfunc func = (hashfunc)wrapped;
2546 long res;
2547
2548 if (!PyArg_ParseTuple(args, ""))
2549 return NULL;
2550 res = (*func)(self);
2551 if (res == -1 && PyErr_Occurred())
2552 return NULL;
2553 return PyInt_FromLong(res);
2554}
2555
Tim Peters6d6c1a32001-08-02 04:15:00 +00002556static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002557wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002558{
2559 ternaryfunc func = (ternaryfunc)wrapped;
2560
Guido van Rossumc8e56452001-10-22 00:43:43 +00002561 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002562}
2563
Tim Peters6d6c1a32001-08-02 04:15:00 +00002564static PyObject *
2565wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2566{
2567 richcmpfunc func = (richcmpfunc)wrapped;
2568 PyObject *other;
2569
2570 if (!PyArg_ParseTuple(args, "O", &other))
2571 return NULL;
2572 return (*func)(self, other, op);
2573}
2574
2575#undef RICHCMP_WRAPPER
2576#define RICHCMP_WRAPPER(NAME, OP) \
2577static PyObject * \
2578richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2579{ \
2580 return wrap_richcmpfunc(self, args, wrapped, OP); \
2581}
2582
Jack Jansen8e938b42001-08-08 15:29:49 +00002583RICHCMP_WRAPPER(lt, Py_LT)
2584RICHCMP_WRAPPER(le, Py_LE)
2585RICHCMP_WRAPPER(eq, Py_EQ)
2586RICHCMP_WRAPPER(ne, Py_NE)
2587RICHCMP_WRAPPER(gt, Py_GT)
2588RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590static PyObject *
2591wrap_next(PyObject *self, PyObject *args, void *wrapped)
2592{
2593 unaryfunc func = (unaryfunc)wrapped;
2594 PyObject *res;
2595
2596 if (!PyArg_ParseTuple(args, ""))
2597 return NULL;
2598 res = (*func)(self);
2599 if (res == NULL && !PyErr_Occurred())
2600 PyErr_SetNone(PyExc_StopIteration);
2601 return res;
2602}
2603
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604static PyObject *
2605wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2606{
2607 descrgetfunc func = (descrgetfunc)wrapped;
2608 PyObject *obj;
2609 PyObject *type = NULL;
2610
2611 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2612 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613 return (*func)(self, obj, type);
2614}
2615
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002617wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618{
2619 descrsetfunc func = (descrsetfunc)wrapped;
2620 PyObject *obj, *value;
2621 int ret;
2622
2623 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2624 return NULL;
2625 ret = (*func)(self, obj, value);
2626 if (ret < 0)
2627 return NULL;
2628 Py_INCREF(Py_None);
2629 return Py_None;
2630}
2631
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002633wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002634{
2635 initproc func = (initproc)wrapped;
2636
Guido van Rossumc8e56452001-10-22 00:43:43 +00002637 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002638 return NULL;
2639 Py_INCREF(Py_None);
2640 return Py_None;
2641}
2642
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002644tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002645{
Barry Warsaw60f01882001-08-22 19:24:42 +00002646 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002647 PyObject *arg0, *res;
2648
2649 if (self == NULL || !PyType_Check(self))
2650 Py_FatalError("__new__() called with non-type 'self'");
2651 type = (PyTypeObject *)self;
2652 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002653 PyErr_Format(PyExc_TypeError,
2654 "%s.__new__(): not enough arguments",
2655 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002656 return NULL;
2657 }
2658 arg0 = PyTuple_GET_ITEM(args, 0);
2659 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002660 PyErr_Format(PyExc_TypeError,
2661 "%s.__new__(X): X is not a type object (%s)",
2662 type->tp_name,
2663 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002664 return NULL;
2665 }
2666 subtype = (PyTypeObject *)arg0;
2667 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002668 PyErr_Format(PyExc_TypeError,
2669 "%s.__new__(%s): %s is not a subtype of %s",
2670 type->tp_name,
2671 subtype->tp_name,
2672 subtype->tp_name,
2673 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002674 return NULL;
2675 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002676
2677 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002678 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002679 most derived base that's not a heap type is this type. */
2680 staticbase = subtype;
2681 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2682 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002683 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002684 PyErr_Format(PyExc_TypeError,
2685 "%s.__new__(%s) is not safe, use %s.__new__()",
2686 type->tp_name,
2687 subtype->tp_name,
2688 staticbase == NULL ? "?" : staticbase->tp_name);
2689 return NULL;
2690 }
2691
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002692 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2693 if (args == NULL)
2694 return NULL;
2695 res = type->tp_new(subtype, args, kwds);
2696 Py_DECREF(args);
2697 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698}
2699
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002700static struct PyMethodDef tp_new_methoddef[] = {
2701 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2702 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703 {0}
2704};
2705
2706static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002707add_tp_new_wrapper(PyTypeObject *type)
2708{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002709 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002710
Guido van Rossum687ae002001-10-15 22:03:32 +00002711 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002712 return 0;
2713 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002714 if (func == NULL)
2715 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002716 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002717}
2718
Guido van Rossumf040ede2001-08-07 16:40:56 +00002719/* Slot wrappers that call the corresponding __foo__ slot. See comments
2720 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721
Guido van Rossumdc91b992001-08-08 22:26:22 +00002722#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002724FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002726 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002727 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728}
2729
Guido van Rossumdc91b992001-08-08 22:26:22 +00002730#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002732FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002733{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002734 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002735 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736}
2737
Guido van Rossumdc91b992001-08-08 22:26:22 +00002738
2739#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002740static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002741FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002743 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002744 int do_other = self->ob_type != other->ob_type && \
2745 other->ob_type->tp_as_number != NULL && \
2746 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002747 if (self->ob_type->tp_as_number != NULL && \
2748 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2749 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002750 if (do_other && \
2751 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2752 r = call_maybe( \
2753 other, ROPSTR, &rcache_str, "(O)", self); \
2754 if (r != Py_NotImplemented) \
2755 return r; \
2756 Py_DECREF(r); \
2757 do_other = 0; \
2758 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002759 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002760 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002761 if (r != Py_NotImplemented || \
2762 other->ob_type == self->ob_type) \
2763 return r; \
2764 Py_DECREF(r); \
2765 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002766 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002767 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002768 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002769 } \
2770 Py_INCREF(Py_NotImplemented); \
2771 return Py_NotImplemented; \
2772}
2773
2774#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2775 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2776
2777#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2778static PyObject * \
2779FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2780{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002781 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002782 return call_method(self, OPSTR, &cache_str, \
2783 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784}
2785
2786static int
2787slot_sq_length(PyObject *self)
2788{
Guido van Rossum2730b132001-08-28 18:22:14 +00002789 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002790 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002791 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002792
2793 if (res == NULL)
2794 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002795 len = (int)PyInt_AsLong(res);
2796 Py_DECREF(res);
2797 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798}
2799
Guido van Rossumdc91b992001-08-08 22:26:22 +00002800SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2801SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002802
2803/* Super-optimized version of slot_sq_item.
2804 Other slots could do the same... */
2805static PyObject *
2806slot_sq_item(PyObject *self, int i)
2807{
2808 static PyObject *getitem_str;
2809 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2810 descrgetfunc f;
2811
2812 if (getitem_str == NULL) {
2813 getitem_str = PyString_InternFromString("__getitem__");
2814 if (getitem_str == NULL)
2815 return NULL;
2816 }
2817 func = _PyType_Lookup(self->ob_type, getitem_str);
2818 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002819 if ((f = func->ob_type->tp_descr_get) == NULL)
2820 Py_INCREF(func);
2821 else
2822 func = f(func, self, (PyObject *)(self->ob_type));
2823 ival = PyInt_FromLong(i);
2824 if (ival != NULL) {
2825 args = PyTuple_New(1);
2826 if (args != NULL) {
2827 PyTuple_SET_ITEM(args, 0, ival);
2828 retval = PyObject_Call(func, args, NULL);
2829 Py_XDECREF(args);
2830 Py_XDECREF(func);
2831 return retval;
2832 }
2833 }
2834 }
2835 else {
2836 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2837 }
2838 Py_XDECREF(args);
2839 Py_XDECREF(ival);
2840 Py_XDECREF(func);
2841 return NULL;
2842}
2843
Guido van Rossumdc91b992001-08-08 22:26:22 +00002844SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002845
2846static int
2847slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2848{
2849 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002850 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002851
2852 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002853 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002854 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002855 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002856 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002857 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002858 if (res == NULL)
2859 return -1;
2860 Py_DECREF(res);
2861 return 0;
2862}
2863
2864static int
2865slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2866{
2867 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002868 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869
2870 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002871 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002872 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002873 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002874 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002875 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002876 if (res == NULL)
2877 return -1;
2878 Py_DECREF(res);
2879 return 0;
2880}
2881
2882static int
2883slot_sq_contains(PyObject *self, PyObject *value)
2884{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002885 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002886 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887
Guido van Rossum55f20992001-10-01 17:18:22 +00002888 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002889
2890 if (func != NULL) {
2891 args = Py_BuildValue("(O)", value);
2892 if (args == NULL)
2893 res = NULL;
2894 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002895 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002896 Py_DECREF(args);
2897 }
2898 Py_DECREF(func);
2899 if (res == NULL)
2900 return -1;
2901 return PyObject_IsTrue(res);
2902 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002903 else if (PyErr_Occurred())
2904 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002905 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002906 return _PySequence_IterSearch(self, value,
2907 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002908 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909}
2910
Guido van Rossumdc91b992001-08-08 22:26:22 +00002911SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2912SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002913
2914#define slot_mp_length slot_sq_length
2915
Guido van Rossumdc91b992001-08-08 22:26:22 +00002916SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917
2918static int
2919slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2920{
2921 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002922 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002923
2924 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002925 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002926 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002928 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002929 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002930 if (res == NULL)
2931 return -1;
2932 Py_DECREF(res);
2933 return 0;
2934}
2935
Guido van Rossumdc91b992001-08-08 22:26:22 +00002936SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2937SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2938SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2939SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2940SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2941SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2942
2943staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2944
2945SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2946 nb_power, "__pow__", "__rpow__")
2947
2948static PyObject *
2949slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2950{
Guido van Rossum2730b132001-08-28 18:22:14 +00002951 static PyObject *pow_str;
2952
Guido van Rossumdc91b992001-08-08 22:26:22 +00002953 if (modulus == Py_None)
2954 return slot_nb_power_binary(self, other);
2955 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002956 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002957 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002958}
2959
2960SLOT0(slot_nb_negative, "__neg__")
2961SLOT0(slot_nb_positive, "__pos__")
2962SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963
2964static int
2965slot_nb_nonzero(PyObject *self)
2966{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002967 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002968 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969
Guido van Rossum55f20992001-10-01 17:18:22 +00002970 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002971 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002972 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002973 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002974 func = lookup_maybe(self, "__len__", &len_str);
2975 if (func == NULL) {
2976 if (PyErr_Occurred())
2977 return -1;
2978 else
2979 return 1;
2980 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002981 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002982 res = PyObject_CallObject(func, NULL);
2983 Py_DECREF(func);
2984 if (res == NULL)
2985 return -1;
2986 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987}
2988
Guido van Rossumdc91b992001-08-08 22:26:22 +00002989SLOT0(slot_nb_invert, "__invert__")
2990SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2991SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2992SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2993SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2994SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002995
2996static int
2997slot_nb_coerce(PyObject **a, PyObject **b)
2998{
2999 static PyObject *coerce_str;
3000 PyObject *self = *a, *other = *b;
3001
3002 if (self->ob_type->tp_as_number != NULL &&
3003 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3004 PyObject *r;
3005 r = call_maybe(
3006 self, "__coerce__", &coerce_str, "(O)", other);
3007 if (r == NULL)
3008 return -1;
3009 if (r == Py_NotImplemented) {
3010 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003011 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003012 else {
3013 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3014 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003015 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003016 Py_DECREF(r);
3017 return -1;
3018 }
3019 *a = PyTuple_GET_ITEM(r, 0);
3020 Py_INCREF(*a);
3021 *b = PyTuple_GET_ITEM(r, 1);
3022 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003023 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003024 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003025 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003026 }
3027 if (other->ob_type->tp_as_number != NULL &&
3028 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3029 PyObject *r;
3030 r = call_maybe(
3031 other, "__coerce__", &coerce_str, "(O)", self);
3032 if (r == NULL)
3033 return -1;
3034 if (r == Py_NotImplemented) {
3035 Py_DECREF(r);
3036 return 1;
3037 }
3038 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3039 PyErr_SetString(PyExc_TypeError,
3040 "__coerce__ didn't return a 2-tuple");
3041 Py_DECREF(r);
3042 return -1;
3043 }
3044 *a = PyTuple_GET_ITEM(r, 1);
3045 Py_INCREF(*a);
3046 *b = PyTuple_GET_ITEM(r, 0);
3047 Py_INCREF(*b);
3048 Py_DECREF(r);
3049 return 0;
3050 }
3051 return 1;
3052}
3053
Guido van Rossumdc91b992001-08-08 22:26:22 +00003054SLOT0(slot_nb_int, "__int__")
3055SLOT0(slot_nb_long, "__long__")
3056SLOT0(slot_nb_float, "__float__")
3057SLOT0(slot_nb_oct, "__oct__")
3058SLOT0(slot_nb_hex, "__hex__")
3059SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3060SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3061SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3062SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3063SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3064SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3065SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3066SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3067SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3068SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3069SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3070SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3071 "__floordiv__", "__rfloordiv__")
3072SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3073SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3074SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003075
3076static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003077half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003078{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003079 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003080 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003081 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003082
Guido van Rossum60718732001-08-28 17:47:51 +00003083 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003084 if (func == NULL) {
3085 PyErr_Clear();
3086 }
3087 else {
3088 args = Py_BuildValue("(O)", other);
3089 if (args == NULL)
3090 res = NULL;
3091 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003092 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003093 Py_DECREF(args);
3094 }
3095 if (res != Py_NotImplemented) {
3096 if (res == NULL)
3097 return -2;
3098 c = PyInt_AsLong(res);
3099 Py_DECREF(res);
3100 if (c == -1 && PyErr_Occurred())
3101 return -2;
3102 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3103 }
3104 Py_DECREF(res);
3105 }
3106 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107}
3108
Guido van Rossumab3b0342001-09-18 20:38:53 +00003109/* This slot is published for the benefit of try_3way_compare in object.c */
3110int
3111_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003112{
3113 int c;
3114
Guido van Rossumab3b0342001-09-18 20:38:53 +00003115 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003116 c = half_compare(self, other);
3117 if (c <= 1)
3118 return c;
3119 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003120 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003121 c = half_compare(other, self);
3122 if (c < -1)
3123 return -2;
3124 if (c <= 1)
3125 return -c;
3126 }
3127 return (void *)self < (void *)other ? -1 :
3128 (void *)self > (void *)other ? 1 : 0;
3129}
3130
3131static PyObject *
3132slot_tp_repr(PyObject *self)
3133{
3134 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003135 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003136
Guido van Rossum60718732001-08-28 17:47:51 +00003137 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003138 if (func != NULL) {
3139 res = PyEval_CallObject(func, NULL);
3140 Py_DECREF(func);
3141 return res;
3142 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003143 PyErr_Clear();
3144 return PyString_FromFormat("<%s object at %p>",
3145 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003146}
3147
3148static PyObject *
3149slot_tp_str(PyObject *self)
3150{
3151 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003152 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003153
Guido van Rossum60718732001-08-28 17:47:51 +00003154 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003155 if (func != NULL) {
3156 res = PyEval_CallObject(func, NULL);
3157 Py_DECREF(func);
3158 return res;
3159 }
3160 else {
3161 PyErr_Clear();
3162 return slot_tp_repr(self);
3163 }
3164}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165
3166static long
3167slot_tp_hash(PyObject *self)
3168{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003169 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003170 static PyObject *hash_str, *eq_str, *cmp_str;
3171
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172 long h;
3173
Guido van Rossum60718732001-08-28 17:47:51 +00003174 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003175
3176 if (func != NULL) {
3177 res = PyEval_CallObject(func, NULL);
3178 Py_DECREF(func);
3179 if (res == NULL)
3180 return -1;
3181 h = PyInt_AsLong(res);
3182 }
3183 else {
3184 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003185 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003186 if (func == NULL) {
3187 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003188 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003189 }
3190 if (func != NULL) {
3191 Py_DECREF(func);
3192 PyErr_SetString(PyExc_TypeError, "unhashable type");
3193 return -1;
3194 }
3195 PyErr_Clear();
3196 h = _Py_HashPointer((void *)self);
3197 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003198 if (h == -1 && !PyErr_Occurred())
3199 h = -2;
3200 return h;
3201}
3202
3203static PyObject *
3204slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3205{
Guido van Rossum60718732001-08-28 17:47:51 +00003206 static PyObject *call_str;
3207 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208 PyObject *res;
3209
3210 if (meth == NULL)
3211 return NULL;
3212 res = PyObject_Call(meth, args, kwds);
3213 Py_DECREF(meth);
3214 return res;
3215}
3216
Guido van Rossum14a6f832001-10-17 13:59:09 +00003217/* There are two slot dispatch functions for tp_getattro.
3218
3219 - slot_tp_getattro() is used when __getattribute__ is overridden
3220 but no __getattr__ hook is present;
3221
3222 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3223
3224 The code in update_slot() and fixup_slot_dispatchers() always installs
3225 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3226 installs the simpler slot if necessary. */
3227
Tim Peters6d6c1a32001-08-02 04:15:00 +00003228static PyObject *
3229slot_tp_getattro(PyObject *self, PyObject *name)
3230{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003231 static PyObject *getattribute_str = NULL;
3232 return call_method(self, "__getattribute__", &getattribute_str,
3233 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003234}
3235
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003236static PyObject *
3237slot_tp_getattr_hook(PyObject *self, PyObject *name)
3238{
3239 PyTypeObject *tp = self->ob_type;
3240 PyObject *getattr, *getattribute, *res;
3241 static PyObject *getattribute_str = NULL;
3242 static PyObject *getattr_str = NULL;
3243
3244 if (getattr_str == NULL) {
3245 getattr_str = PyString_InternFromString("__getattr__");
3246 if (getattr_str == NULL)
3247 return NULL;
3248 }
3249 if (getattribute_str == NULL) {
3250 getattribute_str =
3251 PyString_InternFromString("__getattribute__");
3252 if (getattribute_str == NULL)
3253 return NULL;
3254 }
3255 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003256 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003257 /* No __getattr__ hook: use a simpler dispatcher */
3258 tp->tp_getattro = slot_tp_getattro;
3259 return slot_tp_getattro(self, name);
3260 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003261 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003262 if (getattribute == NULL ||
3263 (getattribute->ob_type == &PyWrapperDescr_Type &&
3264 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3265 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003266 res = PyObject_GenericGetAttr(self, name);
3267 else
3268 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003269 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003270 PyErr_Clear();
3271 res = PyObject_CallFunction(getattr, "OO", self, name);
3272 }
3273 return res;
3274}
3275
Tim Peters6d6c1a32001-08-02 04:15:00 +00003276static int
3277slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3278{
3279 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003280 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281
3282 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003283 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003284 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003286 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003287 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288 if (res == NULL)
3289 return -1;
3290 Py_DECREF(res);
3291 return 0;
3292}
3293
3294/* Map rich comparison operators to their __xx__ namesakes */
3295static char *name_op[] = {
3296 "__lt__",
3297 "__le__",
3298 "__eq__",
3299 "__ne__",
3300 "__gt__",
3301 "__ge__",
3302};
3303
3304static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003305half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003307 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003308 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003309
Guido van Rossum60718732001-08-28 17:47:51 +00003310 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003311 if (func == NULL) {
3312 PyErr_Clear();
3313 Py_INCREF(Py_NotImplemented);
3314 return Py_NotImplemented;
3315 }
3316 args = Py_BuildValue("(O)", other);
3317 if (args == NULL)
3318 res = NULL;
3319 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003320 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003321 Py_DECREF(args);
3322 }
3323 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324 return res;
3325}
3326
Guido van Rossumb8f63662001-08-15 23:57:02 +00003327/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3328static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3329
3330static PyObject *
3331slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3332{
3333 PyObject *res;
3334
3335 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3336 res = half_richcompare(self, other, op);
3337 if (res != Py_NotImplemented)
3338 return res;
3339 Py_DECREF(res);
3340 }
3341 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3342 res = half_richcompare(other, self, swapped_op[op]);
3343 if (res != Py_NotImplemented) {
3344 return res;
3345 }
3346 Py_DECREF(res);
3347 }
3348 Py_INCREF(Py_NotImplemented);
3349 return Py_NotImplemented;
3350}
3351
3352static PyObject *
3353slot_tp_iter(PyObject *self)
3354{
3355 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003356 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003357
Guido van Rossum60718732001-08-28 17:47:51 +00003358 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003359 if (func != NULL) {
3360 res = PyObject_CallObject(func, NULL);
3361 Py_DECREF(func);
3362 return res;
3363 }
3364 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003365 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003366 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003367 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003368 return NULL;
3369 }
3370 Py_DECREF(func);
3371 return PySeqIter_New(self);
3372}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373
3374static PyObject *
3375slot_tp_iternext(PyObject *self)
3376{
Guido van Rossum2730b132001-08-28 18:22:14 +00003377 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003378 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003379}
3380
Guido van Rossum1a493502001-08-17 16:47:50 +00003381static PyObject *
3382slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3383{
3384 PyTypeObject *tp = self->ob_type;
3385 PyObject *get;
3386 static PyObject *get_str = NULL;
3387
3388 if (get_str == NULL) {
3389 get_str = PyString_InternFromString("__get__");
3390 if (get_str == NULL)
3391 return NULL;
3392 }
3393 get = _PyType_Lookup(tp, get_str);
3394 if (get == NULL) {
3395 /* Avoid further slowdowns */
3396 if (tp->tp_descr_get == slot_tp_descr_get)
3397 tp->tp_descr_get = NULL;
3398 Py_INCREF(self);
3399 return self;
3400 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003401 if (obj == NULL)
3402 obj = Py_None;
3403 if (type == NULL)
3404 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003405 return PyObject_CallFunction(get, "OOO", self, obj, type);
3406}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003407
3408static int
3409slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3410{
Guido van Rossum2c252392001-08-24 10:13:31 +00003411 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003412 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003413
3414 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003415 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003416 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003417 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003418 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003419 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420 if (res == NULL)
3421 return -1;
3422 Py_DECREF(res);
3423 return 0;
3424}
3425
3426static int
3427slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3428{
Guido van Rossum60718732001-08-28 17:47:51 +00003429 static PyObject *init_str;
3430 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431 PyObject *res;
3432
3433 if (meth == NULL)
3434 return -1;
3435 res = PyObject_Call(meth, args, kwds);
3436 Py_DECREF(meth);
3437 if (res == NULL)
3438 return -1;
3439 Py_DECREF(res);
3440 return 0;
3441}
3442
3443static PyObject *
3444slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3445{
3446 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3447 PyObject *newargs, *x;
3448 int i, n;
3449
3450 if (func == NULL)
3451 return NULL;
3452 assert(PyTuple_Check(args));
3453 n = PyTuple_GET_SIZE(args);
3454 newargs = PyTuple_New(n+1);
3455 if (newargs == NULL)
3456 return NULL;
3457 Py_INCREF(type);
3458 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3459 for (i = 0; i < n; i++) {
3460 x = PyTuple_GET_ITEM(args, i);
3461 Py_INCREF(x);
3462 PyTuple_SET_ITEM(newargs, i+1, x);
3463 }
3464 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003465 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003466 Py_DECREF(func);
3467 return x;
3468}
3469
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003470
3471/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3472 functions. The offsets here are relative to the 'etype' structure, which
3473 incorporates the additional structures used for numbers, sequences and
3474 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3475 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3476 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3477
Guido van Rossum6d204072001-10-21 00:44:31 +00003478typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003479
3480#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003481#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003482#undef ETSLOT
3483#undef SQSLOT
3484#undef MPSLOT
3485#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003486#undef UNSLOT
3487#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003488#undef BINSLOT
3489#undef RBINSLOT
3490
Guido van Rossum6d204072001-10-21 00:44:31 +00003491#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3492 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003493#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3494 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3495 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003496#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3497 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3498#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3499 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3500#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3501 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3502#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3503 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3504#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3505 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3506 "x." NAME "() <==> " DOC)
3507#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3508 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3509 "x." NAME "(y) <==> x" DOC "y")
3510#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3511 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3512 "x." NAME "(y) <==> x" DOC "y")
3513#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3514 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3515 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003516
3517static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003518 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3519 "x.__len__() <==> len(x)"),
3520 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3521 "x.__add__(y) <==> x+y"),
3522 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3523 "x.__mul__(n) <==> x*n"),
3524 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3525 "x.__rmul__(n) <==> n*x"),
3526 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3527 "x.__getitem__(y) <==> x[y]"),
3528 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3529 "x.__getslice__(i, j) <==> x[i:j]"),
3530 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3531 "x.__setitem__(i, y) <==> x[i]=y"),
3532 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3533 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003534 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003535 wrap_intintobjargproc,
3536 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3537 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3538 "x.__delslice__(i, j) <==> del x[i:j]"),
3539 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3540 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003541 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003542 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003543 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003544 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003545
Guido van Rossum6d204072001-10-21 00:44:31 +00003546 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3547 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003548 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003549 wrap_binaryfunc,
3550 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003551 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003552 wrap_objobjargproc,
3553 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003554 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003555 wrap_delitem,
3556 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003557
Guido van Rossum6d204072001-10-21 00:44:31 +00003558 BINSLOT("__add__", nb_add, slot_nb_add,
3559 "+"),
3560 RBINSLOT("__radd__", nb_add, slot_nb_add,
3561 "+"),
3562 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3563 "-"),
3564 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3565 "-"),
3566 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3567 "*"),
3568 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3569 "*"),
3570 BINSLOT("__div__", nb_divide, slot_nb_divide,
3571 "/"),
3572 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3573 "/"),
3574 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3575 "%"),
3576 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3577 "%"),
3578 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3579 "divmod(x, y)"),
3580 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3581 "divmod(y, x)"),
3582 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3583 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3584 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3585 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3586 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3587 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3588 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3589 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003590 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003591 "x != 0"),
3592 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3593 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3594 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3595 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3596 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3597 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3598 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3599 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3600 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3601 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3602 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3603 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3604 "x.__coerce__(y) <==> coerce(x, y)"),
3605 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3606 "int(x)"),
3607 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3608 "long(x)"),
3609 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3610 "float(x)"),
3611 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3612 "oct(x)"),
3613 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3614 "hex(x)"),
3615 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3616 wrap_binaryfunc, "+"),
3617 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3618 wrap_binaryfunc, "-"),
3619 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3620 wrap_binaryfunc, "*"),
3621 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3622 wrap_binaryfunc, "/"),
3623 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3624 wrap_binaryfunc, "%"),
3625 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3626 wrap_ternaryfunc, "**"),
3627 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3628 wrap_binaryfunc, "<<"),
3629 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3630 wrap_binaryfunc, ">>"),
3631 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3632 wrap_binaryfunc, "&"),
3633 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3634 wrap_binaryfunc, "^"),
3635 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3636 wrap_binaryfunc, "|"),
3637 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3638 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3639 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3640 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3641 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3642 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3643 IBSLOT("__itruediv__", nb_inplace_true_divide,
3644 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003645
Guido van Rossum6d204072001-10-21 00:44:31 +00003646 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3647 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003648 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003649 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3650 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003651 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003652 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3653 "x.__cmp__(y) <==> cmp(x,y)"),
3654 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3655 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003656 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3657 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003658 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003659 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3660 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3661 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3662 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3663 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3664 "x.__setattr__('name', value) <==> x.name = value"),
3665 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3666 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3667 "x.__delattr__('name') <==> del x.name"),
3668 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3669 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3670 "x.__lt__(y) <==> x<y"),
3671 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3672 "x.__le__(y) <==> x<=y"),
3673 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3674 "x.__eq__(y) <==> x==y"),
3675 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3676 "x.__ne__(y) <==> x!=y"),
3677 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3678 "x.__gt__(y) <==> x>y"),
3679 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3680 "x.__ge__(y) <==> x>=y"),
3681 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3682 "x.__iter__() <==> iter(x)"),
3683 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3684 "x.next() -> the next value, or raise StopIteration"),
3685 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3686 "descr.__get__(obj[, type]) -> value"),
3687 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3688 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003689 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003690 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003691 "see x.__class__.__doc__ for signature",
3692 PyWrapperFlag_KEYWORDS),
3693 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003694 {NULL}
3695};
3696
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003697static void **
3698slotptr(PyTypeObject *type, int offset)
3699{
3700 char *ptr;
3701
3702 assert(offset >= 0);
3703 assert(offset < offsetof(etype, as_buffer));
3704 if (offset >= offsetof(etype, as_mapping)) {
3705 ptr = (void *)type->tp_as_mapping;
3706 offset -= offsetof(etype, as_mapping);
3707 }
3708 else if (offset >= offsetof(etype, as_sequence)) {
3709 ptr = (void *)type->tp_as_sequence;
3710 offset -= offsetof(etype, as_sequence);
3711 }
3712 else if (offset >= offsetof(etype, as_number)) {
3713 ptr = (void *)type->tp_as_number;
3714 offset -= offsetof(etype, as_number);
3715 }
3716 else {
3717 ptr = (void *)type;
3718 }
3719 if (ptr != NULL)
3720 ptr += offset;
3721 return (void **)ptr;
3722}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003723
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003724staticforward int recurse_down_subclasses(PyTypeObject *type,
3725 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003726
3727static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003728update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003729{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003730 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003731
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003732 for (pp = pp0; *pp; pp++) {
3733 slotdef *p = *pp;
3734 PyObject *descr;
3735 PyWrapperDescrObject *d;
3736 void *generic = NULL, *specific = NULL;
3737 int use_generic = 0;
3738 int offset = p->offset;
3739 void **ptr = slotptr(type, offset);
3740 if (ptr == NULL)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003741 continue;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003742 do {
3743 descr = _PyType_Lookup(type, p->name_strobj);
3744 if (descr == NULL)
3745 continue;
3746 generic = p->function;
3747 if (descr->ob_type == &PyWrapperDescr_Type) {
3748 d = (PyWrapperDescrObject *)descr;
3749 if (d->d_base->wrapper == p->wrapper &&
3750 PyType_IsSubtype(type, d->d_type)) {
3751 if (specific == NULL ||
3752 specific == d->d_wrapped)
3753 specific = d->d_wrapped;
3754 else
3755 use_generic = 1;
3756 }
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003757 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003758 else
3759 use_generic = 1;
3760 } while ((++p)->offset == offset);
3761 if (specific && !use_generic)
3762 *ptr = specific;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003763 else
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003764 *ptr = generic;
3765 }
3766 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003767}
3768
3769static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003770recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003771{
3772 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003773 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003774 int i, n;
3775
3776 subclasses = type->tp_subclasses;
3777 if (subclasses == NULL)
3778 return 0;
3779 assert(PyList_Check(subclasses));
3780 n = PyList_GET_SIZE(subclasses);
3781 for (i = 0; i < n; i++) {
3782 ref = PyList_GET_ITEM(subclasses, i);
3783 assert(PyWeakref_CheckRef(ref));
3784 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3785 if (subclass == NULL)
3786 continue;
3787 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003788 /* Avoid recursing down into unaffected classes */
3789 dict = subclass->tp_dict;
3790 if (dict != NULL && PyDict_Check(dict) &&
3791 PyDict_GetItem(dict, name) != NULL)
3792 continue;
3793 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003794 return -1;
3795 }
3796 return 0;
3797}
3798
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003799static int
3800slotdef_cmp(const void *aa, const void *bb)
3801{
3802 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3803 int c = a->offset - b->offset;
3804 if (c != 0)
3805 return c;
3806 else
3807 return a - b;
3808}
3809
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003810static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003811init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003812{
3813 slotdef *p;
3814 static int initialized = 0;
3815
3816 if (initialized)
3817 return;
3818 for (p = slotdefs; p->name; p++) {
3819 p->name_strobj = PyString_InternFromString(p->name);
3820 if (!p->name_strobj)
3821 Py_FatalError("XXX ouch");
3822 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003823 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3824 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003825 initialized = 1;
3826}
3827
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003828static int
3829update_slot(PyTypeObject *type, PyObject *name)
3830{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003831 slotdef *ptrs[10];
3832 slotdef *p;
3833 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003834 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003835
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003836 init_slotdefs();
3837 pp = ptrs;
3838 for (p = slotdefs; p->name; p++) {
3839 /* XXX assume name is interned! */
3840 if (p->name_strobj == name)
3841 *pp++ = p;
3842 }
3843 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003844 for (pp = ptrs; *pp; pp++) {
3845 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003846 offset = p->offset;
3847 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003848 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003849 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003850 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003851 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003852}
3853
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003855fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003857 slotdef *p;
3858 PyObject *mro, *descr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003859 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003860 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003861 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003862 void *generic, *specific;
3863 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003865 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003866 mro = type->tp_mro;
3867 assert(PyTuple_Check(mro));
3868 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003869 for (p = slotdefs; p->name; ) {
3870 offset = p->offset;
3871 ptr = slotptr(type, offset);
3872 if (!ptr) {
3873 do {
3874 ++p;
3875 } while (p->offset == offset);
3876 continue;
3877 }
3878 generic = specific = NULL;
3879 use_generic = 0;
3880 do {
3881 descr = NULL;
3882 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003883 PyObject *b = PyTuple_GET_ITEM(mro, i);
3884 PyObject *dict = NULL;
3885 if (PyType_Check(b))
3886 dict = ((PyTypeObject *)b)->tp_dict;
3887 else if (PyClass_Check(b))
3888 dict = ((PyClassObject *)b)->cl_dict;
3889 if (dict != NULL) {
3890 descr = PyDict_GetItem(
3891 dict, p->name_strobj);
3892 if (descr != NULL)
3893 break;
3894 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003895 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003896 if (descr == NULL)
3897 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003898 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003899 if (descr->ob_type == &PyWrapperDescr_Type) {
3900 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003901 if (d->d_base->wrapper == p->wrapper &&
Guido van Rossumcaf59042001-10-17 07:15:43 +00003902 PyType_IsSubtype(type, d->d_type))
3903 {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003904 if (specific == NULL ||
Guido van Rossumcaf59042001-10-17 07:15:43 +00003905 specific == d->d_wrapped)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003906 specific = d->d_wrapped;
3907 else
3908 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003909 }
3910 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003911 else
3912 use_generic = 1;
3913 } while ((++p)->offset == offset);
3914 if (specific && !use_generic)
3915 *ptr = specific;
3916 else
3917 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003918 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003919}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003920
Guido van Rossum6d204072001-10-21 00:44:31 +00003921/* This function is called by PyType_Ready() to populate the type's
3922 dictionary with method descriptors for function slots. For each
3923 function slot (like tp_repr) that's defined in the type, one or
3924 more corresponding descriptors are added in the type's tp_dict
3925 dictionary under the appropriate name (like __repr__). Some
3926 function slots cause more than one descriptor to be added (for
3927 example, the nb_add slot adds both __add__ and __radd__
3928 descriptors) and some function slots compete for the same
3929 descriptor (for example both sq_item and mp_subscript generate a
3930 __getitem__ descriptor). This only adds new descriptors and
3931 doesn't overwrite entries in tp_dict that were previously
3932 defined. The descriptors contain a reference to the C function
3933 they must call, so that it's safe if they are copied into a
3934 subtype's __dict__ and the subtype has a different C function in
3935 its slot -- calling the method defined by the descriptor will call
3936 the C function that was used to create it, rather than the C
3937 function present in the slot when it is called. (This is important
3938 because a subtype may have a C function in the slot that calls the
3939 method from the dictionary, and we want to avoid infinite recursion
3940 here.) */
3941
3942static int
3943add_operators(PyTypeObject *type)
3944{
3945 PyObject *dict = type->tp_dict;
3946 slotdef *p;
3947 PyObject *descr;
3948 void **ptr;
3949
3950 init_slotdefs();
3951 for (p = slotdefs; p->name; p++) {
3952 if (p->wrapper == NULL)
3953 continue;
3954 ptr = slotptr(type, p->offset);
3955 if (!ptr || !*ptr)
3956 continue;
3957 if (PyDict_GetItem(dict, p->name_strobj))
3958 continue;
3959 descr = PyDescr_NewWrapper(type, p, *ptr);
3960 if (descr == NULL)
3961 return -1;
3962 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
3963 return -1;
3964 Py_DECREF(descr);
3965 }
3966 if (type->tp_new != NULL) {
3967 if (add_tp_new_wrapper(type) < 0)
3968 return -1;
3969 }
3970 return 0;
3971}
3972
Guido van Rossum705f0f52001-08-24 16:47:00 +00003973
3974/* Cooperative 'super' */
3975
3976typedef struct {
3977 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003978 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003979 PyObject *obj;
3980} superobject;
3981
Guido van Rossum6f799372001-09-20 20:46:19 +00003982static PyMemberDef super_members[] = {
3983 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3984 "the class invoking super()"},
3985 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3986 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003987 {0}
3988};
3989
Guido van Rossum705f0f52001-08-24 16:47:00 +00003990static void
3991super_dealloc(PyObject *self)
3992{
3993 superobject *su = (superobject *)self;
3994
Guido van Rossum048eb752001-10-02 21:24:57 +00003995 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003996 Py_XDECREF(su->obj);
3997 Py_XDECREF(su->type);
3998 self->ob_type->tp_free(self);
3999}
4000
4001static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004002super_repr(PyObject *self)
4003{
4004 superobject *su = (superobject *)self;
4005
4006 if (su->obj)
4007 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004008 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004009 su->type ? su->type->tp_name : "NULL",
4010 su->obj->ob_type->tp_name);
4011 else
4012 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004013 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004014 su->type ? su->type->tp_name : "NULL");
4015}
4016
4017static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004018super_getattro(PyObject *self, PyObject *name)
4019{
4020 superobject *su = (superobject *)self;
4021
4022 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004023 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004024 descrgetfunc f;
4025 int i, n;
4026
Guido van Rossume705ef12001-08-29 15:47:06 +00004027 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004028 if (mro == NULL)
4029 n = 0;
4030 else {
4031 assert(PyTuple_Check(mro));
4032 n = PyTuple_GET_SIZE(mro);
4033 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004034 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004035 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004036 break;
4037 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004038 if (i >= n && PyType_Check(su->obj)) {
4039 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004040 if (mro == NULL)
4041 n = 0;
4042 else {
4043 assert(PyTuple_Check(mro));
4044 n = PyTuple_GET_SIZE(mro);
4045 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004046 for (i = 0; i < n; i++) {
4047 if ((PyObject *)(su->type) ==
4048 PyTuple_GET_ITEM(mro, i))
4049 break;
4050 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004051 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004052 i++;
4053 res = NULL;
4054 for (; i < n; i++) {
4055 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004056 if (PyType_Check(tmp))
4057 dict = ((PyTypeObject *)tmp)->tp_dict;
4058 else if (PyClass_Check(tmp))
4059 dict = ((PyClassObject *)tmp)->cl_dict;
4060 else
4061 continue;
4062 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004063 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004064 Py_INCREF(res);
4065 f = res->ob_type->tp_descr_get;
4066 if (f != NULL) {
4067 tmp = f(res, su->obj, res);
4068 Py_DECREF(res);
4069 res = tmp;
4070 }
4071 return res;
4072 }
4073 }
4074 }
4075 return PyObject_GenericGetAttr(self, name);
4076}
4077
Guido van Rossum5b443c62001-12-03 15:38:28 +00004078static int
4079supercheck(PyTypeObject *type, PyObject *obj)
4080{
4081 if (!PyType_IsSubtype(obj->ob_type, type) &&
4082 !(PyType_Check(obj) &&
4083 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4084 PyErr_SetString(PyExc_TypeError,
4085 "super(type, obj): "
4086 "obj must be an instance or subtype of type");
4087 return -1;
4088 }
4089 else
4090 return 0;
4091}
4092
Guido van Rossum705f0f52001-08-24 16:47:00 +00004093static PyObject *
4094super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4095{
4096 superobject *su = (superobject *)self;
4097 superobject *new;
4098
4099 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4100 /* Not binding to an object, or already bound */
4101 Py_INCREF(self);
4102 return self;
4103 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004104 if (su->ob_type != &PySuper_Type)
4105 /* If su is an instance of a subclass of super,
4106 call its type */
4107 return PyObject_CallFunction((PyObject *)su->ob_type,
4108 "OO", su->type, obj);
4109 else {
4110 /* Inline the common case */
4111 if (supercheck(su->type, obj) < 0)
4112 return NULL;
4113 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4114 NULL, NULL);
4115 if (new == NULL)
4116 return NULL;
4117 Py_INCREF(su->type);
4118 Py_INCREF(obj);
4119 new->type = su->type;
4120 new->obj = obj;
4121 return (PyObject *)new;
4122 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004123}
4124
4125static int
4126super_init(PyObject *self, PyObject *args, PyObject *kwds)
4127{
4128 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004129 PyTypeObject *type;
4130 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004131
4132 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4133 return -1;
4134 if (obj == Py_None)
4135 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004136 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004137 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004138 Py_INCREF(type);
4139 Py_XINCREF(obj);
4140 su->type = type;
4141 su->obj = obj;
4142 return 0;
4143}
4144
4145static char super_doc[] =
4146"super(type) -> unbound super object\n"
4147"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004148"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004149"Typical use to call a cooperative superclass method:\n"
4150"class C(B):\n"
4151" def meth(self, arg):\n"
4152" super(C, self).meth(arg)";
4153
Guido van Rossum048eb752001-10-02 21:24:57 +00004154static int
4155super_traverse(PyObject *self, visitproc visit, void *arg)
4156{
4157 superobject *su = (superobject *)self;
4158 int err;
4159
4160#define VISIT(SLOT) \
4161 if (SLOT) { \
4162 err = visit((PyObject *)(SLOT), arg); \
4163 if (err) \
4164 return err; \
4165 }
4166
4167 VISIT(su->obj);
4168 VISIT(su->type);
4169
4170#undef VISIT
4171
4172 return 0;
4173}
4174
Guido van Rossum705f0f52001-08-24 16:47:00 +00004175PyTypeObject PySuper_Type = {
4176 PyObject_HEAD_INIT(&PyType_Type)
4177 0, /* ob_size */
4178 "super", /* tp_name */
4179 sizeof(superobject), /* tp_basicsize */
4180 0, /* tp_itemsize */
4181 /* methods */
4182 super_dealloc, /* tp_dealloc */
4183 0, /* tp_print */
4184 0, /* tp_getattr */
4185 0, /* tp_setattr */
4186 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004187 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004188 0, /* tp_as_number */
4189 0, /* tp_as_sequence */
4190 0, /* tp_as_mapping */
4191 0, /* tp_hash */
4192 0, /* tp_call */
4193 0, /* tp_str */
4194 super_getattro, /* tp_getattro */
4195 0, /* tp_setattro */
4196 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004197 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4198 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004199 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004200 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004201 0, /* tp_clear */
4202 0, /* tp_richcompare */
4203 0, /* tp_weaklistoffset */
4204 0, /* tp_iter */
4205 0, /* tp_iternext */
4206 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004207 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004208 0, /* tp_getset */
4209 0, /* tp_base */
4210 0, /* tp_dict */
4211 super_descr_get, /* tp_descr_get */
4212 0, /* tp_descr_set */
4213 0, /* tp_dictoffset */
4214 super_init, /* tp_init */
4215 PyType_GenericAlloc, /* tp_alloc */
4216 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004217 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004218};