blob: 901d0268049f8773e169ae7a7bdaa428ab8edc9a [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) {
2908 if (func->ob_type == &PyWrapperDescr_Type) {
2909 PyWrapperDescrObject *wrapper =
2910 (PyWrapperDescrObject *)func;
2911 if (wrapper->d_base->wrapper == wrap_sq_item) {
2912 intargfunc f;
2913 f = (intargfunc)(wrapper->d_wrapped);
2914 return f(self, i);
2915 }
2916 }
2917 if ((f = func->ob_type->tp_descr_get) == NULL)
2918 Py_INCREF(func);
2919 else
2920 func = f(func, self, (PyObject *)(self->ob_type));
2921 ival = PyInt_FromLong(i);
2922 if (ival != NULL) {
2923 args = PyTuple_New(1);
2924 if (args != NULL) {
2925 PyTuple_SET_ITEM(args, 0, ival);
2926 retval = PyObject_Call(func, args, NULL);
2927 Py_XDECREF(args);
2928 Py_XDECREF(func);
2929 return retval;
2930 }
2931 }
2932 }
2933 else {
2934 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2935 }
2936 Py_XDECREF(args);
2937 Py_XDECREF(ival);
2938 Py_XDECREF(func);
2939 return NULL;
2940}
2941
Guido van Rossumdc91b992001-08-08 22:26:22 +00002942SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002943
2944static int
2945slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2946{
2947 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002948 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002949
2950 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002951 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002952 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002954 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002955 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956 if (res == NULL)
2957 return -1;
2958 Py_DECREF(res);
2959 return 0;
2960}
2961
2962static int
2963slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2964{
2965 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002966 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967
2968 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002969 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002970 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002972 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002973 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974 if (res == NULL)
2975 return -1;
2976 Py_DECREF(res);
2977 return 0;
2978}
2979
2980static int
2981slot_sq_contains(PyObject *self, PyObject *value)
2982{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002983 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002984 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985
Guido van Rossum55f20992001-10-01 17:18:22 +00002986 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002987
2988 if (func != NULL) {
2989 args = Py_BuildValue("(O)", value);
2990 if (args == NULL)
2991 res = NULL;
2992 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002993 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002994 Py_DECREF(args);
2995 }
2996 Py_DECREF(func);
2997 if (res == NULL)
2998 return -1;
2999 return PyObject_IsTrue(res);
3000 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003001 else if (PyErr_Occurred())
3002 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003003 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003004 return _PySequence_IterSearch(self, value,
3005 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003006 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007}
3008
Guido van Rossumdc91b992001-08-08 22:26:22 +00003009SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3010SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003011
3012#define slot_mp_length slot_sq_length
3013
Guido van Rossumdc91b992001-08-08 22:26:22 +00003014SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015
3016static int
3017slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3018{
3019 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003020 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021
3022 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003023 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003024 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003026 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003027 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028 if (res == NULL)
3029 return -1;
3030 Py_DECREF(res);
3031 return 0;
3032}
3033
Guido van Rossumdc91b992001-08-08 22:26:22 +00003034SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3035SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3036SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3037SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3038SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3039SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3040
3041staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3042
3043SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3044 nb_power, "__pow__", "__rpow__")
3045
3046static PyObject *
3047slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3048{
Guido van Rossum2730b132001-08-28 18:22:14 +00003049 static PyObject *pow_str;
3050
Guido van Rossumdc91b992001-08-08 22:26:22 +00003051 if (modulus == Py_None)
3052 return slot_nb_power_binary(self, other);
3053 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003054 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003055 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003056}
3057
3058SLOT0(slot_nb_negative, "__neg__")
3059SLOT0(slot_nb_positive, "__pos__")
3060SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061
3062static int
3063slot_nb_nonzero(PyObject *self)
3064{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003065 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003066 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067
Guido van Rossum55f20992001-10-01 17:18:22 +00003068 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003069 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003070 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003071 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003072 func = lookup_maybe(self, "__len__", &len_str);
3073 if (func == NULL) {
3074 if (PyErr_Occurred())
3075 return -1;
3076 else
3077 return 1;
3078 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003079 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003080 res = PyObject_CallObject(func, NULL);
3081 Py_DECREF(func);
3082 if (res == NULL)
3083 return -1;
3084 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085}
3086
Guido van Rossumdc91b992001-08-08 22:26:22 +00003087SLOT0(slot_nb_invert, "__invert__")
3088SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3089SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3090SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3091SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3092SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003093
3094static int
3095slot_nb_coerce(PyObject **a, PyObject **b)
3096{
3097 static PyObject *coerce_str;
3098 PyObject *self = *a, *other = *b;
3099
3100 if (self->ob_type->tp_as_number != NULL &&
3101 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3102 PyObject *r;
3103 r = call_maybe(
3104 self, "__coerce__", &coerce_str, "(O)", other);
3105 if (r == NULL)
3106 return -1;
3107 if (r == Py_NotImplemented) {
3108 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003109 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003110 else {
3111 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3112 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003113 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003114 Py_DECREF(r);
3115 return -1;
3116 }
3117 *a = PyTuple_GET_ITEM(r, 0);
3118 Py_INCREF(*a);
3119 *b = PyTuple_GET_ITEM(r, 1);
3120 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003121 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003122 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003123 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003124 }
3125 if (other->ob_type->tp_as_number != NULL &&
3126 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3127 PyObject *r;
3128 r = call_maybe(
3129 other, "__coerce__", &coerce_str, "(O)", self);
3130 if (r == NULL)
3131 return -1;
3132 if (r == Py_NotImplemented) {
3133 Py_DECREF(r);
3134 return 1;
3135 }
3136 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3137 PyErr_SetString(PyExc_TypeError,
3138 "__coerce__ didn't return a 2-tuple");
3139 Py_DECREF(r);
3140 return -1;
3141 }
3142 *a = PyTuple_GET_ITEM(r, 1);
3143 Py_INCREF(*a);
3144 *b = PyTuple_GET_ITEM(r, 0);
3145 Py_INCREF(*b);
3146 Py_DECREF(r);
3147 return 0;
3148 }
3149 return 1;
3150}
3151
Guido van Rossumdc91b992001-08-08 22:26:22 +00003152SLOT0(slot_nb_int, "__int__")
3153SLOT0(slot_nb_long, "__long__")
3154SLOT0(slot_nb_float, "__float__")
3155SLOT0(slot_nb_oct, "__oct__")
3156SLOT0(slot_nb_hex, "__hex__")
3157SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3158SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3159SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3160SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3161SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3162SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3163SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3164SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3165SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3166SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3167SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3168SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3169 "__floordiv__", "__rfloordiv__")
3170SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3171SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3172SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003173
3174static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003175half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003177 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003178 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003179 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003180
Guido van Rossum60718732001-08-28 17:47:51 +00003181 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003182 if (func == NULL) {
3183 PyErr_Clear();
3184 }
3185 else {
3186 args = Py_BuildValue("(O)", other);
3187 if (args == NULL)
3188 res = NULL;
3189 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003190 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003191 Py_DECREF(args);
3192 }
3193 if (res != Py_NotImplemented) {
3194 if (res == NULL)
3195 return -2;
3196 c = PyInt_AsLong(res);
3197 Py_DECREF(res);
3198 if (c == -1 && PyErr_Occurred())
3199 return -2;
3200 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3201 }
3202 Py_DECREF(res);
3203 }
3204 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205}
3206
Guido van Rossumab3b0342001-09-18 20:38:53 +00003207/* This slot is published for the benefit of try_3way_compare in object.c */
3208int
3209_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003210{
3211 int c;
3212
Guido van Rossumab3b0342001-09-18 20:38:53 +00003213 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003214 c = half_compare(self, other);
3215 if (c <= 1)
3216 return c;
3217 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003218 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003219 c = half_compare(other, self);
3220 if (c < -1)
3221 return -2;
3222 if (c <= 1)
3223 return -c;
3224 }
3225 return (void *)self < (void *)other ? -1 :
3226 (void *)self > (void *)other ? 1 : 0;
3227}
3228
3229static PyObject *
3230slot_tp_repr(PyObject *self)
3231{
3232 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003233 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003234
Guido van Rossum60718732001-08-28 17:47:51 +00003235 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003236 if (func != NULL) {
3237 res = PyEval_CallObject(func, NULL);
3238 Py_DECREF(func);
3239 return res;
3240 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003241 PyErr_Clear();
3242 return PyString_FromFormat("<%s object at %p>",
3243 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003244}
3245
3246static PyObject *
3247slot_tp_str(PyObject *self)
3248{
3249 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003250 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003251
Guido van Rossum60718732001-08-28 17:47:51 +00003252 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003253 if (func != NULL) {
3254 res = PyEval_CallObject(func, NULL);
3255 Py_DECREF(func);
3256 return res;
3257 }
3258 else {
3259 PyErr_Clear();
3260 return slot_tp_repr(self);
3261 }
3262}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003263
3264static long
3265slot_tp_hash(PyObject *self)
3266{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003267 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003268 static PyObject *hash_str, *eq_str, *cmp_str;
3269
Tim Peters6d6c1a32001-08-02 04:15:00 +00003270 long h;
3271
Guido van Rossum60718732001-08-28 17:47:51 +00003272 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273
3274 if (func != NULL) {
3275 res = PyEval_CallObject(func, NULL);
3276 Py_DECREF(func);
3277 if (res == NULL)
3278 return -1;
3279 h = PyInt_AsLong(res);
3280 }
3281 else {
3282 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003283 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003284 if (func == NULL) {
3285 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003286 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003287 }
3288 if (func != NULL) {
3289 Py_DECREF(func);
3290 PyErr_SetString(PyExc_TypeError, "unhashable type");
3291 return -1;
3292 }
3293 PyErr_Clear();
3294 h = _Py_HashPointer((void *)self);
3295 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296 if (h == -1 && !PyErr_Occurred())
3297 h = -2;
3298 return h;
3299}
3300
3301static PyObject *
3302slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3303{
Guido van Rossum60718732001-08-28 17:47:51 +00003304 static PyObject *call_str;
3305 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306 PyObject *res;
3307
3308 if (meth == NULL)
3309 return NULL;
3310 res = PyObject_Call(meth, args, kwds);
3311 Py_DECREF(meth);
3312 return res;
3313}
3314
Tim Peters6d6c1a32001-08-02 04:15:00 +00003315static PyObject *
3316slot_tp_getattro(PyObject *self, PyObject *name)
3317{
3318 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003320 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003321
Guido van Rossum8e248182001-08-12 05:17:56 +00003322 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003323 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003324 if (getattr_str == NULL)
3325 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003326 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003327 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003328 if (getattr == NULL) {
3329 /* Avoid further slowdowns */
3330 if (tp->tp_getattro == slot_tp_getattro)
3331 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003332 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003333 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003334 return PyObject_CallFunction(getattr, "OO", self, name);
3335}
3336
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003337static PyObject *
3338slot_tp_getattr_hook(PyObject *self, PyObject *name)
3339{
3340 PyTypeObject *tp = self->ob_type;
3341 PyObject *getattr, *getattribute, *res;
3342 static PyObject *getattribute_str = NULL;
3343 static PyObject *getattr_str = NULL;
3344
3345 if (getattr_str == NULL) {
3346 getattr_str = PyString_InternFromString("__getattr__");
3347 if (getattr_str == NULL)
3348 return NULL;
3349 }
3350 if (getattribute_str == NULL) {
3351 getattribute_str =
3352 PyString_InternFromString("__getattribute__");
3353 if (getattribute_str == NULL)
3354 return NULL;
3355 }
3356 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003357 if (getattr == NULL && tp->tp_getattro == slot_tp_getattr_hook) {
3358 /* No __getattr__ hook: use a simpler dispatcher */
3359 tp->tp_getattro = slot_tp_getattro;
3360 return slot_tp_getattro(self, name);
3361 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003362 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003363 if (getattribute != NULL &&
3364 getattribute->ob_type == &PyWrapperDescr_Type &&
3365 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
Guido van Rossum825d8752001-10-15 19:44:24 +00003366 (void *)PyObject_GenericGetAttr)
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003367 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003368 if (getattr == NULL && getattribute == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003369 /* Use the default dispatcher */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003370 if (tp->tp_getattro == slot_tp_getattr_hook)
3371 tp->tp_getattro = PyObject_GenericGetAttr;
3372 return PyObject_GenericGetAttr(self, name);
3373 }
3374 if (getattribute == NULL)
3375 res = PyObject_GenericGetAttr(self, name);
3376 else
3377 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003378 if (getattr != NULL &&
3379 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003380 PyErr_Clear();
3381 res = PyObject_CallFunction(getattr, "OO", self, name);
3382 }
3383 return res;
3384}
3385
Tim Peters6d6c1a32001-08-02 04:15:00 +00003386static int
3387slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3388{
3389 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003390 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391
3392 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003393 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003394 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003396 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003397 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003398 if (res == NULL)
3399 return -1;
3400 Py_DECREF(res);
3401 return 0;
3402}
3403
3404/* Map rich comparison operators to their __xx__ namesakes */
3405static char *name_op[] = {
3406 "__lt__",
3407 "__le__",
3408 "__eq__",
3409 "__ne__",
3410 "__gt__",
3411 "__ge__",
3412};
3413
3414static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003415half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003417 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003418 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419
Guido van Rossum60718732001-08-28 17:47:51 +00003420 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003421 if (func == NULL) {
3422 PyErr_Clear();
3423 Py_INCREF(Py_NotImplemented);
3424 return Py_NotImplemented;
3425 }
3426 args = Py_BuildValue("(O)", other);
3427 if (args == NULL)
3428 res = NULL;
3429 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003430 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003431 Py_DECREF(args);
3432 }
3433 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434 return res;
3435}
3436
Guido van Rossumb8f63662001-08-15 23:57:02 +00003437/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3438static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3439
3440static PyObject *
3441slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3442{
3443 PyObject *res;
3444
3445 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3446 res = half_richcompare(self, other, op);
3447 if (res != Py_NotImplemented)
3448 return res;
3449 Py_DECREF(res);
3450 }
3451 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3452 res = half_richcompare(other, self, swapped_op[op]);
3453 if (res != Py_NotImplemented) {
3454 return res;
3455 }
3456 Py_DECREF(res);
3457 }
3458 Py_INCREF(Py_NotImplemented);
3459 return Py_NotImplemented;
3460}
3461
3462static PyObject *
3463slot_tp_iter(PyObject *self)
3464{
3465 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003466 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003467
Guido van Rossum60718732001-08-28 17:47:51 +00003468 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003469 if (func != NULL) {
3470 res = PyObject_CallObject(func, NULL);
3471 Py_DECREF(func);
3472 return res;
3473 }
3474 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003475 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003476 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003477 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003478 return NULL;
3479 }
3480 Py_DECREF(func);
3481 return PySeqIter_New(self);
3482}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483
3484static PyObject *
3485slot_tp_iternext(PyObject *self)
3486{
Guido van Rossum2730b132001-08-28 18:22:14 +00003487 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003488 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489}
3490
Guido van Rossum1a493502001-08-17 16:47:50 +00003491static PyObject *
3492slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3493{
3494 PyTypeObject *tp = self->ob_type;
3495 PyObject *get;
3496 static PyObject *get_str = NULL;
3497
3498 if (get_str == NULL) {
3499 get_str = PyString_InternFromString("__get__");
3500 if (get_str == NULL)
3501 return NULL;
3502 }
3503 get = _PyType_Lookup(tp, get_str);
3504 if (get == NULL) {
3505 /* Avoid further slowdowns */
3506 if (tp->tp_descr_get == slot_tp_descr_get)
3507 tp->tp_descr_get = NULL;
3508 Py_INCREF(self);
3509 return self;
3510 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003511 if (obj == NULL)
3512 obj = Py_None;
3513 if (type == NULL)
3514 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003515 return PyObject_CallFunction(get, "OOO", self, obj, type);
3516}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517
3518static int
3519slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3520{
Guido van Rossum2c252392001-08-24 10:13:31 +00003521 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003522 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003523
3524 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003525 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003526 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003527 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003528 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003529 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003530 if (res == NULL)
3531 return -1;
3532 Py_DECREF(res);
3533 return 0;
3534}
3535
3536static int
3537slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3538{
Guido van Rossum60718732001-08-28 17:47:51 +00003539 static PyObject *init_str;
3540 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003541 PyObject *res;
3542
3543 if (meth == NULL)
3544 return -1;
3545 res = PyObject_Call(meth, args, kwds);
3546 Py_DECREF(meth);
3547 if (res == NULL)
3548 return -1;
3549 Py_DECREF(res);
3550 return 0;
3551}
3552
3553static PyObject *
3554slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3555{
3556 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3557 PyObject *newargs, *x;
3558 int i, n;
3559
3560 if (func == NULL)
3561 return NULL;
3562 assert(PyTuple_Check(args));
3563 n = PyTuple_GET_SIZE(args);
3564 newargs = PyTuple_New(n+1);
3565 if (newargs == NULL)
3566 return NULL;
3567 Py_INCREF(type);
3568 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3569 for (i = 0; i < n; i++) {
3570 x = PyTuple_GET_ITEM(args, i);
3571 Py_INCREF(x);
3572 PyTuple_SET_ITEM(newargs, i+1, x);
3573 }
3574 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003575 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576 Py_DECREF(func);
3577 return x;
3578}
3579
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003580
3581/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3582 functions. The offsets here are relative to the 'etype' structure, which
3583 incorporates the additional structures used for numbers, sequences and
3584 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3585 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3586 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3587
3588typedef struct {
3589 char *name;
3590 int offset;
3591 void *function;
3592 wrapperfunc wrapper;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003593 PyObject *name_strobj;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003594} slotdef;
3595
3596#undef TPSLOT
3597#undef ETSLOT
3598#undef SQSLOT
3599#undef MPSLOT
3600#undef NBSLOT
3601#undef BINSLOT
3602#undef RBINSLOT
3603
3604#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
Guido van Rossum825d8752001-10-15 19:44:24 +00003605 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003606#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
Guido van Rossum825d8752001-10-15 19:44:24 +00003607 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003608#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3609 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER)
3610#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3611 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER)
3612#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3613 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER)
3614#define BINSLOT(NAME, SLOT, FUNCTION) \
3615 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l)
3616#define RBINSLOT(NAME, SLOT, FUNCTION) \
3617 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r)
3618
3619static slotdef slotdefs[] = {
3620 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry),
3621 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc),
3622 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3623 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3624 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item),
3625 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc),
3626 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem),
3627 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem),
3628 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3629 wrap_intintobjargproc),
3630 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice),
3631 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc),
3632 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3633 wrap_binaryfunc),
3634 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3635 wrap_intargfunc),
3636
3637 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003638 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3639 wrap_binaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003640 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3641 wrap_objobjargproc),
3642 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3643 wrap_delitem),
3644
3645 BINSLOT("__add__", nb_add, slot_nb_add),
3646 RBINSLOT("__radd__", nb_add, slot_nb_add),
3647 BINSLOT("__sub__", nb_subtract, slot_nb_subtract),
3648 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract),
3649 BINSLOT("__mul__", nb_multiply, slot_nb_multiply),
3650 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply),
3651 BINSLOT("__div__", nb_divide, slot_nb_divide),
3652 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide),
3653 BINSLOT("__mod__", nb_remainder, slot_nb_remainder),
3654 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder),
3655 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod),
3656 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod),
3657 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc),
3658 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r),
3659 NBSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc),
3660 NBSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc),
3661 NBSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc),
3662 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc),
3663 NBSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc),
3664 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift),
3665 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift),
3666 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift),
3667 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift),
3668 BINSLOT("__and__", nb_and, slot_nb_and),
3669 RBINSLOT("__rand__", nb_and, slot_nb_and),
3670 BINSLOT("__xor__", nb_xor, slot_nb_xor),
3671 RBINSLOT("__rxor__", nb_xor, slot_nb_xor),
3672 BINSLOT("__or__", nb_or, slot_nb_or),
3673 RBINSLOT("__ror__", nb_or, slot_nb_or),
3674 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc),
3675 NBSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc),
3676 NBSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc),
3677 NBSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc),
3678 NBSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc),
3679 NBSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc),
3680 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3681 wrap_binaryfunc),
3682 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3683 wrap_binaryfunc),
3684 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3685 wrap_binaryfunc),
3686 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3687 wrap_binaryfunc),
3688 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3689 wrap_binaryfunc),
3690 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3691 wrap_ternaryfunc),
3692 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3693 wrap_binaryfunc),
3694 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3695 wrap_binaryfunc),
3696 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3697 wrap_binaryfunc),
3698 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3699 wrap_binaryfunc),
3700 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3701 wrap_binaryfunc),
3702 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide),
3703 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide),
3704 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide),
3705 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide),
3706 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3707 slot_nb_inplace_floor_divide, wrap_binaryfunc),
3708 NBSLOT("__itruediv__", nb_inplace_true_divide,
3709 slot_nb_inplace_true_divide, wrap_binaryfunc),
3710
3711 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003712 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003713 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc),
3714 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc),
3715 TPSLOT("__call__", tp_call, slot_tp_call, wrap_call),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003716 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003717 wrap_binaryfunc),
3718 TPSLOT("__getattribute__", tp_getattr, NULL, NULL),
3719 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL),
3720 TPSLOT("__getattr__", tp_getattr, NULL, NULL),
3721 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr),
3722 TPSLOT("__setattr__", tp_setattr, NULL, NULL),
3723 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr),
3724 TPSLOT("__delattr__", tp_setattr, NULL, NULL),
3725 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt),
3726 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le),
3727 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq),
3728 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne),
3729 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt),
3730 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge),
3731 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc),
3732 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next),
3733 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get),
3734 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set),
3735 TPSLOT("__init__", tp_init, slot_tp_init, wrap_init),
3736 TPSLOT("__new__", tp_new, slot_tp_new, NULL),
3737 {NULL}
3738};
3739
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003740static void **
3741slotptr(PyTypeObject *type, int offset)
3742{
3743 char *ptr;
3744
3745 assert(offset >= 0);
3746 assert(offset < offsetof(etype, as_buffer));
3747 if (offset >= offsetof(etype, as_mapping)) {
3748 ptr = (void *)type->tp_as_mapping;
3749 offset -= offsetof(etype, as_mapping);
3750 }
3751 else if (offset >= offsetof(etype, as_sequence)) {
3752 ptr = (void *)type->tp_as_sequence;
3753 offset -= offsetof(etype, as_sequence);
3754 }
3755 else if (offset >= offsetof(etype, as_number)) {
3756 ptr = (void *)type->tp_as_number;
3757 offset -= offsetof(etype, as_number);
3758 }
3759 else {
3760 ptr = (void *)type;
3761 }
3762 if (ptr != NULL)
3763 ptr += offset;
3764 return (void **)ptr;
3765}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003766
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003767staticforward int recurse_down_subclasses(PyTypeObject *type, slotdef *p);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003768
3769static int
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003770update_one_slot(PyTypeObject *type, slotdef *p0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003771{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003772 slotdef *p = p0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003773 PyObject *descr;
3774 PyWrapperDescrObject *d;
3775 void *generic = NULL, *specific = NULL;
3776 int use_generic = 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003777 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003778 void **ptr;
3779
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003780 offset = p->offset;
3781 ptr = slotptr(type, offset);
3782 if (ptr == NULL)
3783 return recurse_down_subclasses(type, p);
3784 do {
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003785 descr = _PyType_Lookup(type, p->name_strobj);
3786 if (descr == NULL)
3787 continue;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003788 generic = p->function;
3789 if (descr->ob_type == &PyWrapperDescr_Type) {
3790 d = (PyWrapperDescrObject *)descr;
3791 if (d->d_base->wrapper == p->wrapper &&
3792 PyType_IsSubtype(type, d->d_type)) {
3793 if (specific == NULL ||
3794 specific == d->d_wrapped)
3795 specific = d->d_wrapped;
3796 else
3797 use_generic = 1;
3798 }
3799 }
3800 else
3801 use_generic = 1;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003802 } while ((++p)->offset == offset);
3803 if (specific && !use_generic)
3804 *ptr = specific;
3805 else
3806 *ptr = generic;
3807 return recurse_down_subclasses(type, p0);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003808}
3809
3810static int
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003811recurse_down_subclasses(PyTypeObject *type, slotdef *p)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003812{
3813 PyTypeObject *subclass;
3814 PyObject *ref, *subclasses;
3815 int i, n;
3816
3817 subclasses = type->tp_subclasses;
3818 if (subclasses == NULL)
3819 return 0;
3820 assert(PyList_Check(subclasses));
3821 n = PyList_GET_SIZE(subclasses);
3822 for (i = 0; i < n; i++) {
3823 ref = PyList_GET_ITEM(subclasses, i);
3824 assert(PyWeakref_CheckRef(ref));
3825 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3826 if (subclass == NULL)
3827 continue;
3828 assert(PyType_Check(subclass));
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003829 if (update_one_slot(subclass, p) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003830 return -1;
3831 }
3832 return 0;
3833}
3834
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003835static int
3836slotdef_cmp(const void *aa, const void *bb)
3837{
3838 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3839 int c = a->offset - b->offset;
3840 if (c != 0)
3841 return c;
3842 else
3843 return a - b;
3844}
3845
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003846static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003847init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003848{
3849 slotdef *p;
3850 static int initialized = 0;
3851
3852 if (initialized)
3853 return;
3854 for (p = slotdefs; p->name; p++) {
3855 p->name_strobj = PyString_InternFromString(p->name);
3856 if (!p->name_strobj)
3857 Py_FatalError("XXX ouch");
3858 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003859 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003860 initialized = 1;
3861}
3862
3863static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003864collect_ptrs(PyObject *name, slotdef *ptrs[])
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003865{
3866 slotdef *p;
3867
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003868 init_slotdefs();
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003869 for (p = slotdefs; p->name; p++) {
3870 if (name == p->name_strobj)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003871 *ptrs++ = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003872 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003873 *ptrs = NULL;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003874}
3875
3876static int
3877update_slot(PyTypeObject *type, PyObject *name)
3878{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003879 slotdef *ptrs[10];
3880 slotdef *p;
3881 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003882
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003883 collect_ptrs(name, ptrs);
3884 for (pp = ptrs; *pp; pp++) {
3885 p = *pp;
3886 while (p > slotdefs && p->offset == (p-1)->offset)
3887 --p;
3888 if (update_one_slot(type, p) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003889 return -1;
3890 }
3891 return 0;
3892}
3893
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003895fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003896{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003897 slotdef *p;
3898 PyObject *mro, *descr;
3899 PyTypeObject *base;
3900 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003901 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003902 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003903 void *generic, *specific;
3904 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003906 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003907 mro = type->tp_mro;
3908 assert(PyTuple_Check(mro));
3909 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003910 for (p = slotdefs; p->name; ) {
3911 offset = p->offset;
3912 ptr = slotptr(type, offset);
3913 if (!ptr) {
3914 do {
3915 ++p;
3916 } while (p->offset == offset);
3917 continue;
3918 }
3919 generic = specific = NULL;
3920 use_generic = 0;
3921 do {
3922 descr = NULL;
3923 for (i = 0; i < n; i++) {
3924 base = (PyTypeObject *)PyTuple_GET_ITEM(mro, i);
3925 assert(PyType_Check(base));
3926 descr = PyDict_GetItem(
Guido van Rossum687ae002001-10-15 22:03:32 +00003927 base->tp_dict, p->name_strobj);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003928 if (descr != NULL)
3929 break;
3930 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003931 if (descr == NULL)
3932 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003933 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003934 if (descr->ob_type == &PyWrapperDescr_Type) {
3935 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003936 if (d->d_base->wrapper == p->wrapper &&
3937 PyType_IsSubtype(type, d->d_type)) {
3938 if (specific == NULL ||
3939 specific == d->d_wrapped)
3940 specific = d->d_wrapped;
3941 else
3942 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003943 }
3944 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003945 else
3946 use_generic = 1;
3947 } while ((++p)->offset == offset);
3948 if (specific && !use_generic)
3949 *ptr = specific;
3950 else
3951 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003952 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003953}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003954
3955
3956/* Cooperative 'super' */
3957
3958typedef struct {
3959 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003960 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003961 PyObject *obj;
3962} superobject;
3963
Guido van Rossum6f799372001-09-20 20:46:19 +00003964static PyMemberDef super_members[] = {
3965 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3966 "the class invoking super()"},
3967 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3968 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003969 {0}
3970};
3971
Guido van Rossum705f0f52001-08-24 16:47:00 +00003972static void
3973super_dealloc(PyObject *self)
3974{
3975 superobject *su = (superobject *)self;
3976
Guido van Rossum048eb752001-10-02 21:24:57 +00003977 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003978 Py_XDECREF(su->obj);
3979 Py_XDECREF(su->type);
3980 self->ob_type->tp_free(self);
3981}
3982
3983static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003984super_repr(PyObject *self)
3985{
3986 superobject *su = (superobject *)self;
3987
3988 if (su->obj)
3989 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003990 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003991 su->type ? su->type->tp_name : "NULL",
3992 su->obj->ob_type->tp_name);
3993 else
3994 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003995 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003996 su->type ? su->type->tp_name : "NULL");
3997}
3998
3999static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004000super_getattro(PyObject *self, PyObject *name)
4001{
4002 superobject *su = (superobject *)self;
4003
4004 if (su->obj != NULL) {
4005 PyObject *mro, *res, *tmp;
4006 descrgetfunc f;
4007 int i, n;
4008
Guido van Rossume705ef12001-08-29 15:47:06 +00004009 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004010 if (mro == NULL)
4011 n = 0;
4012 else {
4013 assert(PyTuple_Check(mro));
4014 n = PyTuple_GET_SIZE(mro);
4015 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004016 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004017 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004018 break;
4019 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004020 if (i >= n && PyType_Check(su->obj)) {
4021 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004022 if (mro == NULL)
4023 n = 0;
4024 else {
4025 assert(PyTuple_Check(mro));
4026 n = PyTuple_GET_SIZE(mro);
4027 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004028 for (i = 0; i < n; i++) {
4029 if ((PyObject *)(su->type) ==
4030 PyTuple_GET_ITEM(mro, i))
4031 break;
4032 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004033 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004034 i++;
4035 res = NULL;
4036 for (; i < n; i++) {
4037 tmp = PyTuple_GET_ITEM(mro, i);
4038 assert(PyType_Check(tmp));
4039 res = PyDict_GetItem(
Guido van Rossum687ae002001-10-15 22:03:32 +00004040 ((PyTypeObject *)tmp)->tp_dict, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004041 if (res != NULL) {
4042 Py_INCREF(res);
4043 f = res->ob_type->tp_descr_get;
4044 if (f != NULL) {
4045 tmp = f(res, su->obj, res);
4046 Py_DECREF(res);
4047 res = tmp;
4048 }
4049 return res;
4050 }
4051 }
4052 }
4053 return PyObject_GenericGetAttr(self, name);
4054}
4055
4056static PyObject *
4057super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4058{
4059 superobject *su = (superobject *)self;
4060 superobject *new;
4061
4062 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4063 /* Not binding to an object, or already bound */
4064 Py_INCREF(self);
4065 return self;
4066 }
4067 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
4068 if (new == NULL)
4069 return NULL;
4070 Py_INCREF(su->type);
4071 Py_INCREF(obj);
4072 new->type = su->type;
4073 new->obj = obj;
4074 return (PyObject *)new;
4075}
4076
4077static int
4078super_init(PyObject *self, PyObject *args, PyObject *kwds)
4079{
4080 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004081 PyTypeObject *type;
4082 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004083
4084 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4085 return -1;
4086 if (obj == Py_None)
4087 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00004088 if (obj != NULL &&
4089 !PyType_IsSubtype(obj->ob_type, type) &&
4090 !(PyType_Check(obj) &&
4091 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004092 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00004093 "super(type, obj): "
4094 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004095 return -1;
4096 }
4097 Py_INCREF(type);
4098 Py_XINCREF(obj);
4099 su->type = type;
4100 su->obj = obj;
4101 return 0;
4102}
4103
4104static char super_doc[] =
4105"super(type) -> unbound super object\n"
4106"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004107"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004108"Typical use to call a cooperative superclass method:\n"
4109"class C(B):\n"
4110" def meth(self, arg):\n"
4111" super(C, self).meth(arg)";
4112
Guido van Rossum048eb752001-10-02 21:24:57 +00004113static int
4114super_traverse(PyObject *self, visitproc visit, void *arg)
4115{
4116 superobject *su = (superobject *)self;
4117 int err;
4118
4119#define VISIT(SLOT) \
4120 if (SLOT) { \
4121 err = visit((PyObject *)(SLOT), arg); \
4122 if (err) \
4123 return err; \
4124 }
4125
4126 VISIT(su->obj);
4127 VISIT(su->type);
4128
4129#undef VISIT
4130
4131 return 0;
4132}
4133
Guido van Rossum705f0f52001-08-24 16:47:00 +00004134PyTypeObject PySuper_Type = {
4135 PyObject_HEAD_INIT(&PyType_Type)
4136 0, /* ob_size */
4137 "super", /* tp_name */
4138 sizeof(superobject), /* tp_basicsize */
4139 0, /* tp_itemsize */
4140 /* methods */
4141 super_dealloc, /* tp_dealloc */
4142 0, /* tp_print */
4143 0, /* tp_getattr */
4144 0, /* tp_setattr */
4145 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004146 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004147 0, /* tp_as_number */
4148 0, /* tp_as_sequence */
4149 0, /* tp_as_mapping */
4150 0, /* tp_hash */
4151 0, /* tp_call */
4152 0, /* tp_str */
4153 super_getattro, /* tp_getattro */
4154 0, /* tp_setattro */
4155 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004156 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4157 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004158 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004159 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004160 0, /* tp_clear */
4161 0, /* tp_richcompare */
4162 0, /* tp_weaklistoffset */
4163 0, /* tp_iter */
4164 0, /* tp_iternext */
4165 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004166 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004167 0, /* tp_getset */
4168 0, /* tp_base */
4169 0, /* tp_dict */
4170 super_descr_get, /* tp_descr_get */
4171 0, /* tp_descr_set */
4172 0, /* tp_dictoffset */
4173 super_init, /* tp_init */
4174 PyType_GenericAlloc, /* tp_alloc */
4175 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004176 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004177};