blob: c37e54f900f8fd95ca79af7d4e81c2746438a876 [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},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000047 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000048 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
Guido van Rossum3926a632001-09-25 16:25:58 +000056static int
57type_set_module(PyTypeObject *type, PyObject *value, void *context)
58{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000059 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000060 strrchr(type->tp_name, '.')) {
61 PyErr_Format(PyExc_TypeError,
62 "can't set %s.__module__", type->tp_name);
63 return -1;
64 }
65 if (!value) {
66 PyErr_Format(PyExc_TypeError,
67 "can't delete %s.__module__", type->tp_name);
68 return -1;
69 }
70 return PyDict_SetItemString(type->tp_dict, "__module__", value);
71}
72
Tim Peters6d6c1a32001-08-02 04:15:00 +000073static PyObject *
74type_dict(PyTypeObject *type, void *context)
75{
76 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 Py_INCREF(Py_None);
78 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000080 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000081}
82
Guido van Rossum32d34c82001-09-20 21:45:26 +000083PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000084 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +000085 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000086 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 {0}
88};
89
Martin v. Löwis0163d6d2001-06-09 07:34:05 +000090static int
91type_compare(PyObject *v, PyObject *w)
92{
93 /* This is called with type objects only. So we
94 can just compare the addresses. */
95 Py_uintptr_t vv = (Py_uintptr_t)v;
96 Py_uintptr_t ww = (Py_uintptr_t)w;
97 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
98}
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000103 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000104 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000105
106 mod = type_module(type, NULL);
107 if (mod == NULL)
108 PyErr_Clear();
109 else if (!PyString_Check(mod)) {
110 Py_DECREF(mod);
111 mod = NULL;
112 }
113 name = type_name(type, NULL);
114 if (name == NULL)
115 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000117 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
118 kind = "class";
119 else
120 kind = "type";
121
Barry Warsaw7ce36942001-08-24 18:34:26 +0000122 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000123 rtn = PyString_FromFormat("<%s '%s.%s'>",
124 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000125 PyString_AS_STRING(mod),
126 PyString_AS_STRING(name));
127 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000128 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000129 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000130
Guido van Rossumc3542212001-08-16 09:18:56 +0000131 Py_XDECREF(mod);
132 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134}
135
Tim Peters6d6c1a32001-08-02 04:15:00 +0000136static PyObject *
137type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
138{
139 PyObject *obj;
140
141 if (type->tp_new == NULL) {
142 PyErr_Format(PyExc_TypeError,
143 "cannot create '%.100s' instances",
144 type->tp_name);
145 return NULL;
146 }
147
Tim Peters3f996e72001-09-13 19:18:27 +0000148 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000149 if (obj != NULL) {
150 type = obj->ob_type;
151 if (type->tp_init != NULL &&
152 type->tp_init(obj, args, kwds) < 0) {
153 Py_DECREF(obj);
154 obj = NULL;
155 }
156 }
157 return obj;
158}
159
160PyObject *
161PyType_GenericAlloc(PyTypeObject *type, int nitems)
162{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000163 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000164 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000165
166 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000167 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000168 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000169 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000170
Neil Schemenauerc806c882001-08-29 23:54:54 +0000171 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000172 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000173
Neil Schemenauerc806c882001-08-29 23:54:54 +0000174 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000175
Tim Peters6d6c1a32001-08-02 04:15:00 +0000176 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
177 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000178
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 if (type->tp_itemsize == 0)
180 PyObject_INIT(obj, type);
181 else
182 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000183
Tim Peters6d6c1a32001-08-02 04:15:00 +0000184 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000185 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000186 return obj;
187}
188
189PyObject *
190PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
191{
192 return type->tp_alloc(type, 0);
193}
194
Guido van Rossum9475a232001-10-05 20:51:39 +0000195/* Helpers for subtyping */
196
197static int
198subtype_traverse(PyObject *self, visitproc visit, void *arg)
199{
200 PyTypeObject *type, *base;
201 traverseproc f;
202 int err;
203
204 /* Find the nearest base with a different tp_traverse */
205 type = self->ob_type;
206 base = type->tp_base;
207 while ((f = base->tp_traverse) == subtype_traverse) {
208 base = base->tp_base;
209 assert(base);
210 }
211
212 if (type->tp_dictoffset != base->tp_dictoffset) {
213 PyObject **dictptr = _PyObject_GetDictPtr(self);
214 if (dictptr && *dictptr) {
215 err = visit(*dictptr, arg);
216 if (err)
217 return err;
218 }
219 }
220
221 if (f)
222 return f(self, visit, arg);
223 return 0;
224}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000225
226static void
227subtype_dealloc(PyObject *self)
228{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000229 PyTypeObject *type, *base;
230 destructor f;
231
232 /* This exists so we can DECREF self->ob_type */
233
234 /* Find the nearest base with a different tp_dealloc */
235 type = self->ob_type;
236 base = type->tp_base;
237 while ((f = base->tp_dealloc) == subtype_dealloc) {
238 base = base->tp_base;
239 assert(base);
240 }
241
242 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000243 if (type->tp_dictoffset && !base->tp_dictoffset) {
244 PyObject **dictptr = _PyObject_GetDictPtr(self);
245 if (dictptr != NULL) {
246 PyObject *dict = *dictptr;
247 if (dict != NULL) {
248 Py_DECREF(dict);
249 *dictptr = NULL;
250 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000251 }
252 }
253
Guido van Rossum9676b222001-08-17 20:32:36 +0000254 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000255 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000256 PyObject_ClearWeakRefs(self);
257
Tim Peters6d6c1a32001-08-02 04:15:00 +0000258 /* Finalize GC if the base doesn't do GC and we do */
259 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000260 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000261
262 /* Call the base tp_dealloc() */
263 assert(f);
264 f(self);
265
266 /* Can't reference self beyond this point */
267 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
268 Py_DECREF(type);
269 }
270}
271
Tim Peters6d6c1a32001-08-02 04:15:00 +0000272staticforward PyTypeObject *solid_base(PyTypeObject *type);
273
274typedef struct {
275 PyTypeObject type;
276 PyNumberMethods as_number;
277 PySequenceMethods as_sequence;
278 PyMappingMethods as_mapping;
279 PyBufferProcs as_buffer;
280 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000281 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000282} etype;
283
284/* type test with subclassing support */
285
286int
287PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
288{
289 PyObject *mro;
290
Guido van Rossum9478d072001-09-07 18:52:13 +0000291 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
292 return b == a || b == &PyBaseObject_Type;
293
Tim Peters6d6c1a32001-08-02 04:15:00 +0000294 mro = a->tp_mro;
295 if (mro != NULL) {
296 /* Deal with multiple inheritance without recursion
297 by walking the MRO tuple */
298 int i, n;
299 assert(PyTuple_Check(mro));
300 n = PyTuple_GET_SIZE(mro);
301 for (i = 0; i < n; i++) {
302 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
303 return 1;
304 }
305 return 0;
306 }
307 else {
308 /* a is not completely initilized yet; follow tp_base */
309 do {
310 if (a == b)
311 return 1;
312 a = a->tp_base;
313 } while (a != NULL);
314 return b == &PyBaseObject_Type;
315 }
316}
317
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000318/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000319 without looking in the instance dictionary
320 (so we can't use PyObject_GetAttr) but still binding
321 it to the instance. The arguments are the object,
322 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000323 static variable used to cache the interned Python string.
324
325 Two variants:
326
327 - lookup_maybe() returns NULL without raising an exception
328 when the _PyType_Lookup() call fails;
329
330 - lookup_method() always raises an exception upon errors.
331*/
Guido van Rossum60718732001-08-28 17:47:51 +0000332
333static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000334lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000335{
336 PyObject *res;
337
338 if (*attrobj == NULL) {
339 *attrobj = PyString_InternFromString(attrstr);
340 if (*attrobj == NULL)
341 return NULL;
342 }
343 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000344 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000345 descrgetfunc f;
346 if ((f = res->ob_type->tp_descr_get) == NULL)
347 Py_INCREF(res);
348 else
349 res = f(res, self, (PyObject *)(self->ob_type));
350 }
351 return res;
352}
353
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000354static PyObject *
355lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
356{
357 PyObject *res = lookup_maybe(self, attrstr, attrobj);
358 if (res == NULL && !PyErr_Occurred())
359 PyErr_SetObject(PyExc_AttributeError, *attrobj);
360 return res;
361}
362
Guido van Rossum2730b132001-08-28 18:22:14 +0000363/* A variation of PyObject_CallMethod that uses lookup_method()
364 instead of PyObject_GetAttrString(). This uses the same convention
365 as lookup_method to cache the interned name string object. */
366
367PyObject *
368call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
369{
370 va_list va;
371 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000372 va_start(va, format);
373
Guido van Rossumda21c012001-10-03 00:50:18 +0000374 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000375 if (func == NULL) {
376 va_end(va);
377 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000378 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000379 return NULL;
380 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000381
382 if (format && *format)
383 args = Py_VaBuildValue(format, va);
384 else
385 args = PyTuple_New(0);
386
387 va_end(va);
388
389 if (args == NULL)
390 return NULL;
391
392 assert(PyTuple_Check(args));
393 retval = PyObject_Call(func, args, NULL);
394
395 Py_DECREF(args);
396 Py_DECREF(func);
397
398 return retval;
399}
400
401/* Clone of call_method() that returns NotImplemented when the lookup fails. */
402
403PyObject *
404call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
405{
406 va_list va;
407 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000408 va_start(va, format);
409
Guido van Rossumda21c012001-10-03 00:50:18 +0000410 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000411 if (func == NULL) {
412 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000413 if (!PyErr_Occurred()) {
414 Py_INCREF(Py_NotImplemented);
415 return Py_NotImplemented;
416 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000417 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000418 }
419
420 if (format && *format)
421 args = Py_VaBuildValue(format, va);
422 else
423 args = PyTuple_New(0);
424
425 va_end(va);
426
Guido van Rossum717ce002001-09-14 16:58:08 +0000427 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000428 return NULL;
429
Guido van Rossum717ce002001-09-14 16:58:08 +0000430 assert(PyTuple_Check(args));
431 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000432
433 Py_DECREF(args);
434 Py_DECREF(func);
435
436 return retval;
437}
438
Tim Peters6d6c1a32001-08-02 04:15:00 +0000439/* Method resolution order algorithm from "Putting Metaclasses to Work"
440 by Forman and Danforth (Addison-Wesley 1999). */
441
442static int
443conservative_merge(PyObject *left, PyObject *right)
444{
445 int left_size;
446 int right_size;
447 int i, j, r, ok;
448 PyObject *temp, *rr;
449
450 assert(PyList_Check(left));
451 assert(PyList_Check(right));
452
453 again:
454 left_size = PyList_GET_SIZE(left);
455 right_size = PyList_GET_SIZE(right);
456 for (i = 0; i < left_size; i++) {
457 for (j = 0; j < right_size; j++) {
458 if (PyList_GET_ITEM(left, i) ==
459 PyList_GET_ITEM(right, j)) {
460 /* found a merge point */
461 temp = PyList_New(0);
462 if (temp == NULL)
463 return -1;
464 for (r = 0; r < j; r++) {
465 rr = PyList_GET_ITEM(right, r);
466 ok = PySequence_Contains(left, rr);
467 if (ok < 0) {
468 Py_DECREF(temp);
469 return -1;
470 }
471 if (!ok) {
472 ok = PyList_Append(temp, rr);
473 if (ok < 0) {
474 Py_DECREF(temp);
475 return -1;
476 }
477 }
478 }
479 ok = PyList_SetSlice(left, i, i, temp);
480 Py_DECREF(temp);
481 if (ok < 0)
482 return -1;
483 ok = PyList_SetSlice(right, 0, j+1, NULL);
484 if (ok < 0)
485 return -1;
486 goto again;
487 }
488 }
489 }
490 return PyList_SetSlice(left, left_size, left_size, right);
491}
492
493static int
494serious_order_disagreements(PyObject *left, PyObject *right)
495{
496 return 0; /* XXX later -- for now, we cheat: "don't do that" */
497}
498
499static PyObject *
500mro_implementation(PyTypeObject *type)
501{
502 int i, n, ok;
503 PyObject *bases, *result;
504
505 bases = type->tp_bases;
506 n = PyTuple_GET_SIZE(bases);
507 result = Py_BuildValue("[O]", (PyObject *)type);
508 if (result == NULL)
509 return NULL;
510 for (i = 0; i < n; i++) {
511 PyTypeObject *base =
512 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
513 PyObject *parentMRO = PySequence_List(base->tp_mro);
514 if (parentMRO == NULL) {
515 Py_DECREF(result);
516 return NULL;
517 }
518 if (serious_order_disagreements(result, parentMRO)) {
519 Py_DECREF(result);
520 return NULL;
521 }
522 ok = conservative_merge(result, parentMRO);
523 Py_DECREF(parentMRO);
524 if (ok < 0) {
525 Py_DECREF(result);
526 return NULL;
527 }
528 }
529 return result;
530}
531
532static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000533mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000534{
535 PyTypeObject *type = (PyTypeObject *)self;
536
Tim Peters6d6c1a32001-08-02 04:15:00 +0000537 return mro_implementation(type);
538}
539
540static int
541mro_internal(PyTypeObject *type)
542{
543 PyObject *mro, *result, *tuple;
544
545 if (type->ob_type == &PyType_Type) {
546 result = mro_implementation(type);
547 }
548 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000549 static PyObject *mro_str;
550 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000551 if (mro == NULL)
552 return -1;
553 result = PyObject_CallObject(mro, NULL);
554 Py_DECREF(mro);
555 }
556 if (result == NULL)
557 return -1;
558 tuple = PySequence_Tuple(result);
559 Py_DECREF(result);
560 type->tp_mro = tuple;
561 return 0;
562}
563
564
565/* Calculate the best base amongst multiple base classes.
566 This is the first one that's on the path to the "solid base". */
567
568static PyTypeObject *
569best_base(PyObject *bases)
570{
571 int i, n;
572 PyTypeObject *base, *winner, *candidate, *base_i;
573
574 assert(PyTuple_Check(bases));
575 n = PyTuple_GET_SIZE(bases);
576 assert(n > 0);
577 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
578 winner = &PyBaseObject_Type;
579 for (i = 0; i < n; i++) {
580 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
581 if (!PyType_Check((PyObject *)base_i)) {
582 PyErr_SetString(
583 PyExc_TypeError,
584 "bases must be types");
585 return NULL;
586 }
587 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000588 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 return NULL;
590 }
591 candidate = solid_base(base_i);
592 if (PyType_IsSubtype(winner, candidate))
593 ;
594 else if (PyType_IsSubtype(candidate, winner)) {
595 winner = candidate;
596 base = base_i;
597 }
598 else {
599 PyErr_SetString(
600 PyExc_TypeError,
601 "multiple bases have "
602 "instance lay-out conflict");
603 return NULL;
604 }
605 }
606 assert(base != NULL);
607 return base;
608}
609
610static int
611extra_ivars(PyTypeObject *type, PyTypeObject *base)
612{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000613 size_t t_size = type->tp_basicsize;
614 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000615
Guido van Rossum9676b222001-08-17 20:32:36 +0000616 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000617 if (type->tp_itemsize || base->tp_itemsize) {
618 /* If itemsize is involved, stricter rules */
619 return t_size != b_size ||
620 type->tp_itemsize != base->tp_itemsize;
621 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000622 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
623 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
624 t_size -= sizeof(PyObject *);
625 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
626 type->tp_dictoffset + sizeof(PyObject *) == t_size)
627 t_size -= sizeof(PyObject *);
628
629 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000630}
631
632static PyTypeObject *
633solid_base(PyTypeObject *type)
634{
635 PyTypeObject *base;
636
637 if (type->tp_base)
638 base = solid_base(type->tp_base);
639 else
640 base = &PyBaseObject_Type;
641 if (extra_ivars(type, base))
642 return type;
643 else
644 return base;
645}
646
647staticforward void object_dealloc(PyObject *);
648staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000649staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000650staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000651
652static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000653subtype_dict(PyObject *obj, void *context)
654{
655 PyObject **dictptr = _PyObject_GetDictPtr(obj);
656 PyObject *dict;
657
658 if (dictptr == NULL) {
659 PyErr_SetString(PyExc_AttributeError,
660 "This object has no __dict__");
661 return NULL;
662 }
663 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000664 if (dict == NULL)
665 *dictptr = dict = PyDict_New();
666 Py_XINCREF(dict);
667 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000668}
669
Guido van Rossum32d34c82001-09-20 21:45:26 +0000670PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000671 {"__dict__", subtype_dict, NULL, NULL},
672 {0},
673};
674
675static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000676type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
677{
678 PyObject *name, *bases, *dict;
679 static char *kwlist[] = {"name", "bases", "dict", 0};
680 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000681 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000683 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000684 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000685
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000686 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687 if (metatype == &PyType_Type &&
688 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
689 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690 PyObject *x = PyTuple_GET_ITEM(args, 0);
691 Py_INCREF(x->ob_type);
692 return (PyObject *) x->ob_type;
693 }
694
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000695 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
697 &name,
698 &PyTuple_Type, &bases,
699 &PyDict_Type, &dict))
700 return NULL;
701
702 /* Determine the proper metatype to deal with this,
703 and check for metatype conflicts while we're at it.
704 Note that if some other metatype wins to contract,
705 it's possible that its instances are not types. */
706 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000707 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000708 for (i = 0; i < nbases; i++) {
709 tmp = PyTuple_GET_ITEM(bases, i);
710 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000711 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000712 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000713 if (PyType_IsSubtype(tmptype, winner)) {
714 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000715 continue;
716 }
717 PyErr_SetString(PyExc_TypeError,
718 "metatype conflict among bases");
719 return NULL;
720 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000721 if (winner != metatype) {
722 if (winner->tp_new != type_new) /* Pass it to the winner */
723 return winner->tp_new(winner, args, kwds);
724 metatype = winner;
725 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000726
727 /* Adjust for empty tuple bases */
728 if (nbases == 0) {
729 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
730 if (bases == NULL)
731 return NULL;
732 nbases = 1;
733 }
734 else
735 Py_INCREF(bases);
736
737 /* XXX From here until type is allocated, "return NULL" leaks bases! */
738
739 /* Calculate best base, and check that all bases are type objects */
740 base = best_base(bases);
741 if (base == NULL)
742 return NULL;
743 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
744 PyErr_Format(PyExc_TypeError,
745 "type '%.100s' is not an acceptable base type",
746 base->tp_name);
747 return NULL;
748 }
749
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750 /* Check for a __slots__ sequence variable in dict, and count it */
751 slots = PyDict_GetItemString(dict, "__slots__");
752 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000753 add_dict = 0;
754 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755 if (slots != NULL) {
756 /* Make it into a tuple */
757 if (PyString_Check(slots))
758 slots = Py_BuildValue("(O)", slots);
759 else
760 slots = PySequence_Tuple(slots);
761 if (slots == NULL)
762 return NULL;
763 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000764 if (nslots > 0 && base->tp_itemsize != 0) {
765 PyErr_Format(PyExc_TypeError,
766 "nonempty __slots__ "
767 "not supported for subtype of '%s'",
768 base->tp_name);
769 return NULL;
770 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000771 for (i = 0; i < nslots; i++) {
772 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
773 PyErr_SetString(PyExc_TypeError,
774 "__slots__ must be a sequence of strings");
775 Py_DECREF(slots);
776 return NULL;
777 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000778 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000779 }
780 }
781 if (slots == NULL && base->tp_dictoffset == 0 &&
782 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000783 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000784 add_dict++;
785 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000786 if (slots == NULL && base->tp_weaklistoffset == 0 &&
787 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000788 nslots++;
789 add_weak++;
790 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791
792 /* XXX From here until type is safely allocated,
793 "return NULL" may leak slots! */
794
795 /* Allocate the type object */
796 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
797 if (type == NULL)
798 return NULL;
799
800 /* Keep name and slots alive in the extended type object */
801 et = (etype *)type;
802 Py_INCREF(name);
803 et->name = name;
804 et->slots = slots;
805
Guido van Rossumdc91b992001-08-08 22:26:22 +0000806 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
808 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000809 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
810 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000811
812 /* It's a new-style number unless it specifically inherits any
813 old-style numeric behavior */
814 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
815 (base->tp_as_number == NULL))
816 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
817
818 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819 type->tp_as_number = &et->as_number;
820 type->tp_as_sequence = &et->as_sequence;
821 type->tp_as_mapping = &et->as_mapping;
822 type->tp_as_buffer = &et->as_buffer;
823 type->tp_name = PyString_AS_STRING(name);
824
825 /* Set tp_base and tp_bases */
826 type->tp_bases = bases;
827 Py_INCREF(base);
828 type->tp_base = base;
829
Guido van Rossum687ae002001-10-15 22:03:32 +0000830 /* Initialize tp_dict from passed-in dict */
831 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832 if (dict == NULL) {
833 Py_DECREF(type);
834 return NULL;
835 }
836
Guido van Rossumc3542212001-08-16 09:18:56 +0000837 /* Set __module__ in the dict */
838 if (PyDict_GetItemString(dict, "__module__") == NULL) {
839 tmp = PyEval_GetGlobals();
840 if (tmp != NULL) {
841 tmp = PyDict_GetItemString(tmp, "__name__");
842 if (tmp != NULL) {
843 if (PyDict_SetItemString(dict, "__module__",
844 tmp) < 0)
845 return NULL;
846 }
847 }
848 }
849
Tim Peters2f93e282001-10-04 05:27:00 +0000850 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
851 and is a string (tp_doc is a char* -- can't copy a general object
852 into it).
853 XXX What if it's a Unicode string? Don't know -- this ignores it.
854 */
855 {
856 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
857 if (doc != NULL && PyString_Check(doc)) {
858 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000859 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000860 if (type->tp_doc == NULL) {
861 Py_DECREF(type);
862 return NULL;
863 }
864 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
865 }
866 }
867
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 /* Special-case __new__: if it's a plain function,
869 make it a static function */
870 tmp = PyDict_GetItemString(dict, "__new__");
871 if (tmp != NULL && PyFunction_Check(tmp)) {
872 tmp = PyStaticMethod_New(tmp);
873 if (tmp == NULL) {
874 Py_DECREF(type);
875 return NULL;
876 }
877 PyDict_SetItemString(dict, "__new__", tmp);
878 Py_DECREF(tmp);
879 }
880
881 /* Add descriptors for custom slots from __slots__, or for __dict__ */
882 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000883 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884 if (slots != NULL) {
885 for (i = 0; i < nslots; i++, mp++) {
886 mp->name = PyString_AS_STRING(
887 PyTuple_GET_ITEM(slots, i));
888 mp->type = T_OBJECT;
889 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000890 if (base->tp_weaklistoffset == 0 &&
891 strcmp(mp->name, "__weakref__") == 0)
892 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000893 slotoffset += sizeof(PyObject *);
894 }
895 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000896 else {
897 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000898 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000899 type->tp_dictoffset =
900 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000901 else
902 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000903 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000904 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000905 }
906 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000907 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000908 type->tp_weaklistoffset = slotoffset;
909 mp->name = "__weakref__";
910 mp->type = T_OBJECT;
911 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000912 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000913 mp++;
914 slotoffset += sizeof(PyObject *);
915 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000916 }
917 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000918 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000919 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000920
921 /* Special case some slots */
922 if (type->tp_dictoffset != 0 || nslots > 0) {
923 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
924 type->tp_getattro = PyObject_GenericGetAttr;
925 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
926 type->tp_setattro = PyObject_GenericSetAttr;
927 }
928 type->tp_dealloc = subtype_dealloc;
929
Guido van Rossum9475a232001-10-05 20:51:39 +0000930 /* Enable GC unless there are really no instance variables possible */
931 if (!(type->tp_basicsize == sizeof(PyObject) &&
932 type->tp_itemsize == 0))
933 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
934
Tim Peters6d6c1a32001-08-02 04:15:00 +0000935 /* Always override allocation strategy to use regular heap */
936 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +0000937 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
938 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +0000939 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +0000940 type->tp_clear = base->tp_clear;
941 }
942 else
943 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000944
945 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000946 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000947 Py_DECREF(type);
948 return NULL;
949 }
950
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000951 /* Put the proper slots in place */
952 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000953
Tim Peters6d6c1a32001-08-02 04:15:00 +0000954 return (PyObject *)type;
955}
956
957/* Internal API to look for a name through the MRO.
958 This returns a borrowed reference, and doesn't set an exception! */
959PyObject *
960_PyType_Lookup(PyTypeObject *type, PyObject *name)
961{
962 int i, n;
963 PyObject *mro, *res, *dict;
964
Guido van Rossum687ae002001-10-15 22:03:32 +0000965 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000966 mro = type->tp_mro;
967 assert(PyTuple_Check(mro));
968 n = PyTuple_GET_SIZE(mro);
969 for (i = 0; i < n; i++) {
970 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
971 assert(PyType_Check(type));
Guido van Rossum687ae002001-10-15 22:03:32 +0000972 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000973 assert(dict && PyDict_Check(dict));
974 res = PyDict_GetItem(dict, name);
975 if (res != NULL)
976 return res;
977 }
978 return NULL;
979}
980
981/* This is similar to PyObject_GenericGetAttr(),
982 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
983static PyObject *
984type_getattro(PyTypeObject *type, PyObject *name)
985{
986 PyTypeObject *metatype = type->ob_type;
987 PyObject *descr, *res;
988 descrgetfunc f;
989
990 /* Initialize this type (we'll assume the metatype is initialized) */
991 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000992 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 return NULL;
994 }
995
996 /* Get a descriptor from the metatype */
997 descr = _PyType_Lookup(metatype, name);
998 f = NULL;
999 if (descr != NULL) {
1000 f = descr->ob_type->tp_descr_get;
1001 if (f != NULL && PyDescr_IsData(descr))
1002 return f(descr,
1003 (PyObject *)type, (PyObject *)metatype);
1004 }
1005
Guido van Rossum687ae002001-10-15 22:03:32 +00001006 /* Look in tp_dict of this type and its bases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007 res = _PyType_Lookup(type, name);
1008 if (res != NULL) {
1009 f = res->ob_type->tp_descr_get;
1010 if (f != NULL)
1011 return f(res, (PyObject *)NULL, (PyObject *)type);
1012 Py_INCREF(res);
1013 return res;
1014 }
1015
1016 /* Use the descriptor from the metatype */
1017 if (f != NULL) {
1018 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1019 return res;
1020 }
1021 if (descr != NULL) {
1022 Py_INCREF(descr);
1023 return descr;
1024 }
1025
1026 /* Give up */
1027 PyErr_Format(PyExc_AttributeError,
1028 "type object '%.50s' has no attribute '%.400s'",
1029 type->tp_name, PyString_AS_STRING(name));
1030 return NULL;
1031}
1032
1033static int
1034type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1035{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001036 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1037 PyErr_Format(
1038 PyExc_TypeError,
1039 "can't set attributes of built-in/extension type '%s'",
1040 type->tp_name);
1041 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001042 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001043 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1044 return -1;
1045 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046}
1047
1048static void
1049type_dealloc(PyTypeObject *type)
1050{
1051 etype *et;
1052
1053 /* Assert this is a heap-allocated type object */
1054 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001055 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001056 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001057 et = (etype *)type;
1058 Py_XDECREF(type->tp_base);
1059 Py_XDECREF(type->tp_dict);
1060 Py_XDECREF(type->tp_bases);
1061 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001062 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001063 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064 Py_XDECREF(et->name);
1065 Py_XDECREF(et->slots);
1066 type->ob_type->tp_free((PyObject *)type);
1067}
1068
Guido van Rossum1c450732001-10-08 15:18:27 +00001069static PyObject *
1070type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1071{
1072 PyObject *list, *raw, *ref;
1073 int i, n;
1074
1075 list = PyList_New(0);
1076 if (list == NULL)
1077 return NULL;
1078 raw = type->tp_subclasses;
1079 if (raw == NULL)
1080 return list;
1081 assert(PyList_Check(raw));
1082 n = PyList_GET_SIZE(raw);
1083 for (i = 0; i < n; i++) {
1084 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001085 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001086 ref = PyWeakref_GET_OBJECT(ref);
1087 if (ref != Py_None) {
1088 if (PyList_Append(list, ref) < 0) {
1089 Py_DECREF(list);
1090 return NULL;
1091 }
1092 }
1093 }
1094 return list;
1095}
1096
Tim Peters6d6c1a32001-08-02 04:15:00 +00001097static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001098 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001100 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1101 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102 {0}
1103};
1104
1105static char type_doc[] =
1106"type(object) -> the object's type\n"
1107"type(name, bases, dict) -> a new type";
1108
Guido van Rossum048eb752001-10-02 21:24:57 +00001109static int
1110type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1111{
1112 etype *et;
1113 int err;
1114
1115 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1116 return 0;
1117
1118 et = (etype *)type;
1119
1120#define VISIT(SLOT) \
1121 if (SLOT) { \
1122 err = visit((PyObject *)(SLOT), arg); \
1123 if (err) \
1124 return err; \
1125 }
1126
1127 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001128 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001129 VISIT(type->tp_mro);
1130 VISIT(type->tp_bases);
1131 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001132 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001133 VISIT(et->slots);
1134
1135#undef VISIT
1136
1137 return 0;
1138}
1139
1140static int
1141type_clear(PyTypeObject *type)
1142{
1143 etype *et;
1144 PyObject *tmp;
1145
1146 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1147 return 0;
1148
1149 et = (etype *)type;
1150
1151#define CLEAR(SLOT) \
1152 if (SLOT) { \
1153 tmp = (PyObject *)(SLOT); \
1154 SLOT = NULL; \
1155 Py_DECREF(tmp); \
1156 }
1157
1158 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001159 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001160 CLEAR(type->tp_mro);
1161 CLEAR(type->tp_bases);
1162 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001163 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001164 CLEAR(et->slots);
1165
Tim Peters2f93e282001-10-04 05:27:00 +00001166 if (type->tp_doc != NULL) {
1167 PyObject_FREE(type->tp_doc);
1168 type->tp_doc = NULL;
1169 }
1170
Guido van Rossum048eb752001-10-02 21:24:57 +00001171#undef CLEAR
1172
1173 return 0;
1174}
1175
1176static int
1177type_is_gc(PyTypeObject *type)
1178{
1179 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1180}
1181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001182PyTypeObject PyType_Type = {
1183 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184 0, /* ob_size */
1185 "type", /* tp_name */
1186 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001187 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 (destructor)type_dealloc, /* tp_dealloc */
1189 0, /* tp_print */
1190 0, /* tp_getattr */
1191 0, /* tp_setattr */
1192 type_compare, /* tp_compare */
1193 (reprfunc)type_repr, /* tp_repr */
1194 0, /* tp_as_number */
1195 0, /* tp_as_sequence */
1196 0, /* tp_as_mapping */
1197 (hashfunc)_Py_HashPointer, /* tp_hash */
1198 (ternaryfunc)type_call, /* tp_call */
1199 0, /* tp_str */
1200 (getattrofunc)type_getattro, /* tp_getattro */
1201 (setattrofunc)type_setattro, /* tp_setattro */
1202 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001203 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1204 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001206 (traverseproc)type_traverse, /* tp_traverse */
1207 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001209 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 0, /* tp_iter */
1211 0, /* tp_iternext */
1212 type_methods, /* tp_methods */
1213 type_members, /* tp_members */
1214 type_getsets, /* tp_getset */
1215 0, /* tp_base */
1216 0, /* tp_dict */
1217 0, /* tp_descr_get */
1218 0, /* tp_descr_set */
1219 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1220 0, /* tp_init */
1221 0, /* tp_alloc */
1222 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001223 _PyObject_GC_Del, /* tp_free */
1224 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001225};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226
1227
1228/* The base type of all types (eventually)... except itself. */
1229
1230static int
1231object_init(PyObject *self, PyObject *args, PyObject *kwds)
1232{
1233 return 0;
1234}
1235
1236static void
1237object_dealloc(PyObject *self)
1238{
1239 self->ob_type->tp_free(self);
1240}
1241
Guido van Rossum8e248182001-08-12 05:17:56 +00001242static PyObject *
1243object_repr(PyObject *self)
1244{
Guido van Rossum76e69632001-08-16 18:52:43 +00001245 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001246 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001247
Guido van Rossum76e69632001-08-16 18:52:43 +00001248 type = self->ob_type;
1249 mod = type_module(type, NULL);
1250 if (mod == NULL)
1251 PyErr_Clear();
1252 else if (!PyString_Check(mod)) {
1253 Py_DECREF(mod);
1254 mod = NULL;
1255 }
1256 name = type_name(type, NULL);
1257 if (name == NULL)
1258 return NULL;
1259 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001260 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001261 PyString_AS_STRING(mod),
1262 PyString_AS_STRING(name),
1263 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001264 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001265 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001266 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001267 Py_XDECREF(mod);
1268 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001269 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001270}
1271
Guido van Rossumb8f63662001-08-15 23:57:02 +00001272static PyObject *
1273object_str(PyObject *self)
1274{
1275 unaryfunc f;
1276
1277 f = self->ob_type->tp_repr;
1278 if (f == NULL)
1279 f = object_repr;
1280 return f(self);
1281}
1282
Guido van Rossum8e248182001-08-12 05:17:56 +00001283static long
1284object_hash(PyObject *self)
1285{
1286 return _Py_HashPointer(self);
1287}
Guido van Rossum8e248182001-08-12 05:17:56 +00001288
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001289static PyObject *
1290object_get_class(PyObject *self, void *closure)
1291{
1292 Py_INCREF(self->ob_type);
1293 return (PyObject *)(self->ob_type);
1294}
1295
1296static int
1297equiv_structs(PyTypeObject *a, PyTypeObject *b)
1298{
1299 return a == b ||
1300 (a != NULL &&
1301 b != NULL &&
1302 a->tp_basicsize == b->tp_basicsize &&
1303 a->tp_itemsize == b->tp_itemsize &&
1304 a->tp_dictoffset == b->tp_dictoffset &&
1305 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1306 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1307 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1308}
1309
1310static int
1311same_slots_added(PyTypeObject *a, PyTypeObject *b)
1312{
1313 PyTypeObject *base = a->tp_base;
1314 int size;
1315
1316 if (base != b->tp_base)
1317 return 0;
1318 if (equiv_structs(a, base) && equiv_structs(b, base))
1319 return 1;
1320 size = base->tp_basicsize;
1321 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1322 size += sizeof(PyObject *);
1323 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1324 size += sizeof(PyObject *);
1325 return size == a->tp_basicsize && size == b->tp_basicsize;
1326}
1327
1328static int
1329object_set_class(PyObject *self, PyObject *value, void *closure)
1330{
1331 PyTypeObject *old = self->ob_type;
1332 PyTypeObject *new, *newbase, *oldbase;
1333
1334 if (!PyType_Check(value)) {
1335 PyErr_Format(PyExc_TypeError,
1336 "__class__ must be set to new-style class, not '%s' object",
1337 value->ob_type->tp_name);
1338 return -1;
1339 }
1340 new = (PyTypeObject *)value;
1341 newbase = new;
1342 oldbase = old;
1343 while (equiv_structs(newbase, newbase->tp_base))
1344 newbase = newbase->tp_base;
1345 while (equiv_structs(oldbase, oldbase->tp_base))
1346 oldbase = oldbase->tp_base;
1347 if (newbase != oldbase &&
1348 (newbase->tp_base != oldbase->tp_base ||
1349 !same_slots_added(newbase, oldbase))) {
1350 PyErr_Format(PyExc_TypeError,
1351 "__class__ assignment: "
1352 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001353 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001354 old->tp_name);
1355 return -1;
1356 }
1357 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1358 Py_INCREF(new);
1359 }
1360 self->ob_type = new;
1361 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1362 Py_DECREF(old);
1363 }
1364 return 0;
1365}
1366
1367static PyGetSetDef object_getsets[] = {
1368 {"__class__", object_get_class, object_set_class,
1369 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370 {0}
1371};
1372
Guido van Rossum3926a632001-09-25 16:25:58 +00001373static PyObject *
1374object_reduce(PyObject *self, PyObject *args)
1375{
1376 /* Call copy_reg._reduce(self) */
1377 static PyObject *copy_reg_str;
1378 PyObject *copy_reg, *res;
1379
1380 if (!copy_reg_str) {
1381 copy_reg_str = PyString_InternFromString("copy_reg");
1382 if (copy_reg_str == NULL)
1383 return NULL;
1384 }
1385 copy_reg = PyImport_Import(copy_reg_str);
1386 if (!copy_reg)
1387 return NULL;
1388 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1389 Py_DECREF(copy_reg);
1390 return res;
1391}
1392
1393static PyMethodDef object_methods[] = {
1394 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1395 {0}
1396};
1397
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398PyTypeObject PyBaseObject_Type = {
1399 PyObject_HEAD_INIT(&PyType_Type)
1400 0, /* ob_size */
1401 "object", /* tp_name */
1402 sizeof(PyObject), /* tp_basicsize */
1403 0, /* tp_itemsize */
1404 (destructor)object_dealloc, /* tp_dealloc */
1405 0, /* tp_print */
1406 0, /* tp_getattr */
1407 0, /* tp_setattr */
1408 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001409 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410 0, /* tp_as_number */
1411 0, /* tp_as_sequence */
1412 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001413 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001415 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001416 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001417 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 0, /* tp_as_buffer */
1419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1420 "The most base type", /* tp_doc */
1421 0, /* tp_traverse */
1422 0, /* tp_clear */
1423 0, /* tp_richcompare */
1424 0, /* tp_weaklistoffset */
1425 0, /* tp_iter */
1426 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001427 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001428 0, /* tp_members */
1429 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001430 0, /* tp_base */
1431 0, /* tp_dict */
1432 0, /* tp_descr_get */
1433 0, /* tp_descr_set */
1434 0, /* tp_dictoffset */
1435 object_init, /* tp_init */
1436 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001437 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001438 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001439};
1440
1441
1442/* Initialize the __dict__ in a type object */
1443
1444static int
1445add_methods(PyTypeObject *type, PyMethodDef *meth)
1446{
Guido van Rossum687ae002001-10-15 22:03:32 +00001447 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448
1449 for (; meth->ml_name != NULL; meth++) {
1450 PyObject *descr;
1451 if (PyDict_GetItemString(dict, meth->ml_name))
1452 continue;
1453 descr = PyDescr_NewMethod(type, meth);
1454 if (descr == NULL)
1455 return -1;
1456 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1457 return -1;
1458 Py_DECREF(descr);
1459 }
1460 return 0;
1461}
1462
1463static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001464add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465{
Guido van Rossum687ae002001-10-15 22:03:32 +00001466 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467
1468 for (; memb->name != NULL; memb++) {
1469 PyObject *descr;
1470 if (PyDict_GetItemString(dict, memb->name))
1471 continue;
1472 descr = PyDescr_NewMember(type, memb);
1473 if (descr == NULL)
1474 return -1;
1475 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1476 return -1;
1477 Py_DECREF(descr);
1478 }
1479 return 0;
1480}
1481
1482static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001483add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484{
Guido van Rossum687ae002001-10-15 22:03:32 +00001485 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486
1487 for (; gsp->name != NULL; gsp++) {
1488 PyObject *descr;
1489 if (PyDict_GetItemString(dict, gsp->name))
1490 continue;
1491 descr = PyDescr_NewGetSet(type, gsp);
1492
1493 if (descr == NULL)
1494 return -1;
1495 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1496 return -1;
1497 Py_DECREF(descr);
1498 }
1499 return 0;
1500}
1501
Guido van Rossum13d52f02001-08-10 21:24:08 +00001502static void
1503inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504{
1505 int oldsize, newsize;
1506
Guido van Rossum13d52f02001-08-10 21:24:08 +00001507 /* Special flag magic */
1508 if (!type->tp_as_buffer && base->tp_as_buffer) {
1509 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1510 type->tp_flags |=
1511 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1512 }
1513 if (!type->tp_as_sequence && base->tp_as_sequence) {
1514 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1515 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1516 }
1517 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1518 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1519 if ((!type->tp_as_number && base->tp_as_number) ||
1520 (!type->tp_as_sequence && base->tp_as_sequence)) {
1521 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1522 if (!type->tp_as_number && !type->tp_as_sequence) {
1523 type->tp_flags |= base->tp_flags &
1524 Py_TPFLAGS_HAVE_INPLACEOPS;
1525 }
1526 }
1527 /* Wow */
1528 }
1529 if (!type->tp_as_number && base->tp_as_number) {
1530 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1531 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1532 }
1533
1534 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001535 oldsize = base->tp_basicsize;
1536 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1537 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1538 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001539 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1540 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001541 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001542 if (type->tp_traverse == NULL)
1543 type->tp_traverse = base->tp_traverse;
1544 if (type->tp_clear == NULL)
1545 type->tp_clear = base->tp_clear;
1546 }
1547 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1548 if (base != &PyBaseObject_Type ||
1549 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1550 if (type->tp_new == NULL)
1551 type->tp_new = base->tp_new;
1552 }
1553 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001554 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001555
1556 /* Copy other non-function slots */
1557
1558#undef COPYVAL
1559#define COPYVAL(SLOT) \
1560 if (type->SLOT == 0) type->SLOT = base->SLOT
1561
1562 COPYVAL(tp_itemsize);
1563 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1564 COPYVAL(tp_weaklistoffset);
1565 }
1566 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1567 COPYVAL(tp_dictoffset);
1568 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001569}
1570
1571static void
1572inherit_slots(PyTypeObject *type, PyTypeObject *base)
1573{
1574 PyTypeObject *basebase;
1575
1576#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577#undef COPYSLOT
1578#undef COPYNUM
1579#undef COPYSEQ
1580#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001581#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001582
1583#define SLOTDEFINED(SLOT) \
1584 (base->SLOT != 0 && \
1585 (basebase == NULL || base->SLOT != basebase->SLOT))
1586
Tim Peters6d6c1a32001-08-02 04:15:00 +00001587#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001588 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589
1590#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1591#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1592#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001593#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594
Guido van Rossum13d52f02001-08-10 21:24:08 +00001595 /* This won't inherit indirect slots (from tp_as_number etc.)
1596 if type doesn't provide the space. */
1597
1598 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1599 basebase = base->tp_base;
1600 if (basebase->tp_as_number == NULL)
1601 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602 COPYNUM(nb_add);
1603 COPYNUM(nb_subtract);
1604 COPYNUM(nb_multiply);
1605 COPYNUM(nb_divide);
1606 COPYNUM(nb_remainder);
1607 COPYNUM(nb_divmod);
1608 COPYNUM(nb_power);
1609 COPYNUM(nb_negative);
1610 COPYNUM(nb_positive);
1611 COPYNUM(nb_absolute);
1612 COPYNUM(nb_nonzero);
1613 COPYNUM(nb_invert);
1614 COPYNUM(nb_lshift);
1615 COPYNUM(nb_rshift);
1616 COPYNUM(nb_and);
1617 COPYNUM(nb_xor);
1618 COPYNUM(nb_or);
1619 COPYNUM(nb_coerce);
1620 COPYNUM(nb_int);
1621 COPYNUM(nb_long);
1622 COPYNUM(nb_float);
1623 COPYNUM(nb_oct);
1624 COPYNUM(nb_hex);
1625 COPYNUM(nb_inplace_add);
1626 COPYNUM(nb_inplace_subtract);
1627 COPYNUM(nb_inplace_multiply);
1628 COPYNUM(nb_inplace_divide);
1629 COPYNUM(nb_inplace_remainder);
1630 COPYNUM(nb_inplace_power);
1631 COPYNUM(nb_inplace_lshift);
1632 COPYNUM(nb_inplace_rshift);
1633 COPYNUM(nb_inplace_and);
1634 COPYNUM(nb_inplace_xor);
1635 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001636 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1637 COPYNUM(nb_true_divide);
1638 COPYNUM(nb_floor_divide);
1639 COPYNUM(nb_inplace_true_divide);
1640 COPYNUM(nb_inplace_floor_divide);
1641 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001642 }
1643
Guido van Rossum13d52f02001-08-10 21:24:08 +00001644 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1645 basebase = base->tp_base;
1646 if (basebase->tp_as_sequence == NULL)
1647 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001648 COPYSEQ(sq_length);
1649 COPYSEQ(sq_concat);
1650 COPYSEQ(sq_repeat);
1651 COPYSEQ(sq_item);
1652 COPYSEQ(sq_slice);
1653 COPYSEQ(sq_ass_item);
1654 COPYSEQ(sq_ass_slice);
1655 COPYSEQ(sq_contains);
1656 COPYSEQ(sq_inplace_concat);
1657 COPYSEQ(sq_inplace_repeat);
1658 }
1659
Guido van Rossum13d52f02001-08-10 21:24:08 +00001660 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1661 basebase = base->tp_base;
1662 if (basebase->tp_as_mapping == NULL)
1663 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664 COPYMAP(mp_length);
1665 COPYMAP(mp_subscript);
1666 COPYMAP(mp_ass_subscript);
1667 }
1668
Tim Petersfc57ccb2001-10-12 02:38:24 +00001669 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1670 basebase = base->tp_base;
1671 if (basebase->tp_as_buffer == NULL)
1672 basebase = NULL;
1673 COPYBUF(bf_getreadbuffer);
1674 COPYBUF(bf_getwritebuffer);
1675 COPYBUF(bf_getsegcount);
1676 COPYBUF(bf_getcharbuffer);
1677 }
1678
Guido van Rossum13d52f02001-08-10 21:24:08 +00001679 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 COPYSLOT(tp_dealloc);
1682 COPYSLOT(tp_print);
1683 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1684 type->tp_getattr = base->tp_getattr;
1685 type->tp_getattro = base->tp_getattro;
1686 }
1687 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1688 type->tp_setattr = base->tp_setattr;
1689 type->tp_setattro = base->tp_setattro;
1690 }
1691 /* tp_compare see tp_richcompare */
1692 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001693 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 COPYSLOT(tp_call);
1695 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001696 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001697 if (type->tp_compare == NULL &&
1698 type->tp_richcompare == NULL &&
1699 type->tp_hash == NULL)
1700 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701 type->tp_compare = base->tp_compare;
1702 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001703 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704 }
1705 }
1706 else {
1707 COPYSLOT(tp_compare);
1708 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1710 COPYSLOT(tp_iter);
1711 COPYSLOT(tp_iternext);
1712 }
1713 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1714 COPYSLOT(tp_descr_get);
1715 COPYSLOT(tp_descr_set);
1716 COPYSLOT(tp_dictoffset);
1717 COPYSLOT(tp_init);
1718 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719 COPYSLOT(tp_free);
1720 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721}
1722
Guido van Rossum13d52f02001-08-10 21:24:08 +00001723staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001724staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001725
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001727PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001729 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 PyTypeObject *base;
1731 int i, n;
1732
Guido van Rossumd614f972001-08-10 17:39:49 +00001733 if (type->tp_flags & Py_TPFLAGS_READY) {
1734 assert(type->tp_dict != NULL);
1735 return 0;
1736 }
1737 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00001738
1739 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001740
1741 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1742 base = type->tp_base;
1743 if (base == NULL && type != &PyBaseObject_Type)
1744 base = type->tp_base = &PyBaseObject_Type;
1745
1746 /* Initialize tp_bases */
1747 bases = type->tp_bases;
1748 if (bases == NULL) {
1749 if (base == NULL)
1750 bases = PyTuple_New(0);
1751 else
1752 bases = Py_BuildValue("(O)", base);
1753 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001754 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001755 type->tp_bases = bases;
1756 }
1757
1758 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001759 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001760 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001761 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762 }
1763
Guido van Rossum687ae002001-10-15 22:03:32 +00001764 /* Initialize tp_dict */
1765 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 if (dict == NULL) {
1767 dict = PyDict_New();
1768 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001769 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00001770 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771 }
1772
Guido van Rossum687ae002001-10-15 22:03:32 +00001773 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001775 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776 if (type->tp_methods != NULL) {
1777 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001778 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779 }
1780 if (type->tp_members != NULL) {
1781 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001782 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 }
1784 if (type->tp_getset != NULL) {
1785 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001786 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 }
1788
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789 /* Calculate method resolution order */
1790 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001791 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792 }
1793
Guido van Rossum13d52f02001-08-10 21:24:08 +00001794 /* Inherit special flags from dominant base */
1795 if (type->tp_base != NULL)
1796 inherit_special(type, type->tp_base);
1797
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001799 bases = type->tp_mro;
1800 assert(bases != NULL);
1801 assert(PyTuple_Check(bases));
1802 n = PyTuple_GET_SIZE(bases);
1803 for (i = 1; i < n; i++) {
1804 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1805 assert(PyType_Check(base));
1806 inherit_slots(type, base);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001807 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808
Guido van Rossum13d52f02001-08-10 21:24:08 +00001809 /* Some more special stuff */
1810 base = type->tp_base;
1811 if (base != NULL) {
1812 if (type->tp_as_number == NULL)
1813 type->tp_as_number = base->tp_as_number;
1814 if (type->tp_as_sequence == NULL)
1815 type->tp_as_sequence = base->tp_as_sequence;
1816 if (type->tp_as_mapping == NULL)
1817 type->tp_as_mapping = base->tp_as_mapping;
1818 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819
Guido van Rossum1c450732001-10-08 15:18:27 +00001820 /* Link into each base class's list of subclasses */
1821 bases = type->tp_bases;
1822 n = PyTuple_GET_SIZE(bases);
1823 for (i = 0; i < n; i++) {
1824 base = (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
1825 if (add_subclass((PyTypeObject *)base, type) < 0)
1826 goto error;
1827 }
1828
Guido van Rossum13d52f02001-08-10 21:24:08 +00001829 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001830 assert(type->tp_dict != NULL);
1831 type->tp_flags =
1832 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001833 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001834
1835 error:
1836 type->tp_flags &= ~Py_TPFLAGS_READYING;
1837 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838}
1839
Guido van Rossum1c450732001-10-08 15:18:27 +00001840static int
1841add_subclass(PyTypeObject *base, PyTypeObject *type)
1842{
1843 int i;
1844 PyObject *list, *ref, *new;
1845
1846 list = base->tp_subclasses;
1847 if (list == NULL) {
1848 base->tp_subclasses = list = PyList_New(0);
1849 if (list == NULL)
1850 return -1;
1851 }
1852 assert(PyList_Check(list));
1853 new = PyWeakref_NewRef((PyObject *)type, NULL);
1854 i = PyList_GET_SIZE(list);
1855 while (--i >= 0) {
1856 ref = PyList_GET_ITEM(list, i);
1857 assert(PyWeakref_CheckRef(ref));
1858 if (PyWeakref_GET_OBJECT(ref) == Py_None)
1859 return PyList_SetItem(list, i, new);
1860 }
1861 i = PyList_Append(list, new);
1862 Py_DECREF(new);
1863 return i;
1864}
1865
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866
1867/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1868
1869/* There's a wrapper *function* for each distinct function typedef used
1870 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1871 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1872 Most tables have only one entry; the tables for binary operators have two
1873 entries, one regular and one with reversed arguments. */
1874
1875static PyObject *
1876wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1877{
1878 inquiry func = (inquiry)wrapped;
1879 int res;
1880
1881 if (!PyArg_ParseTuple(args, ""))
1882 return NULL;
1883 res = (*func)(self);
1884 if (res == -1 && PyErr_Occurred())
1885 return NULL;
1886 return PyInt_FromLong((long)res);
1887}
1888
1889static struct wrapperbase tab_len[] = {
1890 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1891 {0}
1892};
1893
1894static PyObject *
1895wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1896{
1897 binaryfunc func = (binaryfunc)wrapped;
1898 PyObject *other;
1899
1900 if (!PyArg_ParseTuple(args, "O", &other))
1901 return NULL;
1902 return (*func)(self, other);
1903}
1904
1905static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001906wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
1907{
1908 binaryfunc func = (binaryfunc)wrapped;
1909 PyObject *other;
1910
1911 if (!PyArg_ParseTuple(args, "O", &other))
1912 return NULL;
1913 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001914 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001915 Py_INCREF(Py_NotImplemented);
1916 return Py_NotImplemented;
1917 }
1918 return (*func)(self, other);
1919}
1920
1921static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1923{
1924 binaryfunc func = (binaryfunc)wrapped;
1925 PyObject *other;
1926
1927 if (!PyArg_ParseTuple(args, "O", &other))
1928 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001929 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001930 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001931 Py_INCREF(Py_NotImplemented);
1932 return Py_NotImplemented;
1933 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 return (*func)(other, self);
1935}
1936
1937#undef BINARY
1938#define BINARY(NAME, OP) \
1939static struct wrapperbase tab_##NAME[] = { \
1940 {"__" #NAME "__", \
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001941 (wrapperfunc)wrap_binaryfunc_l, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00001942 "x.__" #NAME "__(y) <==> " #OP}, \
1943 {"__r" #NAME "__", \
1944 (wrapperfunc)wrap_binaryfunc_r, \
1945 "y.__r" #NAME "__(x) <==> " #OP}, \
1946 {0} \
1947}
1948
1949BINARY(add, "x+y");
1950BINARY(sub, "x-y");
1951BINARY(mul, "x*y");
1952BINARY(div, "x/y");
1953BINARY(mod, "x%y");
1954BINARY(divmod, "divmod(x,y)");
1955BINARY(lshift, "x<<y");
1956BINARY(rshift, "x>>y");
1957BINARY(and, "x&y");
1958BINARY(xor, "x^y");
1959BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001960
1961static PyObject *
1962wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1963{
1964 coercion func = (coercion)wrapped;
1965 PyObject *other, *res;
1966 int ok;
1967
1968 if (!PyArg_ParseTuple(args, "O", &other))
1969 return NULL;
1970 ok = func(&self, &other);
1971 if (ok < 0)
1972 return NULL;
1973 if (ok > 0) {
1974 Py_INCREF(Py_NotImplemented);
1975 return Py_NotImplemented;
1976 }
1977 res = PyTuple_New(2);
1978 if (res == NULL) {
1979 Py_DECREF(self);
1980 Py_DECREF(other);
1981 return NULL;
1982 }
1983 PyTuple_SET_ITEM(res, 0, self);
1984 PyTuple_SET_ITEM(res, 1, other);
1985 return res;
1986}
1987
1988static struct wrapperbase tab_coerce[] = {
1989 {"__coerce__", (wrapperfunc)wrap_coercefunc,
1990 "x.__coerce__(y) <==> coerce(x, y)"},
1991 {0}
1992};
1993
Guido van Rossum874f15a2001-09-25 21:16:33 +00001994BINARY(floordiv, "x//y");
1995BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996
1997static PyObject *
1998wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1999{
2000 ternaryfunc func = (ternaryfunc)wrapped;
2001 PyObject *other;
2002 PyObject *third = Py_None;
2003
2004 /* Note: This wrapper only works for __pow__() */
2005
2006 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2007 return NULL;
2008 return (*func)(self, other, third);
2009}
2010
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002011static PyObject *
2012wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2013{
2014 ternaryfunc func = (ternaryfunc)wrapped;
2015 PyObject *other;
2016 PyObject *third = Py_None;
2017
2018 /* Note: This wrapper only works for __pow__() */
2019
2020 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2021 return NULL;
2022 return (*func)(other, self, third);
2023}
2024
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025#undef TERNARY
2026#define TERNARY(NAME, OP) \
2027static struct wrapperbase tab_##NAME[] = { \
2028 {"__" #NAME "__", \
2029 (wrapperfunc)wrap_ternaryfunc, \
2030 "x.__" #NAME "__(y, z) <==> " #OP}, \
2031 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002032 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2034 {0} \
2035}
2036
2037TERNARY(pow, "(x**y) % z");
2038
2039#undef UNARY
2040#define UNARY(NAME, OP) \
2041static struct wrapperbase tab_##NAME[] = { \
2042 {"__" #NAME "__", \
2043 (wrapperfunc)wrap_unaryfunc, \
2044 "x.__" #NAME "__() <==> " #OP}, \
2045 {0} \
2046}
2047
2048static PyObject *
2049wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2050{
2051 unaryfunc func = (unaryfunc)wrapped;
2052
2053 if (!PyArg_ParseTuple(args, ""))
2054 return NULL;
2055 return (*func)(self);
2056}
2057
2058UNARY(neg, "-x");
2059UNARY(pos, "+x");
2060UNARY(abs, "abs(x)");
2061UNARY(nonzero, "x != 0");
2062UNARY(invert, "~x");
2063UNARY(int, "int(x)");
2064UNARY(long, "long(x)");
2065UNARY(float, "float(x)");
2066UNARY(oct, "oct(x)");
2067UNARY(hex, "hex(x)");
2068
2069#undef IBINARY
2070#define IBINARY(NAME, OP) \
2071static struct wrapperbase tab_##NAME[] = { \
2072 {"__" #NAME "__", \
2073 (wrapperfunc)wrap_binaryfunc, \
2074 "x.__" #NAME "__(y) <==> " #OP}, \
2075 {0} \
2076}
2077
2078IBINARY(iadd, "x+=y");
2079IBINARY(isub, "x-=y");
2080IBINARY(imul, "x*=y");
2081IBINARY(idiv, "x/=y");
2082IBINARY(imod, "x%=y");
2083IBINARY(ilshift, "x<<=y");
2084IBINARY(irshift, "x>>=y");
2085IBINARY(iand, "x&=y");
2086IBINARY(ixor, "x^=y");
2087IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002088IBINARY(ifloordiv, "x//=y");
2089IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002090
2091#undef ITERNARY
2092#define ITERNARY(NAME, OP) \
2093static struct wrapperbase tab_##NAME[] = { \
2094 {"__" #NAME "__", \
2095 (wrapperfunc)wrap_ternaryfunc, \
2096 "x.__" #NAME "__(y) <==> " #OP}, \
2097 {0} \
2098}
2099
2100ITERNARY(ipow, "x = (x**y) % z");
2101
2102static struct wrapperbase tab_getitem[] = {
2103 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2104 "x.__getitem__(y) <==> x[y]"},
2105 {0}
2106};
2107
2108static PyObject *
2109wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2110{
2111 intargfunc func = (intargfunc)wrapped;
2112 int i;
2113
2114 if (!PyArg_ParseTuple(args, "i", &i))
2115 return NULL;
2116 return (*func)(self, i);
2117}
2118
2119static struct wrapperbase tab_mul_int[] = {
2120 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2121 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2122 {0}
2123};
2124
2125static struct wrapperbase tab_concat[] = {
2126 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2127 {0}
2128};
2129
2130static struct wrapperbase tab_imul_int[] = {
2131 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2132 {0}
2133};
2134
Guido van Rossum5d815f32001-08-17 21:57:47 +00002135static int
2136getindex(PyObject *self, PyObject *arg)
2137{
2138 int i;
2139
2140 i = PyInt_AsLong(arg);
2141 if (i == -1 && PyErr_Occurred())
2142 return -1;
2143 if (i < 0) {
2144 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2145 if (sq && sq->sq_length) {
2146 int n = (*sq->sq_length)(self);
2147 if (n < 0)
2148 return -1;
2149 i += n;
2150 }
2151 }
2152 return i;
2153}
2154
2155static PyObject *
2156wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2157{
2158 intargfunc func = (intargfunc)wrapped;
2159 PyObject *arg;
2160 int i;
2161
Guido van Rossumf4593e02001-10-03 12:09:30 +00002162 if (PyTuple_GET_SIZE(args) == 1) {
2163 arg = PyTuple_GET_ITEM(args, 0);
2164 i = getindex(self, arg);
2165 if (i == -1 && PyErr_Occurred())
2166 return NULL;
2167 return (*func)(self, i);
2168 }
2169 PyArg_ParseTuple(args, "O", &arg);
2170 assert(PyErr_Occurred());
2171 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002172}
2173
Tim Peters6d6c1a32001-08-02 04:15:00 +00002174static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002175 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176 "x.__getitem__(i) <==> x[i]"},
2177 {0}
2178};
2179
2180static PyObject *
2181wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2182{
2183 intintargfunc func = (intintargfunc)wrapped;
2184 int i, j;
2185
2186 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2187 return NULL;
2188 return (*func)(self, i, j);
2189}
2190
2191static struct wrapperbase tab_getslice[] = {
2192 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2193 "x.__getslice__(i, j) <==> x[i:j]"},
2194 {0}
2195};
2196
2197static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002198wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002199{
2200 intobjargproc func = (intobjargproc)wrapped;
2201 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002202 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203
Guido van Rossum5d815f32001-08-17 21:57:47 +00002204 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2205 return NULL;
2206 i = getindex(self, arg);
2207 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002208 return NULL;
2209 res = (*func)(self, i, value);
2210 if (res == -1 && PyErr_Occurred())
2211 return NULL;
2212 Py_INCREF(Py_None);
2213 return Py_None;
2214}
2215
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002216static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002217wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002218{
2219 intobjargproc func = (intobjargproc)wrapped;
2220 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002221 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002222
Guido van Rossum5d815f32001-08-17 21:57:47 +00002223 if (!PyArg_ParseTuple(args, "O", &arg))
2224 return NULL;
2225 i = getindex(self, arg);
2226 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002227 return NULL;
2228 res = (*func)(self, i, NULL);
2229 if (res == -1 && PyErr_Occurred())
2230 return NULL;
2231 Py_INCREF(Py_None);
2232 return Py_None;
2233}
2234
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002236 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002238 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002239 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240 {0}
2241};
2242
2243static PyObject *
2244wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2245{
2246 intintobjargproc func = (intintobjargproc)wrapped;
2247 int i, j, res;
2248 PyObject *value;
2249
2250 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2251 return NULL;
2252 res = (*func)(self, i, j, value);
2253 if (res == -1 && PyErr_Occurred())
2254 return NULL;
2255 Py_INCREF(Py_None);
2256 return Py_None;
2257}
2258
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002259static PyObject *
2260wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2261{
2262 intintobjargproc func = (intintobjargproc)wrapped;
2263 int i, j, res;
2264
2265 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2266 return NULL;
2267 res = (*func)(self, i, j, NULL);
2268 if (res == -1 && PyErr_Occurred())
2269 return NULL;
2270 Py_INCREF(Py_None);
2271 return Py_None;
2272}
2273
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274static struct wrapperbase tab_setslice[] = {
2275 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2276 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002277 {"__delslice__", (wrapperfunc)wrap_delslice,
2278 "x.__delslice__(i, j) <==> del x[i:j]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279 {0}
2280};
2281
2282/* XXX objobjproc is a misnomer; should be objargpred */
2283static PyObject *
2284wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2285{
2286 objobjproc func = (objobjproc)wrapped;
2287 int res;
2288 PyObject *value;
2289
2290 if (!PyArg_ParseTuple(args, "O", &value))
2291 return NULL;
2292 res = (*func)(self, value);
2293 if (res == -1 && PyErr_Occurred())
2294 return NULL;
2295 return PyInt_FromLong((long)res);
2296}
2297
2298static struct wrapperbase tab_contains[] = {
2299 {"__contains__", (wrapperfunc)wrap_objobjproc,
2300 "x.__contains__(y) <==> y in x"},
2301 {0}
2302};
2303
2304static PyObject *
2305wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2306{
2307 objobjargproc func = (objobjargproc)wrapped;
2308 int res;
2309 PyObject *key, *value;
2310
2311 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2312 return NULL;
2313 res = (*func)(self, key, value);
2314 if (res == -1 && PyErr_Occurred())
2315 return NULL;
2316 Py_INCREF(Py_None);
2317 return Py_None;
2318}
2319
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002320static PyObject *
2321wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2322{
2323 objobjargproc func = (objobjargproc)wrapped;
2324 int res;
2325 PyObject *key;
2326
2327 if (!PyArg_ParseTuple(args, "O", &key))
2328 return NULL;
2329 res = (*func)(self, key, NULL);
2330 if (res == -1 && PyErr_Occurred())
2331 return NULL;
2332 Py_INCREF(Py_None);
2333 return Py_None;
2334}
2335
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336static struct wrapperbase tab_setitem[] = {
2337 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2338 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002339 {"__delitem__", (wrapperfunc)wrap_delitem,
2340 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341 {0}
2342};
2343
2344static PyObject *
2345wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2346{
2347 cmpfunc func = (cmpfunc)wrapped;
2348 int res;
2349 PyObject *other;
2350
2351 if (!PyArg_ParseTuple(args, "O", &other))
2352 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002353 if (other->ob_type->tp_compare != func &&
2354 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002355 PyErr_Format(
2356 PyExc_TypeError,
2357 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2358 self->ob_type->tp_name,
2359 self->ob_type->tp_name,
2360 other->ob_type->tp_name);
2361 return NULL;
2362 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363 res = (*func)(self, other);
2364 if (PyErr_Occurred())
2365 return NULL;
2366 return PyInt_FromLong((long)res);
2367}
2368
2369static struct wrapperbase tab_cmp[] = {
2370 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2371 "x.__cmp__(y) <==> cmp(x,y)"},
2372 {0}
2373};
2374
2375static struct wrapperbase tab_repr[] = {
2376 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2377 "x.__repr__() <==> repr(x)"},
2378 {0}
2379};
2380
2381static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002382 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2383 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002384 {0}
2385};
2386
2387static PyObject *
2388wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2389{
2390 setattrofunc func = (setattrofunc)wrapped;
2391 int res;
2392 PyObject *name, *value;
2393
2394 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2395 return NULL;
2396 res = (*func)(self, name, value);
2397 if (res < 0)
2398 return NULL;
2399 Py_INCREF(Py_None);
2400 return Py_None;
2401}
2402
2403static PyObject *
2404wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2405{
2406 setattrofunc func = (setattrofunc)wrapped;
2407 int res;
2408 PyObject *name;
2409
2410 if (!PyArg_ParseTuple(args, "O", &name))
2411 return NULL;
2412 res = (*func)(self, name, NULL);
2413 if (res < 0)
2414 return NULL;
2415 Py_INCREF(Py_None);
2416 return Py_None;
2417}
2418
2419static struct wrapperbase tab_setattr[] = {
2420 {"__setattr__", (wrapperfunc)wrap_setattr,
2421 "x.__setattr__('name', value) <==> x.name = value"},
2422 {"__delattr__", (wrapperfunc)wrap_delattr,
2423 "x.__delattr__('name') <==> del x.name"},
2424 {0}
2425};
2426
2427static PyObject *
2428wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2429{
2430 hashfunc func = (hashfunc)wrapped;
2431 long res;
2432
2433 if (!PyArg_ParseTuple(args, ""))
2434 return NULL;
2435 res = (*func)(self);
2436 if (res == -1 && PyErr_Occurred())
2437 return NULL;
2438 return PyInt_FromLong(res);
2439}
2440
2441static struct wrapperbase tab_hash[] = {
2442 {"__hash__", (wrapperfunc)wrap_hashfunc,
2443 "x.__hash__() <==> hash(x)"},
2444 {0}
2445};
2446
2447static PyObject *
2448wrap_call(PyObject *self, PyObject *args, void *wrapped)
2449{
2450 ternaryfunc func = (ternaryfunc)wrapped;
2451
2452 /* XXX What about keyword arguments? */
2453 return (*func)(self, args, NULL);
2454}
2455
2456static struct wrapperbase tab_call[] = {
2457 {"__call__", (wrapperfunc)wrap_call,
2458 "x.__call__(...) <==> x(...)"},
2459 {0}
2460};
2461
2462static struct wrapperbase tab_str[] = {
2463 {"__str__", (wrapperfunc)wrap_unaryfunc,
2464 "x.__str__() <==> str(x)"},
2465 {0}
2466};
2467
2468static PyObject *
2469wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2470{
2471 richcmpfunc func = (richcmpfunc)wrapped;
2472 PyObject *other;
2473
2474 if (!PyArg_ParseTuple(args, "O", &other))
2475 return NULL;
2476 return (*func)(self, other, op);
2477}
2478
2479#undef RICHCMP_WRAPPER
2480#define RICHCMP_WRAPPER(NAME, OP) \
2481static PyObject * \
2482richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2483{ \
2484 return wrap_richcmpfunc(self, args, wrapped, OP); \
2485}
2486
Jack Jansen8e938b42001-08-08 15:29:49 +00002487RICHCMP_WRAPPER(lt, Py_LT)
2488RICHCMP_WRAPPER(le, Py_LE)
2489RICHCMP_WRAPPER(eq, Py_EQ)
2490RICHCMP_WRAPPER(ne, Py_NE)
2491RICHCMP_WRAPPER(gt, Py_GT)
2492RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002493
2494#undef RICHCMP_ENTRY
2495#define RICHCMP_ENTRY(NAME, EXPR) \
2496 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2497 "x.__" #NAME "__(y) <==> " EXPR}
2498
2499static struct wrapperbase tab_richcmp[] = {
2500 RICHCMP_ENTRY(lt, "x<y"),
2501 RICHCMP_ENTRY(le, "x<=y"),
2502 RICHCMP_ENTRY(eq, "x==y"),
2503 RICHCMP_ENTRY(ne, "x!=y"),
2504 RICHCMP_ENTRY(gt, "x>y"),
2505 RICHCMP_ENTRY(ge, "x>=y"),
2506 {0}
2507};
2508
2509static struct wrapperbase tab_iter[] = {
2510 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2511 {0}
2512};
2513
2514static PyObject *
2515wrap_next(PyObject *self, PyObject *args, void *wrapped)
2516{
2517 unaryfunc func = (unaryfunc)wrapped;
2518 PyObject *res;
2519
2520 if (!PyArg_ParseTuple(args, ""))
2521 return NULL;
2522 res = (*func)(self);
2523 if (res == NULL && !PyErr_Occurred())
2524 PyErr_SetNone(PyExc_StopIteration);
2525 return res;
2526}
2527
2528static struct wrapperbase tab_next[] = {
2529 {"next", (wrapperfunc)wrap_next,
2530 "x.next() -> the next value, or raise StopIteration"},
2531 {0}
2532};
2533
2534static PyObject *
2535wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2536{
2537 descrgetfunc func = (descrgetfunc)wrapped;
2538 PyObject *obj;
2539 PyObject *type = NULL;
2540
2541 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2542 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543 return (*func)(self, obj, type);
2544}
2545
2546static struct wrapperbase tab_descr_get[] = {
2547 {"__get__", (wrapperfunc)wrap_descr_get,
2548 "descr.__get__(obj, type) -> value"},
2549 {0}
2550};
2551
2552static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002553wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002554{
2555 descrsetfunc func = (descrsetfunc)wrapped;
2556 PyObject *obj, *value;
2557 int ret;
2558
2559 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2560 return NULL;
2561 ret = (*func)(self, obj, value);
2562 if (ret < 0)
2563 return NULL;
2564 Py_INCREF(Py_None);
2565 return Py_None;
2566}
2567
2568static struct wrapperbase tab_descr_set[] = {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002569 {"__set__", (wrapperfunc)wrap_descr_set,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570 "descr.__set__(obj, value)"},
2571 {0}
2572};
2573
2574static PyObject *
2575wrap_init(PyObject *self, PyObject *args, void *wrapped)
2576{
2577 initproc func = (initproc)wrapped;
2578
2579 /* XXX What about keyword arguments? */
2580 if (func(self, args, NULL) < 0)
2581 return NULL;
2582 Py_INCREF(Py_None);
2583 return Py_None;
2584}
2585
2586static struct wrapperbase tab_init[] = {
2587 {"__init__", (wrapperfunc)wrap_init,
2588 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002589 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590 {0}
2591};
2592
2593static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002594tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595{
Barry Warsaw60f01882001-08-22 19:24:42 +00002596 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002597 PyObject *arg0, *res;
2598
2599 if (self == NULL || !PyType_Check(self))
2600 Py_FatalError("__new__() called with non-type 'self'");
2601 type = (PyTypeObject *)self;
2602 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002603 PyErr_Format(PyExc_TypeError,
2604 "%s.__new__(): not enough arguments",
2605 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002606 return NULL;
2607 }
2608 arg0 = PyTuple_GET_ITEM(args, 0);
2609 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002610 PyErr_Format(PyExc_TypeError,
2611 "%s.__new__(X): X is not a type object (%s)",
2612 type->tp_name,
2613 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002614 return NULL;
2615 }
2616 subtype = (PyTypeObject *)arg0;
2617 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002618 PyErr_Format(PyExc_TypeError,
2619 "%s.__new__(%s): %s is not a subtype of %s",
2620 type->tp_name,
2621 subtype->tp_name,
2622 subtype->tp_name,
2623 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002624 return NULL;
2625 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002626
2627 /* Check that the use doesn't do something silly and unsafe like
2628 object.__new__(dictionary). To do this, we check that the
2629 most derived base that's not a heap type is this type. */
2630 staticbase = subtype;
2631 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2632 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002633 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002634 PyErr_Format(PyExc_TypeError,
2635 "%s.__new__(%s) is not safe, use %s.__new__()",
2636 type->tp_name,
2637 subtype->tp_name,
2638 staticbase == NULL ? "?" : staticbase->tp_name);
2639 return NULL;
2640 }
2641
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002642 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2643 if (args == NULL)
2644 return NULL;
2645 res = type->tp_new(subtype, args, kwds);
2646 Py_DECREF(args);
2647 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002648}
2649
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002650static struct PyMethodDef tp_new_methoddef[] = {
2651 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2652 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002653 {0}
2654};
2655
2656static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002657add_tp_new_wrapper(PyTypeObject *type)
2658{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002659 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002660
Guido van Rossum687ae002001-10-15 22:03:32 +00002661 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002662 return 0;
2663 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002664 if (func == NULL)
2665 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002666 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002667}
2668
Guido van Rossum13d52f02001-08-10 21:24:08 +00002669static int
2670add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2671{
Guido van Rossum687ae002001-10-15 22:03:32 +00002672 PyObject *dict = type->tp_dict;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002673
2674 for (; wraps->name != NULL; wraps++) {
2675 PyObject *descr;
2676 if (PyDict_GetItemString(dict, wraps->name))
2677 continue;
2678 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2679 if (descr == NULL)
2680 return -1;
2681 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2682 return -1;
2683 Py_DECREF(descr);
2684 }
2685 return 0;
2686}
2687
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002688/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002689 dictionary with method descriptors for function slots. For each
2690 function slot (like tp_repr) that's defined in the type, one or
Guido van Rossum687ae002001-10-15 22:03:32 +00002691 more corresponding descriptors are added in the type's tp_dict
Guido van Rossumf040ede2001-08-07 16:40:56 +00002692 dictionary under the appropriate name (like __repr__). Some
2693 function slots cause more than one descriptor to be added (for
2694 example, the nb_add slot adds both __add__ and __radd__
2695 descriptors) and some function slots compete for the same
2696 descriptor (for example both sq_item and mp_subscript generate a
2697 __getitem__ descriptor). This only adds new descriptors and
Guido van Rossum687ae002001-10-15 22:03:32 +00002698 doesn't overwrite entries in tp_dict that were previously
Guido van Rossumf040ede2001-08-07 16:40:56 +00002699 defined. The descriptors contain a reference to the C function
2700 they must call, so that it's safe if they are copied into a
2701 subtype's __dict__ and the subtype has a different C function in
2702 its slot -- calling the method defined by the descriptor will call
2703 the C function that was used to create it, rather than the C
2704 function present in the slot when it is called. (This is important
2705 because a subtype may have a C function in the slot that calls the
2706 method from the dictionary, and we want to avoid infinite recursion
2707 here.) */
2708
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002709static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710add_operators(PyTypeObject *type)
2711{
2712 PySequenceMethods *sq;
2713 PyMappingMethods *mp;
2714 PyNumberMethods *nb;
2715
2716#undef ADD
2717#define ADD(SLOT, TABLE) \
2718 if (SLOT) { \
2719 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2720 return -1; \
2721 }
2722
2723 if ((sq = type->tp_as_sequence) != NULL) {
2724 ADD(sq->sq_length, tab_len);
2725 ADD(sq->sq_concat, tab_concat);
2726 ADD(sq->sq_repeat, tab_mul_int);
2727 ADD(sq->sq_item, tab_getitem_int);
2728 ADD(sq->sq_slice, tab_getslice);
2729 ADD(sq->sq_ass_item, tab_setitem_int);
2730 ADD(sq->sq_ass_slice, tab_setslice);
2731 ADD(sq->sq_contains, tab_contains);
2732 ADD(sq->sq_inplace_concat, tab_iadd);
2733 ADD(sq->sq_inplace_repeat, tab_imul_int);
2734 }
2735
2736 if ((mp = type->tp_as_mapping) != NULL) {
2737 if (sq->sq_length == NULL)
2738 ADD(mp->mp_length, tab_len);
2739 ADD(mp->mp_subscript, tab_getitem);
2740 ADD(mp->mp_ass_subscript, tab_setitem);
2741 }
2742
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002743 if ((nb = type->tp_as_number) != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744 ADD(nb->nb_add, tab_add);
2745 ADD(nb->nb_subtract, tab_sub);
2746 ADD(nb->nb_multiply, tab_mul);
2747 ADD(nb->nb_divide, tab_div);
2748 ADD(nb->nb_remainder, tab_mod);
2749 ADD(nb->nb_divmod, tab_divmod);
2750 ADD(nb->nb_power, tab_pow);
2751 ADD(nb->nb_negative, tab_neg);
2752 ADD(nb->nb_positive, tab_pos);
2753 ADD(nb->nb_absolute, tab_abs);
2754 ADD(nb->nb_nonzero, tab_nonzero);
2755 ADD(nb->nb_invert, tab_invert);
2756 ADD(nb->nb_lshift, tab_lshift);
2757 ADD(nb->nb_rshift, tab_rshift);
2758 ADD(nb->nb_and, tab_and);
2759 ADD(nb->nb_xor, tab_xor);
2760 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002761 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762 ADD(nb->nb_int, tab_int);
2763 ADD(nb->nb_long, tab_long);
2764 ADD(nb->nb_float, tab_float);
2765 ADD(nb->nb_oct, tab_oct);
2766 ADD(nb->nb_hex, tab_hex);
2767 ADD(nb->nb_inplace_add, tab_iadd);
2768 ADD(nb->nb_inplace_subtract, tab_isub);
2769 ADD(nb->nb_inplace_multiply, tab_imul);
2770 ADD(nb->nb_inplace_divide, tab_idiv);
2771 ADD(nb->nb_inplace_remainder, tab_imod);
2772 ADD(nb->nb_inplace_power, tab_ipow);
2773 ADD(nb->nb_inplace_lshift, tab_ilshift);
2774 ADD(nb->nb_inplace_rshift, tab_irshift);
2775 ADD(nb->nb_inplace_and, tab_iand);
2776 ADD(nb->nb_inplace_xor, tab_ixor);
2777 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002778 if (type->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossum874f15a2001-09-25 21:16:33 +00002779 ADD(nb->nb_floor_divide, tab_floordiv);
2780 ADD(nb->nb_true_divide, tab_truediv);
2781 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2782 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2783 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784 }
2785
2786 ADD(type->tp_getattro, tab_getattr);
2787 ADD(type->tp_setattro, tab_setattr);
2788 ADD(type->tp_compare, tab_cmp);
2789 ADD(type->tp_repr, tab_repr);
2790 ADD(type->tp_hash, tab_hash);
2791 ADD(type->tp_call, tab_call);
2792 ADD(type->tp_str, tab_str);
2793 ADD(type->tp_richcompare, tab_richcmp);
2794 ADD(type->tp_iter, tab_iter);
2795 ADD(type->tp_iternext, tab_next);
2796 ADD(type->tp_descr_get, tab_descr_get);
2797 ADD(type->tp_descr_set, tab_descr_set);
2798 ADD(type->tp_init, tab_init);
2799
Guido van Rossumf040ede2001-08-07 16:40:56 +00002800 if (type->tp_new != NULL) {
2801 if (add_tp_new_wrapper(type) < 0)
2802 return -1;
2803 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002804
2805 return 0;
2806}
2807
Guido van Rossumf040ede2001-08-07 16:40:56 +00002808/* Slot wrappers that call the corresponding __foo__ slot. See comments
2809 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810
Guido van Rossumdc91b992001-08-08 22:26:22 +00002811#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002813FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002815 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002816 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817}
2818
Guido van Rossumdc91b992001-08-08 22:26:22 +00002819#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002821FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002823 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002824 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825}
2826
Guido van Rossumdc91b992001-08-08 22:26:22 +00002827
2828#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002829static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002830FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002831{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002832 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002833 int do_other = self->ob_type != other->ob_type && \
2834 other->ob_type->tp_as_number != NULL && \
2835 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002836 if (self->ob_type->tp_as_number != NULL && \
2837 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2838 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002839 if (do_other && \
2840 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2841 r = call_maybe( \
2842 other, ROPSTR, &rcache_str, "(O)", self); \
2843 if (r != Py_NotImplemented) \
2844 return r; \
2845 Py_DECREF(r); \
2846 do_other = 0; \
2847 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002848 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002849 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002850 if (r != Py_NotImplemented || \
2851 other->ob_type == self->ob_type) \
2852 return r; \
2853 Py_DECREF(r); \
2854 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002855 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002856 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002857 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002858 } \
2859 Py_INCREF(Py_NotImplemented); \
2860 return Py_NotImplemented; \
2861}
2862
2863#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2864 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2865
2866#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2867static PyObject * \
2868FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2869{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002870 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002871 return call_method(self, OPSTR, &cache_str, \
2872 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002873}
2874
2875static int
2876slot_sq_length(PyObject *self)
2877{
Guido van Rossum2730b132001-08-28 18:22:14 +00002878 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002879 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002880 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002881
2882 if (res == NULL)
2883 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002884 len = (int)PyInt_AsLong(res);
2885 Py_DECREF(res);
2886 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887}
2888
Guido van Rossumdc91b992001-08-08 22:26:22 +00002889SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2890SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002891
2892/* Super-optimized version of slot_sq_item.
2893 Other slots could do the same... */
2894static PyObject *
2895slot_sq_item(PyObject *self, int i)
2896{
2897 static PyObject *getitem_str;
2898 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2899 descrgetfunc f;
2900
2901 if (getitem_str == NULL) {
2902 getitem_str = PyString_InternFromString("__getitem__");
2903 if (getitem_str == NULL)
2904 return NULL;
2905 }
2906 func = _PyType_Lookup(self->ob_type, getitem_str);
2907 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002908 if ((f = func->ob_type->tp_descr_get) == NULL)
2909 Py_INCREF(func);
2910 else
2911 func = f(func, self, (PyObject *)(self->ob_type));
2912 ival = PyInt_FromLong(i);
2913 if (ival != NULL) {
2914 args = PyTuple_New(1);
2915 if (args != NULL) {
2916 PyTuple_SET_ITEM(args, 0, ival);
2917 retval = PyObject_Call(func, args, NULL);
2918 Py_XDECREF(args);
2919 Py_XDECREF(func);
2920 return retval;
2921 }
2922 }
2923 }
2924 else {
2925 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2926 }
2927 Py_XDECREF(args);
2928 Py_XDECREF(ival);
2929 Py_XDECREF(func);
2930 return NULL;
2931}
2932
Guido van Rossumdc91b992001-08-08 22:26:22 +00002933SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002934
2935static int
2936slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2937{
2938 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002939 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940
2941 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002942 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002943 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002944 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002945 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002946 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002947 if (res == NULL)
2948 return -1;
2949 Py_DECREF(res);
2950 return 0;
2951}
2952
2953static int
2954slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2955{
2956 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002957 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002958
2959 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002960 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002961 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002963 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002964 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965 if (res == NULL)
2966 return -1;
2967 Py_DECREF(res);
2968 return 0;
2969}
2970
2971static int
2972slot_sq_contains(PyObject *self, PyObject *value)
2973{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002974 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002975 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002976
Guido van Rossum55f20992001-10-01 17:18:22 +00002977 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002978
2979 if (func != NULL) {
2980 args = Py_BuildValue("(O)", value);
2981 if (args == NULL)
2982 res = NULL;
2983 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002984 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002985 Py_DECREF(args);
2986 }
2987 Py_DECREF(func);
2988 if (res == NULL)
2989 return -1;
2990 return PyObject_IsTrue(res);
2991 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002992 else if (PyErr_Occurred())
2993 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002994 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002995 return _PySequence_IterSearch(self, value,
2996 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002997 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002998}
2999
Guido van Rossumdc91b992001-08-08 22:26:22 +00003000SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3001SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002
3003#define slot_mp_length slot_sq_length
3004
Guido van Rossumdc91b992001-08-08 22:26:22 +00003005SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006
3007static int
3008slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3009{
3010 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003011 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012
3013 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003014 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003015 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003017 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003018 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019 if (res == NULL)
3020 return -1;
3021 Py_DECREF(res);
3022 return 0;
3023}
3024
Guido van Rossumdc91b992001-08-08 22:26:22 +00003025SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3026SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3027SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3028SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3029SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3030SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3031
3032staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3033
3034SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3035 nb_power, "__pow__", "__rpow__")
3036
3037static PyObject *
3038slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3039{
Guido van Rossum2730b132001-08-28 18:22:14 +00003040 static PyObject *pow_str;
3041
Guido van Rossumdc91b992001-08-08 22:26:22 +00003042 if (modulus == Py_None)
3043 return slot_nb_power_binary(self, other);
3044 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003045 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003046 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003047}
3048
3049SLOT0(slot_nb_negative, "__neg__")
3050SLOT0(slot_nb_positive, "__pos__")
3051SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052
3053static int
3054slot_nb_nonzero(PyObject *self)
3055{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003056 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003057 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058
Guido van Rossum55f20992001-10-01 17:18:22 +00003059 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003060 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003061 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003062 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003063 func = lookup_maybe(self, "__len__", &len_str);
3064 if (func == NULL) {
3065 if (PyErr_Occurred())
3066 return -1;
3067 else
3068 return 1;
3069 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003070 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003071 res = PyObject_CallObject(func, NULL);
3072 Py_DECREF(func);
3073 if (res == NULL)
3074 return -1;
3075 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003076}
3077
Guido van Rossumdc91b992001-08-08 22:26:22 +00003078SLOT0(slot_nb_invert, "__invert__")
3079SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3080SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3081SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3082SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3083SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003084
3085static int
3086slot_nb_coerce(PyObject **a, PyObject **b)
3087{
3088 static PyObject *coerce_str;
3089 PyObject *self = *a, *other = *b;
3090
3091 if (self->ob_type->tp_as_number != NULL &&
3092 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3093 PyObject *r;
3094 r = call_maybe(
3095 self, "__coerce__", &coerce_str, "(O)", other);
3096 if (r == NULL)
3097 return -1;
3098 if (r == Py_NotImplemented) {
3099 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003100 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003101 else {
3102 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3103 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003104 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003105 Py_DECREF(r);
3106 return -1;
3107 }
3108 *a = PyTuple_GET_ITEM(r, 0);
3109 Py_INCREF(*a);
3110 *b = PyTuple_GET_ITEM(r, 1);
3111 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003112 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003113 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003114 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003115 }
3116 if (other->ob_type->tp_as_number != NULL &&
3117 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3118 PyObject *r;
3119 r = call_maybe(
3120 other, "__coerce__", &coerce_str, "(O)", self);
3121 if (r == NULL)
3122 return -1;
3123 if (r == Py_NotImplemented) {
3124 Py_DECREF(r);
3125 return 1;
3126 }
3127 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3128 PyErr_SetString(PyExc_TypeError,
3129 "__coerce__ didn't return a 2-tuple");
3130 Py_DECREF(r);
3131 return -1;
3132 }
3133 *a = PyTuple_GET_ITEM(r, 1);
3134 Py_INCREF(*a);
3135 *b = PyTuple_GET_ITEM(r, 0);
3136 Py_INCREF(*b);
3137 Py_DECREF(r);
3138 return 0;
3139 }
3140 return 1;
3141}
3142
Guido van Rossumdc91b992001-08-08 22:26:22 +00003143SLOT0(slot_nb_int, "__int__")
3144SLOT0(slot_nb_long, "__long__")
3145SLOT0(slot_nb_float, "__float__")
3146SLOT0(slot_nb_oct, "__oct__")
3147SLOT0(slot_nb_hex, "__hex__")
3148SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3149SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3150SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3151SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3152SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3153SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3154SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3155SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3156SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3157SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3158SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3159SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3160 "__floordiv__", "__rfloordiv__")
3161SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3162SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3163SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003164
3165static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003166half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003168 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003169 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003170 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171
Guido van Rossum60718732001-08-28 17:47:51 +00003172 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003173 if (func == NULL) {
3174 PyErr_Clear();
3175 }
3176 else {
3177 args = Py_BuildValue("(O)", other);
3178 if (args == NULL)
3179 res = NULL;
3180 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003181 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003182 Py_DECREF(args);
3183 }
3184 if (res != Py_NotImplemented) {
3185 if (res == NULL)
3186 return -2;
3187 c = PyInt_AsLong(res);
3188 Py_DECREF(res);
3189 if (c == -1 && PyErr_Occurred())
3190 return -2;
3191 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3192 }
3193 Py_DECREF(res);
3194 }
3195 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003196}
3197
Guido van Rossumab3b0342001-09-18 20:38:53 +00003198/* This slot is published for the benefit of try_3way_compare in object.c */
3199int
3200_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003201{
3202 int c;
3203
Guido van Rossumab3b0342001-09-18 20:38:53 +00003204 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003205 c = half_compare(self, other);
3206 if (c <= 1)
3207 return c;
3208 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003209 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003210 c = half_compare(other, self);
3211 if (c < -1)
3212 return -2;
3213 if (c <= 1)
3214 return -c;
3215 }
3216 return (void *)self < (void *)other ? -1 :
3217 (void *)self > (void *)other ? 1 : 0;
3218}
3219
3220static PyObject *
3221slot_tp_repr(PyObject *self)
3222{
3223 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003224 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003225
Guido van Rossum60718732001-08-28 17:47:51 +00003226 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003227 if (func != NULL) {
3228 res = PyEval_CallObject(func, NULL);
3229 Py_DECREF(func);
3230 return res;
3231 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003232 PyErr_Clear();
3233 return PyString_FromFormat("<%s object at %p>",
3234 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003235}
3236
3237static PyObject *
3238slot_tp_str(PyObject *self)
3239{
3240 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003241 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003242
Guido van Rossum60718732001-08-28 17:47:51 +00003243 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003244 if (func != NULL) {
3245 res = PyEval_CallObject(func, NULL);
3246 Py_DECREF(func);
3247 return res;
3248 }
3249 else {
3250 PyErr_Clear();
3251 return slot_tp_repr(self);
3252 }
3253}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003254
3255static long
3256slot_tp_hash(PyObject *self)
3257{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003258 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003259 static PyObject *hash_str, *eq_str, *cmp_str;
3260
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261 long h;
3262
Guido van Rossum60718732001-08-28 17:47:51 +00003263 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003264
3265 if (func != NULL) {
3266 res = PyEval_CallObject(func, NULL);
3267 Py_DECREF(func);
3268 if (res == NULL)
3269 return -1;
3270 h = PyInt_AsLong(res);
3271 }
3272 else {
3273 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003274 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003275 if (func == NULL) {
3276 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003277 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278 }
3279 if (func != NULL) {
3280 Py_DECREF(func);
3281 PyErr_SetString(PyExc_TypeError, "unhashable type");
3282 return -1;
3283 }
3284 PyErr_Clear();
3285 h = _Py_HashPointer((void *)self);
3286 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003287 if (h == -1 && !PyErr_Occurred())
3288 h = -2;
3289 return h;
3290}
3291
3292static PyObject *
3293slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3294{
Guido van Rossum60718732001-08-28 17:47:51 +00003295 static PyObject *call_str;
3296 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003297 PyObject *res;
3298
3299 if (meth == NULL)
3300 return NULL;
3301 res = PyObject_Call(meth, args, kwds);
3302 Py_DECREF(meth);
3303 return res;
3304}
3305
Guido van Rossum14a6f832001-10-17 13:59:09 +00003306/* There are two slot dispatch functions for tp_getattro.
3307
3308 - slot_tp_getattro() is used when __getattribute__ is overridden
3309 but no __getattr__ hook is present;
3310
3311 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3312
3313 The code in update_slot() and fixup_slot_dispatchers() always installs
3314 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3315 installs the simpler slot if necessary. */
3316
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317static PyObject *
3318slot_tp_getattro(PyObject *self, PyObject *name)
3319{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003320 static PyObject *getattribute_str = NULL;
3321 return call_method(self, "__getattribute__", &getattribute_str,
3322 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003323}
3324
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003325static PyObject *
3326slot_tp_getattr_hook(PyObject *self, PyObject *name)
3327{
3328 PyTypeObject *tp = self->ob_type;
3329 PyObject *getattr, *getattribute, *res;
3330 static PyObject *getattribute_str = NULL;
3331 static PyObject *getattr_str = NULL;
3332
3333 if (getattr_str == NULL) {
3334 getattr_str = PyString_InternFromString("__getattr__");
3335 if (getattr_str == NULL)
3336 return NULL;
3337 }
3338 if (getattribute_str == NULL) {
3339 getattribute_str =
3340 PyString_InternFromString("__getattribute__");
3341 if (getattribute_str == NULL)
3342 return NULL;
3343 }
3344 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003345 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003346 /* No __getattr__ hook: use a simpler dispatcher */
3347 tp->tp_getattro = slot_tp_getattro;
3348 return slot_tp_getattro(self, name);
3349 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003350 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003351 if (getattribute == NULL ||
3352 (getattribute->ob_type == &PyWrapperDescr_Type &&
3353 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3354 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003355 res = PyObject_GenericGetAttr(self, name);
3356 else
3357 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003358 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003359 PyErr_Clear();
3360 res = PyObject_CallFunction(getattr, "OO", self, name);
3361 }
3362 return res;
3363}
3364
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365static int
3366slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3367{
3368 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003369 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003370
3371 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003372 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003373 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003374 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003375 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003376 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377 if (res == NULL)
3378 return -1;
3379 Py_DECREF(res);
3380 return 0;
3381}
3382
3383/* Map rich comparison operators to their __xx__ namesakes */
3384static char *name_op[] = {
3385 "__lt__",
3386 "__le__",
3387 "__eq__",
3388 "__ne__",
3389 "__gt__",
3390 "__ge__",
3391};
3392
3393static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003394half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003396 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003397 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003398
Guido van Rossum60718732001-08-28 17:47:51 +00003399 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003400 if (func == NULL) {
3401 PyErr_Clear();
3402 Py_INCREF(Py_NotImplemented);
3403 return Py_NotImplemented;
3404 }
3405 args = Py_BuildValue("(O)", other);
3406 if (args == NULL)
3407 res = NULL;
3408 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003409 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003410 Py_DECREF(args);
3411 }
3412 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413 return res;
3414}
3415
Guido van Rossumb8f63662001-08-15 23:57:02 +00003416/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3417static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3418
3419static PyObject *
3420slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3421{
3422 PyObject *res;
3423
3424 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3425 res = half_richcompare(self, other, op);
3426 if (res != Py_NotImplemented)
3427 return res;
3428 Py_DECREF(res);
3429 }
3430 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3431 res = half_richcompare(other, self, swapped_op[op]);
3432 if (res != Py_NotImplemented) {
3433 return res;
3434 }
3435 Py_DECREF(res);
3436 }
3437 Py_INCREF(Py_NotImplemented);
3438 return Py_NotImplemented;
3439}
3440
3441static PyObject *
3442slot_tp_iter(PyObject *self)
3443{
3444 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003445 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003446
Guido van Rossum60718732001-08-28 17:47:51 +00003447 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003448 if (func != NULL) {
3449 res = PyObject_CallObject(func, NULL);
3450 Py_DECREF(func);
3451 return res;
3452 }
3453 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003454 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003455 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003456 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003457 return NULL;
3458 }
3459 Py_DECREF(func);
3460 return PySeqIter_New(self);
3461}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003462
3463static PyObject *
3464slot_tp_iternext(PyObject *self)
3465{
Guido van Rossum2730b132001-08-28 18:22:14 +00003466 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003467 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003468}
3469
Guido van Rossum1a493502001-08-17 16:47:50 +00003470static PyObject *
3471slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3472{
3473 PyTypeObject *tp = self->ob_type;
3474 PyObject *get;
3475 static PyObject *get_str = NULL;
3476
3477 if (get_str == NULL) {
3478 get_str = PyString_InternFromString("__get__");
3479 if (get_str == NULL)
3480 return NULL;
3481 }
3482 get = _PyType_Lookup(tp, get_str);
3483 if (get == NULL) {
3484 /* Avoid further slowdowns */
3485 if (tp->tp_descr_get == slot_tp_descr_get)
3486 tp->tp_descr_get = NULL;
3487 Py_INCREF(self);
3488 return self;
3489 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003490 if (obj == NULL)
3491 obj = Py_None;
3492 if (type == NULL)
3493 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003494 return PyObject_CallFunction(get, "OOO", self, obj, type);
3495}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003496
3497static int
3498slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3499{
Guido van Rossum2c252392001-08-24 10:13:31 +00003500 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003501 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003502
3503 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003504 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003505 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003506 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003507 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003508 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509 if (res == NULL)
3510 return -1;
3511 Py_DECREF(res);
3512 return 0;
3513}
3514
3515static int
3516slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3517{
Guido van Rossum60718732001-08-28 17:47:51 +00003518 static PyObject *init_str;
3519 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003520 PyObject *res;
3521
3522 if (meth == NULL)
3523 return -1;
3524 res = PyObject_Call(meth, args, kwds);
3525 Py_DECREF(meth);
3526 if (res == NULL)
3527 return -1;
3528 Py_DECREF(res);
3529 return 0;
3530}
3531
3532static PyObject *
3533slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3534{
3535 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3536 PyObject *newargs, *x;
3537 int i, n;
3538
3539 if (func == NULL)
3540 return NULL;
3541 assert(PyTuple_Check(args));
3542 n = PyTuple_GET_SIZE(args);
3543 newargs = PyTuple_New(n+1);
3544 if (newargs == NULL)
3545 return NULL;
3546 Py_INCREF(type);
3547 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3548 for (i = 0; i < n; i++) {
3549 x = PyTuple_GET_ITEM(args, i);
3550 Py_INCREF(x);
3551 PyTuple_SET_ITEM(newargs, i+1, x);
3552 }
3553 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003554 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003555 Py_DECREF(func);
3556 return x;
3557}
3558
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003559
3560/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3561 functions. The offsets here are relative to the 'etype' structure, which
3562 incorporates the additional structures used for numbers, sequences and
3563 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3564 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3565 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3566
3567typedef struct {
3568 char *name;
3569 int offset;
3570 void *function;
3571 wrapperfunc wrapper;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003572 PyObject *name_strobj;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003573} slotdef;
3574
3575#undef TPSLOT
3576#undef ETSLOT
3577#undef SQSLOT
3578#undef MPSLOT
3579#undef NBSLOT
3580#undef BINSLOT
3581#undef RBINSLOT
3582
3583#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
Guido van Rossum825d8752001-10-15 19:44:24 +00003584 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003585#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
Guido van Rossum825d8752001-10-15 19:44:24 +00003586 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003587#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3588 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER)
3589#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3590 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER)
3591#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3592 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER)
3593#define BINSLOT(NAME, SLOT, FUNCTION) \
3594 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l)
3595#define RBINSLOT(NAME, SLOT, FUNCTION) \
3596 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r)
3597
3598static slotdef slotdefs[] = {
3599 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry),
3600 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc),
3601 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3602 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3603 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item),
3604 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc),
3605 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem),
3606 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem),
3607 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3608 wrap_intintobjargproc),
3609 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice),
3610 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc),
3611 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3612 wrap_binaryfunc),
3613 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3614 wrap_intargfunc),
3615
3616 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003617 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3618 wrap_binaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003619 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3620 wrap_objobjargproc),
3621 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3622 wrap_delitem),
3623
3624 BINSLOT("__add__", nb_add, slot_nb_add),
3625 RBINSLOT("__radd__", nb_add, slot_nb_add),
3626 BINSLOT("__sub__", nb_subtract, slot_nb_subtract),
3627 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract),
3628 BINSLOT("__mul__", nb_multiply, slot_nb_multiply),
3629 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply),
3630 BINSLOT("__div__", nb_divide, slot_nb_divide),
3631 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide),
3632 BINSLOT("__mod__", nb_remainder, slot_nb_remainder),
3633 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder),
3634 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod),
3635 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod),
3636 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc),
3637 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r),
3638 NBSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc),
3639 NBSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc),
3640 NBSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc),
3641 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc),
3642 NBSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc),
3643 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift),
3644 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift),
3645 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift),
3646 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift),
3647 BINSLOT("__and__", nb_and, slot_nb_and),
3648 RBINSLOT("__rand__", nb_and, slot_nb_and),
3649 BINSLOT("__xor__", nb_xor, slot_nb_xor),
3650 RBINSLOT("__rxor__", nb_xor, slot_nb_xor),
3651 BINSLOT("__or__", nb_or, slot_nb_or),
3652 RBINSLOT("__ror__", nb_or, slot_nb_or),
3653 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc),
3654 NBSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc),
3655 NBSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc),
3656 NBSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc),
3657 NBSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc),
3658 NBSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc),
3659 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3660 wrap_binaryfunc),
3661 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3662 wrap_binaryfunc),
3663 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3664 wrap_binaryfunc),
3665 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3666 wrap_binaryfunc),
3667 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3668 wrap_binaryfunc),
3669 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3670 wrap_ternaryfunc),
3671 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3672 wrap_binaryfunc),
3673 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3674 wrap_binaryfunc),
3675 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3676 wrap_binaryfunc),
3677 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3678 wrap_binaryfunc),
3679 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3680 wrap_binaryfunc),
3681 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide),
3682 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide),
3683 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide),
3684 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide),
3685 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3686 slot_nb_inplace_floor_divide, wrap_binaryfunc),
3687 NBSLOT("__itruediv__", nb_inplace_true_divide,
3688 slot_nb_inplace_true_divide, wrap_binaryfunc),
3689
3690 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003691 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003692 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc),
3693 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc),
3694 TPSLOT("__call__", tp_call, slot_tp_call, wrap_call),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003695 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003696 wrap_binaryfunc),
3697 TPSLOT("__getattribute__", tp_getattr, NULL, NULL),
3698 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL),
3699 TPSLOT("__getattr__", tp_getattr, NULL, NULL),
3700 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr),
3701 TPSLOT("__setattr__", tp_setattr, NULL, NULL),
3702 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr),
3703 TPSLOT("__delattr__", tp_setattr, NULL, NULL),
3704 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt),
3705 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le),
3706 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq),
3707 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne),
3708 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt),
3709 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge),
3710 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc),
3711 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next),
3712 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get),
3713 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set),
3714 TPSLOT("__init__", tp_init, slot_tp_init, wrap_init),
3715 TPSLOT("__new__", tp_new, slot_tp_new, NULL),
3716 {NULL}
3717};
3718
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003719static void **
3720slotptr(PyTypeObject *type, int offset)
3721{
3722 char *ptr;
3723
3724 assert(offset >= 0);
3725 assert(offset < offsetof(etype, as_buffer));
3726 if (offset >= offsetof(etype, as_mapping)) {
3727 ptr = (void *)type->tp_as_mapping;
3728 offset -= offsetof(etype, as_mapping);
3729 }
3730 else if (offset >= offsetof(etype, as_sequence)) {
3731 ptr = (void *)type->tp_as_sequence;
3732 offset -= offsetof(etype, as_sequence);
3733 }
3734 else if (offset >= offsetof(etype, as_number)) {
3735 ptr = (void *)type->tp_as_number;
3736 offset -= offsetof(etype, as_number);
3737 }
3738 else {
3739 ptr = (void *)type;
3740 }
3741 if (ptr != NULL)
3742 ptr += offset;
3743 return (void **)ptr;
3744}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003745
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003746staticforward int recurse_down_subclasses(PyTypeObject *type,
3747 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003748
3749static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003750update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003751{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003752 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003753
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003754 for (pp = pp0; *pp; pp++) {
3755 slotdef *p = *pp;
3756 PyObject *descr;
3757 PyWrapperDescrObject *d;
3758 void *generic = NULL, *specific = NULL;
3759 int use_generic = 0;
3760 int offset = p->offset;
3761 void **ptr = slotptr(type, offset);
3762 if (ptr == NULL)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003763 continue;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003764 do {
3765 descr = _PyType_Lookup(type, p->name_strobj);
3766 if (descr == NULL)
3767 continue;
3768 generic = p->function;
3769 if (descr->ob_type == &PyWrapperDescr_Type) {
3770 d = (PyWrapperDescrObject *)descr;
3771 if (d->d_base->wrapper == p->wrapper &&
3772 PyType_IsSubtype(type, d->d_type)) {
3773 if (specific == NULL ||
3774 specific == d->d_wrapped)
3775 specific = d->d_wrapped;
3776 else
3777 use_generic = 1;
3778 }
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003779 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003780 else
3781 use_generic = 1;
3782 } while ((++p)->offset == offset);
3783 if (specific && !use_generic)
3784 *ptr = specific;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003785 else
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003786 *ptr = generic;
3787 }
3788 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003789}
3790
3791static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003792recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003793{
3794 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003795 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003796 int i, n;
3797
3798 subclasses = type->tp_subclasses;
3799 if (subclasses == NULL)
3800 return 0;
3801 assert(PyList_Check(subclasses));
3802 n = PyList_GET_SIZE(subclasses);
3803 for (i = 0; i < n; i++) {
3804 ref = PyList_GET_ITEM(subclasses, i);
3805 assert(PyWeakref_CheckRef(ref));
3806 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3807 if (subclass == NULL)
3808 continue;
3809 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003810 /* Avoid recursing down into unaffected classes */
3811 dict = subclass->tp_dict;
3812 if (dict != NULL && PyDict_Check(dict) &&
3813 PyDict_GetItem(dict, name) != NULL)
3814 continue;
3815 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003816 return -1;
3817 }
3818 return 0;
3819}
3820
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003821static int
3822slotdef_cmp(const void *aa, const void *bb)
3823{
3824 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3825 int c = a->offset - b->offset;
3826 if (c != 0)
3827 return c;
3828 else
3829 return a - b;
3830}
3831
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003832static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003833init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003834{
3835 slotdef *p;
3836 static int initialized = 0;
3837
3838 if (initialized)
3839 return;
3840 for (p = slotdefs; p->name; p++) {
3841 p->name_strobj = PyString_InternFromString(p->name);
3842 if (!p->name_strobj)
3843 Py_FatalError("XXX ouch");
3844 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003845 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3846 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003847 initialized = 1;
3848}
3849
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003850static int
3851update_slot(PyTypeObject *type, PyObject *name)
3852{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003853 slotdef *ptrs[10];
3854 slotdef *p;
3855 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003856 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003857
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003858 init_slotdefs();
3859 pp = ptrs;
3860 for (p = slotdefs; p->name; p++) {
3861 /* XXX assume name is interned! */
3862 if (p->name_strobj == name)
3863 *pp++ = p;
3864 }
3865 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003866 for (pp = ptrs; *pp; pp++) {
3867 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003868 offset = p->offset;
3869 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003870 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003871 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003872 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003873 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003874}
3875
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003877fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003878{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003879 slotdef *p;
3880 PyObject *mro, *descr;
3881 PyTypeObject *base;
3882 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003883 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003884 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003885 void *generic, *specific;
3886 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003888 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003889 mro = type->tp_mro;
3890 assert(PyTuple_Check(mro));
3891 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003892 for (p = slotdefs; p->name; ) {
3893 offset = p->offset;
3894 ptr = slotptr(type, offset);
3895 if (!ptr) {
3896 do {
3897 ++p;
3898 } while (p->offset == offset);
3899 continue;
3900 }
3901 generic = specific = NULL;
3902 use_generic = 0;
3903 do {
3904 descr = NULL;
3905 for (i = 0; i < n; i++) {
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003906 base = (PyTypeObject *)
3907 PyTuple_GET_ITEM(mro, i);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003908 assert(PyType_Check(base));
3909 descr = PyDict_GetItem(
Guido van Rossum687ae002001-10-15 22:03:32 +00003910 base->tp_dict, p->name_strobj);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003911 if (descr != NULL)
3912 break;
3913 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003914 if (descr == NULL)
3915 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003916 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003917 if (descr->ob_type == &PyWrapperDescr_Type) {
3918 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003919 if (d->d_base->wrapper == p->wrapper &&
Guido van Rossumcaf59042001-10-17 07:15:43 +00003920 PyType_IsSubtype(type, d->d_type))
3921 {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003922 if (specific == NULL ||
Guido van Rossumcaf59042001-10-17 07:15:43 +00003923 specific == d->d_wrapped)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003924 specific = d->d_wrapped;
3925 else
3926 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003927 }
3928 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003929 else
3930 use_generic = 1;
3931 } while ((++p)->offset == offset);
3932 if (specific && !use_generic)
3933 *ptr = specific;
3934 else
3935 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003936 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003937}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003938
3939
3940/* Cooperative 'super' */
3941
3942typedef struct {
3943 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003944 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003945 PyObject *obj;
3946} superobject;
3947
Guido van Rossum6f799372001-09-20 20:46:19 +00003948static PyMemberDef super_members[] = {
3949 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3950 "the class invoking super()"},
3951 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3952 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003953 {0}
3954};
3955
Guido van Rossum705f0f52001-08-24 16:47:00 +00003956static void
3957super_dealloc(PyObject *self)
3958{
3959 superobject *su = (superobject *)self;
3960
Guido van Rossum048eb752001-10-02 21:24:57 +00003961 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003962 Py_XDECREF(su->obj);
3963 Py_XDECREF(su->type);
3964 self->ob_type->tp_free(self);
3965}
3966
3967static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003968super_repr(PyObject *self)
3969{
3970 superobject *su = (superobject *)self;
3971
3972 if (su->obj)
3973 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003974 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003975 su->type ? su->type->tp_name : "NULL",
3976 su->obj->ob_type->tp_name);
3977 else
3978 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003979 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003980 su->type ? su->type->tp_name : "NULL");
3981}
3982
3983static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003984super_getattro(PyObject *self, PyObject *name)
3985{
3986 superobject *su = (superobject *)self;
3987
3988 if (su->obj != NULL) {
3989 PyObject *mro, *res, *tmp;
3990 descrgetfunc f;
3991 int i, n;
3992
Guido van Rossume705ef12001-08-29 15:47:06 +00003993 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003994 if (mro == NULL)
3995 n = 0;
3996 else {
3997 assert(PyTuple_Check(mro));
3998 n = PyTuple_GET_SIZE(mro);
3999 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004000 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004001 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004002 break;
4003 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004004 if (i >= n && PyType_Check(su->obj)) {
4005 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004006 if (mro == NULL)
4007 n = 0;
4008 else {
4009 assert(PyTuple_Check(mro));
4010 n = PyTuple_GET_SIZE(mro);
4011 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004012 for (i = 0; i < n; i++) {
4013 if ((PyObject *)(su->type) ==
4014 PyTuple_GET_ITEM(mro, i))
4015 break;
4016 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004017 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004018 i++;
4019 res = NULL;
4020 for (; i < n; i++) {
4021 tmp = PyTuple_GET_ITEM(mro, i);
4022 assert(PyType_Check(tmp));
4023 res = PyDict_GetItem(
Guido van Rossum687ae002001-10-15 22:03:32 +00004024 ((PyTypeObject *)tmp)->tp_dict, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004025 if (res != NULL) {
4026 Py_INCREF(res);
4027 f = res->ob_type->tp_descr_get;
4028 if (f != NULL) {
4029 tmp = f(res, su->obj, res);
4030 Py_DECREF(res);
4031 res = tmp;
4032 }
4033 return res;
4034 }
4035 }
4036 }
4037 return PyObject_GenericGetAttr(self, name);
4038}
4039
4040static PyObject *
4041super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4042{
4043 superobject *su = (superobject *)self;
4044 superobject *new;
4045
4046 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4047 /* Not binding to an object, or already bound */
4048 Py_INCREF(self);
4049 return self;
4050 }
4051 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
4052 if (new == NULL)
4053 return NULL;
4054 Py_INCREF(su->type);
4055 Py_INCREF(obj);
4056 new->type = su->type;
4057 new->obj = obj;
4058 return (PyObject *)new;
4059}
4060
4061static int
4062super_init(PyObject *self, PyObject *args, PyObject *kwds)
4063{
4064 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004065 PyTypeObject *type;
4066 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004067
4068 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4069 return -1;
4070 if (obj == Py_None)
4071 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00004072 if (obj != NULL &&
4073 !PyType_IsSubtype(obj->ob_type, type) &&
4074 !(PyType_Check(obj) &&
4075 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004076 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00004077 "super(type, obj): "
4078 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004079 return -1;
4080 }
4081 Py_INCREF(type);
4082 Py_XINCREF(obj);
4083 su->type = type;
4084 su->obj = obj;
4085 return 0;
4086}
4087
4088static char super_doc[] =
4089"super(type) -> unbound super object\n"
4090"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004091"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004092"Typical use to call a cooperative superclass method:\n"
4093"class C(B):\n"
4094" def meth(self, arg):\n"
4095" super(C, self).meth(arg)";
4096
Guido van Rossum048eb752001-10-02 21:24:57 +00004097static int
4098super_traverse(PyObject *self, visitproc visit, void *arg)
4099{
4100 superobject *su = (superobject *)self;
4101 int err;
4102
4103#define VISIT(SLOT) \
4104 if (SLOT) { \
4105 err = visit((PyObject *)(SLOT), arg); \
4106 if (err) \
4107 return err; \
4108 }
4109
4110 VISIT(su->obj);
4111 VISIT(su->type);
4112
4113#undef VISIT
4114
4115 return 0;
4116}
4117
Guido van Rossum705f0f52001-08-24 16:47:00 +00004118PyTypeObject PySuper_Type = {
4119 PyObject_HEAD_INIT(&PyType_Type)
4120 0, /* ob_size */
4121 "super", /* tp_name */
4122 sizeof(superobject), /* tp_basicsize */
4123 0, /* tp_itemsize */
4124 /* methods */
4125 super_dealloc, /* tp_dealloc */
4126 0, /* tp_print */
4127 0, /* tp_getattr */
4128 0, /* tp_setattr */
4129 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004130 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004131 0, /* tp_as_number */
4132 0, /* tp_as_sequence */
4133 0, /* tp_as_mapping */
4134 0, /* tp_hash */
4135 0, /* tp_call */
4136 0, /* tp_str */
4137 super_getattro, /* tp_getattro */
4138 0, /* tp_setattro */
4139 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004140 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4141 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004142 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004143 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004144 0, /* tp_clear */
4145 0, /* tp_richcompare */
4146 0, /* tp_weaklistoffset */
4147 0, /* tp_iter */
4148 0, /* tp_iternext */
4149 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004150 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004151 0, /* tp_getset */
4152 0, /* tp_base */
4153 0, /* tp_dict */
4154 super_descr_get, /* tp_descr_get */
4155 0, /* tp_descr_set */
4156 0, /* tp_dictoffset */
4157 super_init, /* tp_init */
4158 PyType_GenericAlloc, /* tp_alloc */
4159 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004160 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004161};