blob: 8a78e69ebb8a0c0fdb8860d5d9aef63d57732999 [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__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 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
Tim Peters6d6c1a32001-08-02 04:15:00 +000083static PyObject *
84type_defined(PyTypeObject *type, void *context)
85{
86 if (type->tp_defined == NULL) {
87 Py_INCREF(Py_None);
88 return Py_None;
89 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000090 return PyDictProxy_New(type->tp_defined);
91}
92
Guido van Rossum32d34c82001-09-20 21:45:26 +000093PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000094 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +000095 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000096 {"__dict__", (getter)type_dict, NULL, NULL},
97 {"__defined__", (getter)type_defined, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000098 {0}
99};
100
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000101static int
102type_compare(PyObject *v, PyObject *w)
103{
104 /* This is called with type objects only. So we
105 can just compare the addresses. */
106 Py_uintptr_t vv = (Py_uintptr_t)v;
107 Py_uintptr_t ww = (Py_uintptr_t)w;
108 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
109}
110
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000112type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000113{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000114 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000115 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000116
117 mod = type_module(type, NULL);
118 if (mod == NULL)
119 PyErr_Clear();
120 else if (!PyString_Check(mod)) {
121 Py_DECREF(mod);
122 mod = NULL;
123 }
124 name = type_name(type, NULL);
125 if (name == NULL)
126 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000127
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000128 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
129 kind = "class";
130 else
131 kind = "type";
132
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000134 rtn = PyString_FromFormat("<%s '%s.%s'>",
135 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000136 PyString_AS_STRING(mod),
137 PyString_AS_STRING(name));
138 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000139 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000140 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000141
Guido van Rossumc3542212001-08-16 09:18:56 +0000142 Py_XDECREF(mod);
143 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000144 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145}
146
Tim Peters6d6c1a32001-08-02 04:15:00 +0000147static PyObject *
148type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
149{
150 PyObject *obj;
151
152 if (type->tp_new == NULL) {
153 PyErr_Format(PyExc_TypeError,
154 "cannot create '%.100s' instances",
155 type->tp_name);
156 return NULL;
157 }
158
Tim Peters3f996e72001-09-13 19:18:27 +0000159 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000160 if (obj != NULL) {
161 type = obj->ob_type;
162 if (type->tp_init != NULL &&
163 type->tp_init(obj, args, kwds) < 0) {
164 Py_DECREF(obj);
165 obj = NULL;
166 }
167 }
168 return obj;
169}
170
171PyObject *
172PyType_GenericAlloc(PyTypeObject *type, int nitems)
173{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000174 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000175 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000176
177 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000178 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000179 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000180 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000181
Neil Schemenauerc806c882001-08-29 23:54:54 +0000182 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000183 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000184
Neil Schemenauerc806c882001-08-29 23:54:54 +0000185 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000186
Tim Peters6d6c1a32001-08-02 04:15:00 +0000187 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
188 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000189
Tim Peters6d6c1a32001-08-02 04:15:00 +0000190 if (type->tp_itemsize == 0)
191 PyObject_INIT(obj, type);
192 else
193 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000194
Tim Peters6d6c1a32001-08-02 04:15:00 +0000195 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000196 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000197 return obj;
198}
199
200PyObject *
201PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
202{
203 return type->tp_alloc(type, 0);
204}
205
Guido van Rossum9475a232001-10-05 20:51:39 +0000206/* Helpers for subtyping */
207
208static int
209subtype_traverse(PyObject *self, visitproc visit, void *arg)
210{
211 PyTypeObject *type, *base;
212 traverseproc f;
213 int err;
214
215 /* Find the nearest base with a different tp_traverse */
216 type = self->ob_type;
217 base = type->tp_base;
218 while ((f = base->tp_traverse) == subtype_traverse) {
219 base = base->tp_base;
220 assert(base);
221 }
222
223 if (type->tp_dictoffset != base->tp_dictoffset) {
224 PyObject **dictptr = _PyObject_GetDictPtr(self);
225 if (dictptr && *dictptr) {
226 err = visit(*dictptr, arg);
227 if (err)
228 return err;
229 }
230 }
231
232 if (f)
233 return f(self, visit, arg);
234 return 0;
235}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000236
237static void
238subtype_dealloc(PyObject *self)
239{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000240 PyTypeObject *type, *base;
241 destructor f;
242
243 /* This exists so we can DECREF self->ob_type */
244
245 /* Find the nearest base with a different tp_dealloc */
246 type = self->ob_type;
247 base = type->tp_base;
248 while ((f = base->tp_dealloc) == subtype_dealloc) {
249 base = base->tp_base;
250 assert(base);
251 }
252
253 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000254 if (type->tp_dictoffset && !base->tp_dictoffset) {
255 PyObject **dictptr = _PyObject_GetDictPtr(self);
256 if (dictptr != NULL) {
257 PyObject *dict = *dictptr;
258 if (dict != NULL) {
259 Py_DECREF(dict);
260 *dictptr = NULL;
261 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000262 }
263 }
264
Guido van Rossum9676b222001-08-17 20:32:36 +0000265 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000266 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000267 PyObject_ClearWeakRefs(self);
268
Tim Peters6d6c1a32001-08-02 04:15:00 +0000269 /* Finalize GC if the base doesn't do GC and we do */
270 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000271 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000272
273 /* Call the base tp_dealloc() */
274 assert(f);
275 f(self);
276
277 /* Can't reference self beyond this point */
278 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
279 Py_DECREF(type);
280 }
281}
282
Tim Peters6d6c1a32001-08-02 04:15:00 +0000283staticforward PyTypeObject *solid_base(PyTypeObject *type);
284
285typedef struct {
286 PyTypeObject type;
287 PyNumberMethods as_number;
288 PySequenceMethods as_sequence;
289 PyMappingMethods as_mapping;
290 PyBufferProcs as_buffer;
291 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000292 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000293} etype;
294
295/* type test with subclassing support */
296
297int
298PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
299{
300 PyObject *mro;
301
Guido van Rossum9478d072001-09-07 18:52:13 +0000302 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
303 return b == a || b == &PyBaseObject_Type;
304
Tim Peters6d6c1a32001-08-02 04:15:00 +0000305 mro = a->tp_mro;
306 if (mro != NULL) {
307 /* Deal with multiple inheritance without recursion
308 by walking the MRO tuple */
309 int i, n;
310 assert(PyTuple_Check(mro));
311 n = PyTuple_GET_SIZE(mro);
312 for (i = 0; i < n; i++) {
313 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
314 return 1;
315 }
316 return 0;
317 }
318 else {
319 /* a is not completely initilized yet; follow tp_base */
320 do {
321 if (a == b)
322 return 1;
323 a = a->tp_base;
324 } while (a != NULL);
325 return b == &PyBaseObject_Type;
326 }
327}
328
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000329/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000330 without looking in the instance dictionary
331 (so we can't use PyObject_GetAttr) but still binding
332 it to the instance. The arguments are the object,
333 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000334 static variable used to cache the interned Python string.
335
336 Two variants:
337
338 - lookup_maybe() returns NULL without raising an exception
339 when the _PyType_Lookup() call fails;
340
341 - lookup_method() always raises an exception upon errors.
342*/
Guido van Rossum60718732001-08-28 17:47:51 +0000343
344static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000345lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000346{
347 PyObject *res;
348
349 if (*attrobj == NULL) {
350 *attrobj = PyString_InternFromString(attrstr);
351 if (*attrobj == NULL)
352 return NULL;
353 }
354 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000355 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000356 descrgetfunc f;
357 if ((f = res->ob_type->tp_descr_get) == NULL)
358 Py_INCREF(res);
359 else
360 res = f(res, self, (PyObject *)(self->ob_type));
361 }
362 return res;
363}
364
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000365static PyObject *
366lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
367{
368 PyObject *res = lookup_maybe(self, attrstr, attrobj);
369 if (res == NULL && !PyErr_Occurred())
370 PyErr_SetObject(PyExc_AttributeError, *attrobj);
371 return res;
372}
373
Guido van Rossum2730b132001-08-28 18:22:14 +0000374/* A variation of PyObject_CallMethod that uses lookup_method()
375 instead of PyObject_GetAttrString(). This uses the same convention
376 as lookup_method to cache the interned name string object. */
377
378PyObject *
379call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
380{
381 va_list va;
382 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000383 va_start(va, format);
384
Guido van Rossumda21c012001-10-03 00:50:18 +0000385 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000386 if (func == NULL) {
387 va_end(va);
388 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000389 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000390 return NULL;
391 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000392
393 if (format && *format)
394 args = Py_VaBuildValue(format, va);
395 else
396 args = PyTuple_New(0);
397
398 va_end(va);
399
400 if (args == NULL)
401 return NULL;
402
403 assert(PyTuple_Check(args));
404 retval = PyObject_Call(func, args, NULL);
405
406 Py_DECREF(args);
407 Py_DECREF(func);
408
409 return retval;
410}
411
412/* Clone of call_method() that returns NotImplemented when the lookup fails. */
413
414PyObject *
415call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
416{
417 va_list va;
418 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000419 va_start(va, format);
420
Guido van Rossumda21c012001-10-03 00:50:18 +0000421 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000422 if (func == NULL) {
423 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000424 if (!PyErr_Occurred()) {
425 Py_INCREF(Py_NotImplemented);
426 return Py_NotImplemented;
427 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000428 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000429 }
430
431 if (format && *format)
432 args = Py_VaBuildValue(format, va);
433 else
434 args = PyTuple_New(0);
435
436 va_end(va);
437
Guido van Rossum717ce002001-09-14 16:58:08 +0000438 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000439 return NULL;
440
Guido van Rossum717ce002001-09-14 16:58:08 +0000441 assert(PyTuple_Check(args));
442 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000443
444 Py_DECREF(args);
445 Py_DECREF(func);
446
447 return retval;
448}
449
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450/* Method resolution order algorithm from "Putting Metaclasses to Work"
451 by Forman and Danforth (Addison-Wesley 1999). */
452
453static int
454conservative_merge(PyObject *left, PyObject *right)
455{
456 int left_size;
457 int right_size;
458 int i, j, r, ok;
459 PyObject *temp, *rr;
460
461 assert(PyList_Check(left));
462 assert(PyList_Check(right));
463
464 again:
465 left_size = PyList_GET_SIZE(left);
466 right_size = PyList_GET_SIZE(right);
467 for (i = 0; i < left_size; i++) {
468 for (j = 0; j < right_size; j++) {
469 if (PyList_GET_ITEM(left, i) ==
470 PyList_GET_ITEM(right, j)) {
471 /* found a merge point */
472 temp = PyList_New(0);
473 if (temp == NULL)
474 return -1;
475 for (r = 0; r < j; r++) {
476 rr = PyList_GET_ITEM(right, r);
477 ok = PySequence_Contains(left, rr);
478 if (ok < 0) {
479 Py_DECREF(temp);
480 return -1;
481 }
482 if (!ok) {
483 ok = PyList_Append(temp, rr);
484 if (ok < 0) {
485 Py_DECREF(temp);
486 return -1;
487 }
488 }
489 }
490 ok = PyList_SetSlice(left, i, i, temp);
491 Py_DECREF(temp);
492 if (ok < 0)
493 return -1;
494 ok = PyList_SetSlice(right, 0, j+1, NULL);
495 if (ok < 0)
496 return -1;
497 goto again;
498 }
499 }
500 }
501 return PyList_SetSlice(left, left_size, left_size, right);
502}
503
504static int
505serious_order_disagreements(PyObject *left, PyObject *right)
506{
507 return 0; /* XXX later -- for now, we cheat: "don't do that" */
508}
509
510static PyObject *
511mro_implementation(PyTypeObject *type)
512{
513 int i, n, ok;
514 PyObject *bases, *result;
515
516 bases = type->tp_bases;
517 n = PyTuple_GET_SIZE(bases);
518 result = Py_BuildValue("[O]", (PyObject *)type);
519 if (result == NULL)
520 return NULL;
521 for (i = 0; i < n; i++) {
522 PyTypeObject *base =
523 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
524 PyObject *parentMRO = PySequence_List(base->tp_mro);
525 if (parentMRO == NULL) {
526 Py_DECREF(result);
527 return NULL;
528 }
529 if (serious_order_disagreements(result, parentMRO)) {
530 Py_DECREF(result);
531 return NULL;
532 }
533 ok = conservative_merge(result, parentMRO);
534 Py_DECREF(parentMRO);
535 if (ok < 0) {
536 Py_DECREF(result);
537 return NULL;
538 }
539 }
540 return result;
541}
542
543static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000544mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545{
546 PyTypeObject *type = (PyTypeObject *)self;
547
Tim Peters6d6c1a32001-08-02 04:15:00 +0000548 return mro_implementation(type);
549}
550
551static int
552mro_internal(PyTypeObject *type)
553{
554 PyObject *mro, *result, *tuple;
555
556 if (type->ob_type == &PyType_Type) {
557 result = mro_implementation(type);
558 }
559 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000560 static PyObject *mro_str;
561 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000562 if (mro == NULL)
563 return -1;
564 result = PyObject_CallObject(mro, NULL);
565 Py_DECREF(mro);
566 }
567 if (result == NULL)
568 return -1;
569 tuple = PySequence_Tuple(result);
570 Py_DECREF(result);
571 type->tp_mro = tuple;
572 return 0;
573}
574
575
576/* Calculate the best base amongst multiple base classes.
577 This is the first one that's on the path to the "solid base". */
578
579static PyTypeObject *
580best_base(PyObject *bases)
581{
582 int i, n;
583 PyTypeObject *base, *winner, *candidate, *base_i;
584
585 assert(PyTuple_Check(bases));
586 n = PyTuple_GET_SIZE(bases);
587 assert(n > 0);
588 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
589 winner = &PyBaseObject_Type;
590 for (i = 0; i < n; i++) {
591 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
592 if (!PyType_Check((PyObject *)base_i)) {
593 PyErr_SetString(
594 PyExc_TypeError,
595 "bases must be types");
596 return NULL;
597 }
598 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000599 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000600 return NULL;
601 }
602 candidate = solid_base(base_i);
603 if (PyType_IsSubtype(winner, candidate))
604 ;
605 else if (PyType_IsSubtype(candidate, winner)) {
606 winner = candidate;
607 base = base_i;
608 }
609 else {
610 PyErr_SetString(
611 PyExc_TypeError,
612 "multiple bases have "
613 "instance lay-out conflict");
614 return NULL;
615 }
616 }
617 assert(base != NULL);
618 return base;
619}
620
621static int
622extra_ivars(PyTypeObject *type, PyTypeObject *base)
623{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000624 size_t t_size = type->tp_basicsize;
625 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000626
Guido van Rossum9676b222001-08-17 20:32:36 +0000627 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000628 if (type->tp_itemsize || base->tp_itemsize) {
629 /* If itemsize is involved, stricter rules */
630 return t_size != b_size ||
631 type->tp_itemsize != base->tp_itemsize;
632 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000633 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
634 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
635 t_size -= sizeof(PyObject *);
636 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
637 type->tp_dictoffset + sizeof(PyObject *) == t_size)
638 t_size -= sizeof(PyObject *);
639
640 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000641}
642
643static PyTypeObject *
644solid_base(PyTypeObject *type)
645{
646 PyTypeObject *base;
647
648 if (type->tp_base)
649 base = solid_base(type->tp_base);
650 else
651 base = &PyBaseObject_Type;
652 if (extra_ivars(type, base))
653 return type;
654 else
655 return base;
656}
657
658staticforward void object_dealloc(PyObject *);
659staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000660staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000661staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000662
663static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000664subtype_dict(PyObject *obj, void *context)
665{
666 PyObject **dictptr = _PyObject_GetDictPtr(obj);
667 PyObject *dict;
668
669 if (dictptr == NULL) {
670 PyErr_SetString(PyExc_AttributeError,
671 "This object has no __dict__");
672 return NULL;
673 }
674 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000675 if (dict == NULL)
676 *dictptr = dict = PyDict_New();
677 Py_XINCREF(dict);
678 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000679}
680
Guido van Rossum32d34c82001-09-20 21:45:26 +0000681PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000682 {"__dict__", subtype_dict, NULL, NULL},
683 {0},
684};
685
686static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
688{
689 PyObject *name, *bases, *dict;
690 static char *kwlist[] = {"name", "bases", "dict", 0};
691 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000692 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000693 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000694 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000695 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000697 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000698 if (metatype == &PyType_Type &&
699 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
700 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000701 PyObject *x = PyTuple_GET_ITEM(args, 0);
702 Py_INCREF(x->ob_type);
703 return (PyObject *) x->ob_type;
704 }
705
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000706 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
708 &name,
709 &PyTuple_Type, &bases,
710 &PyDict_Type, &dict))
711 return NULL;
712
713 /* Determine the proper metatype to deal with this,
714 and check for metatype conflicts while we're at it.
715 Note that if some other metatype wins to contract,
716 it's possible that its instances are not types. */
717 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000718 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719 for (i = 0; i < nbases; i++) {
720 tmp = PyTuple_GET_ITEM(bases, i);
721 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000722 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000723 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000724 if (PyType_IsSubtype(tmptype, winner)) {
725 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000726 continue;
727 }
728 PyErr_SetString(PyExc_TypeError,
729 "metatype conflict among bases");
730 return NULL;
731 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000732 if (winner != metatype) {
733 if (winner->tp_new != type_new) /* Pass it to the winner */
734 return winner->tp_new(winner, args, kwds);
735 metatype = winner;
736 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000737
738 /* Adjust for empty tuple bases */
739 if (nbases == 0) {
740 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
741 if (bases == NULL)
742 return NULL;
743 nbases = 1;
744 }
745 else
746 Py_INCREF(bases);
747
748 /* XXX From here until type is allocated, "return NULL" leaks bases! */
749
750 /* Calculate best base, and check that all bases are type objects */
751 base = best_base(bases);
752 if (base == NULL)
753 return NULL;
754 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
755 PyErr_Format(PyExc_TypeError,
756 "type '%.100s' is not an acceptable base type",
757 base->tp_name);
758 return NULL;
759 }
760
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761 /* Check for a __slots__ sequence variable in dict, and count it */
762 slots = PyDict_GetItemString(dict, "__slots__");
763 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000764 add_dict = 0;
765 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000766 if (slots != NULL) {
767 /* Make it into a tuple */
768 if (PyString_Check(slots))
769 slots = Py_BuildValue("(O)", slots);
770 else
771 slots = PySequence_Tuple(slots);
772 if (slots == NULL)
773 return NULL;
774 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000775 if (nslots > 0 && base->tp_itemsize != 0) {
776 PyErr_Format(PyExc_TypeError,
777 "nonempty __slots__ "
778 "not supported for subtype of '%s'",
779 base->tp_name);
780 return NULL;
781 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000782 for (i = 0; i < nslots; i++) {
783 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
784 PyErr_SetString(PyExc_TypeError,
785 "__slots__ must be a sequence of strings");
786 Py_DECREF(slots);
787 return NULL;
788 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000789 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790 }
791 }
792 if (slots == NULL && base->tp_dictoffset == 0 &&
793 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000794 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000795 add_dict++;
796 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000797 if (slots == NULL && base->tp_weaklistoffset == 0 &&
798 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000799 nslots++;
800 add_weak++;
801 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000802
803 /* XXX From here until type is safely allocated,
804 "return NULL" may leak slots! */
805
806 /* Allocate the type object */
807 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
808 if (type == NULL)
809 return NULL;
810
811 /* Keep name and slots alive in the extended type object */
812 et = (etype *)type;
813 Py_INCREF(name);
814 et->name = name;
815 et->slots = slots;
816
Guido van Rossumdc91b992001-08-08 22:26:22 +0000817 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
819 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000820 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
821 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000822
823 /* It's a new-style number unless it specifically inherits any
824 old-style numeric behavior */
825 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
826 (base->tp_as_number == NULL))
827 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
828
829 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 type->tp_as_number = &et->as_number;
831 type->tp_as_sequence = &et->as_sequence;
832 type->tp_as_mapping = &et->as_mapping;
833 type->tp_as_buffer = &et->as_buffer;
834 type->tp_name = PyString_AS_STRING(name);
835
836 /* Set tp_base and tp_bases */
837 type->tp_bases = bases;
838 Py_INCREF(base);
839 type->tp_base = base;
840
841 /* Initialize tp_defined from passed-in dict */
842 type->tp_defined = dict = PyDict_Copy(dict);
843 if (dict == NULL) {
844 Py_DECREF(type);
845 return NULL;
846 }
847
Guido van Rossumc3542212001-08-16 09:18:56 +0000848 /* Set __module__ in the dict */
849 if (PyDict_GetItemString(dict, "__module__") == NULL) {
850 tmp = PyEval_GetGlobals();
851 if (tmp != NULL) {
852 tmp = PyDict_GetItemString(tmp, "__name__");
853 if (tmp != NULL) {
854 if (PyDict_SetItemString(dict, "__module__",
855 tmp) < 0)
856 return NULL;
857 }
858 }
859 }
860
Tim Peters2f93e282001-10-04 05:27:00 +0000861 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
862 and is a string (tp_doc is a char* -- can't copy a general object
863 into it).
864 XXX What if it's a Unicode string? Don't know -- this ignores it.
865 */
866 {
867 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
868 if (doc != NULL && PyString_Check(doc)) {
869 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000870 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000871 if (type->tp_doc == NULL) {
872 Py_DECREF(type);
873 return NULL;
874 }
875 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
876 }
877 }
878
Tim Peters6d6c1a32001-08-02 04:15:00 +0000879 /* Special-case __new__: if it's a plain function,
880 make it a static function */
881 tmp = PyDict_GetItemString(dict, "__new__");
882 if (tmp != NULL && PyFunction_Check(tmp)) {
883 tmp = PyStaticMethod_New(tmp);
884 if (tmp == NULL) {
885 Py_DECREF(type);
886 return NULL;
887 }
888 PyDict_SetItemString(dict, "__new__", tmp);
889 Py_DECREF(tmp);
890 }
891
892 /* Add descriptors for custom slots from __slots__, or for __dict__ */
893 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000894 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895 if (slots != NULL) {
896 for (i = 0; i < nslots; i++, mp++) {
897 mp->name = PyString_AS_STRING(
898 PyTuple_GET_ITEM(slots, i));
899 mp->type = T_OBJECT;
900 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000901 if (base->tp_weaklistoffset == 0 &&
902 strcmp(mp->name, "__weakref__") == 0)
903 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000904 slotoffset += sizeof(PyObject *);
905 }
906 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000907 else {
908 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000909 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000910 type->tp_dictoffset =
911 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000912 else
913 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000914 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000915 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000916 }
917 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000918 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000919 type->tp_weaklistoffset = slotoffset;
920 mp->name = "__weakref__";
921 mp->type = T_OBJECT;
922 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000923 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000924 mp++;
925 slotoffset += sizeof(PyObject *);
926 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000927 }
928 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000929 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000930 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000931
932 /* Special case some slots */
933 if (type->tp_dictoffset != 0 || nslots > 0) {
934 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
935 type->tp_getattro = PyObject_GenericGetAttr;
936 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
937 type->tp_setattro = PyObject_GenericSetAttr;
938 }
939 type->tp_dealloc = subtype_dealloc;
940
Guido van Rossum9475a232001-10-05 20:51:39 +0000941 /* Enable GC unless there are really no instance variables possible */
942 if (!(type->tp_basicsize == sizeof(PyObject) &&
943 type->tp_itemsize == 0))
944 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
945
Tim Peters6d6c1a32001-08-02 04:15:00 +0000946 /* Always override allocation strategy to use regular heap */
947 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +0000948 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
949 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +0000950 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +0000951 type->tp_clear = base->tp_clear;
952 }
953 else
954 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000955
956 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000957 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000958 Py_DECREF(type);
959 return NULL;
960 }
961
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000962 /* Put the proper slots in place */
963 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000964
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965 return (PyObject *)type;
966}
967
968/* Internal API to look for a name through the MRO.
969 This returns a borrowed reference, and doesn't set an exception! */
970PyObject *
971_PyType_Lookup(PyTypeObject *type, PyObject *name)
972{
973 int i, n;
974 PyObject *mro, *res, *dict;
975
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000976 /* Look in tp_defined of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977 mro = type->tp_mro;
978 assert(PyTuple_Check(mro));
979 n = PyTuple_GET_SIZE(mro);
980 for (i = 0; i < n; i++) {
981 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
982 assert(PyType_Check(type));
983 dict = type->tp_defined;
984 assert(dict && PyDict_Check(dict));
985 res = PyDict_GetItem(dict, name);
986 if (res != NULL)
987 return res;
988 }
989 return NULL;
990}
991
992/* This is similar to PyObject_GenericGetAttr(),
993 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
994static PyObject *
995type_getattro(PyTypeObject *type, PyObject *name)
996{
997 PyTypeObject *metatype = type->ob_type;
998 PyObject *descr, *res;
999 descrgetfunc f;
1000
1001 /* Initialize this type (we'll assume the metatype is initialized) */
1002 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001003 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001004 return NULL;
1005 }
1006
1007 /* Get a descriptor from the metatype */
1008 descr = _PyType_Lookup(metatype, name);
1009 f = NULL;
1010 if (descr != NULL) {
1011 f = descr->ob_type->tp_descr_get;
1012 if (f != NULL && PyDescr_IsData(descr))
1013 return f(descr,
1014 (PyObject *)type, (PyObject *)metatype);
1015 }
1016
1017 /* Look in tp_defined of this type and its bases */
1018 res = _PyType_Lookup(type, name);
1019 if (res != NULL) {
1020 f = res->ob_type->tp_descr_get;
1021 if (f != NULL)
1022 return f(res, (PyObject *)NULL, (PyObject *)type);
1023 Py_INCREF(res);
1024 return res;
1025 }
1026
1027 /* Use the descriptor from the metatype */
1028 if (f != NULL) {
1029 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1030 return res;
1031 }
1032 if (descr != NULL) {
1033 Py_INCREF(descr);
1034 return descr;
1035 }
1036
1037 /* Give up */
1038 PyErr_Format(PyExc_AttributeError,
1039 "type object '%.50s' has no attribute '%.400s'",
1040 type->tp_name, PyString_AS_STRING(name));
1041 return NULL;
1042}
1043
1044static int
1045type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1046{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001047 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1048 PyErr_Format(
1049 PyExc_TypeError,
1050 "can't set attributes of built-in/extension type '%s'",
1051 type->tp_name);
1052 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001053 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001054 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1055 return -1;
1056 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001057}
1058
1059static void
1060type_dealloc(PyTypeObject *type)
1061{
1062 etype *et;
1063
1064 /* Assert this is a heap-allocated type object */
1065 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001066 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001067 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001068 et = (etype *)type;
1069 Py_XDECREF(type->tp_base);
1070 Py_XDECREF(type->tp_dict);
1071 Py_XDECREF(type->tp_bases);
1072 Py_XDECREF(type->tp_mro);
1073 Py_XDECREF(type->tp_defined);
Guido van Rossum1c450732001-10-08 15:18:27 +00001074 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 Py_XDECREF(et->name);
1076 Py_XDECREF(et->slots);
1077 type->ob_type->tp_free((PyObject *)type);
1078}
1079
Guido van Rossum1c450732001-10-08 15:18:27 +00001080static PyObject *
1081type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1082{
1083 PyObject *list, *raw, *ref;
1084 int i, n;
1085
1086 list = PyList_New(0);
1087 if (list == NULL)
1088 return NULL;
1089 raw = type->tp_subclasses;
1090 if (raw == NULL)
1091 return list;
1092 assert(PyList_Check(raw));
1093 n = PyList_GET_SIZE(raw);
1094 for (i = 0; i < n; i++) {
1095 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001096 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001097 ref = PyWeakref_GET_OBJECT(ref);
1098 if (ref != Py_None) {
1099 if (PyList_Append(list, ref) < 0) {
1100 Py_DECREF(list);
1101 return NULL;
1102 }
1103 }
1104 }
1105 return list;
1106}
1107
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001109 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001110 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001111 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1112 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 {0}
1114};
1115
1116static char type_doc[] =
1117"type(object) -> the object's type\n"
1118"type(name, bases, dict) -> a new type";
1119
Guido van Rossum048eb752001-10-02 21:24:57 +00001120static int
1121type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1122{
1123 etype *et;
1124 int err;
1125
1126 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1127 return 0;
1128
1129 et = (etype *)type;
1130
1131#define VISIT(SLOT) \
1132 if (SLOT) { \
1133 err = visit((PyObject *)(SLOT), arg); \
1134 if (err) \
1135 return err; \
1136 }
1137
1138 VISIT(type->tp_dict);
1139 VISIT(type->tp_defined);
1140 VISIT(type->tp_mro);
1141 VISIT(type->tp_bases);
1142 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001143 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001144 VISIT(et->slots);
1145
1146#undef VISIT
1147
1148 return 0;
1149}
1150
1151static int
1152type_clear(PyTypeObject *type)
1153{
1154 etype *et;
1155 PyObject *tmp;
1156
1157 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1158 return 0;
1159
1160 et = (etype *)type;
1161
1162#define CLEAR(SLOT) \
1163 if (SLOT) { \
1164 tmp = (PyObject *)(SLOT); \
1165 SLOT = NULL; \
1166 Py_DECREF(tmp); \
1167 }
1168
1169 CLEAR(type->tp_dict);
1170 CLEAR(type->tp_defined);
1171 CLEAR(type->tp_mro);
1172 CLEAR(type->tp_bases);
1173 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001174 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001175 CLEAR(et->slots);
1176
Tim Peters2f93e282001-10-04 05:27:00 +00001177 if (type->tp_doc != NULL) {
1178 PyObject_FREE(type->tp_doc);
1179 type->tp_doc = NULL;
1180 }
1181
Guido van Rossum048eb752001-10-02 21:24:57 +00001182#undef CLEAR
1183
1184 return 0;
1185}
1186
1187static int
1188type_is_gc(PyTypeObject *type)
1189{
1190 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1191}
1192
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001193PyTypeObject PyType_Type = {
1194 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 0, /* ob_size */
1196 "type", /* tp_name */
1197 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001198 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 (destructor)type_dealloc, /* tp_dealloc */
1200 0, /* tp_print */
1201 0, /* tp_getattr */
1202 0, /* tp_setattr */
1203 type_compare, /* tp_compare */
1204 (reprfunc)type_repr, /* tp_repr */
1205 0, /* tp_as_number */
1206 0, /* tp_as_sequence */
1207 0, /* tp_as_mapping */
1208 (hashfunc)_Py_HashPointer, /* tp_hash */
1209 (ternaryfunc)type_call, /* tp_call */
1210 0, /* tp_str */
1211 (getattrofunc)type_getattro, /* tp_getattro */
1212 (setattrofunc)type_setattro, /* tp_setattro */
1213 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001214 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1215 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001217 (traverseproc)type_traverse, /* tp_traverse */
1218 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001220 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 0, /* tp_iter */
1222 0, /* tp_iternext */
1223 type_methods, /* tp_methods */
1224 type_members, /* tp_members */
1225 type_getsets, /* tp_getset */
1226 0, /* tp_base */
1227 0, /* tp_dict */
1228 0, /* tp_descr_get */
1229 0, /* tp_descr_set */
1230 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1231 0, /* tp_init */
1232 0, /* tp_alloc */
1233 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001234 _PyObject_GC_Del, /* tp_free */
1235 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001236};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237
1238
1239/* The base type of all types (eventually)... except itself. */
1240
1241static int
1242object_init(PyObject *self, PyObject *args, PyObject *kwds)
1243{
1244 return 0;
1245}
1246
1247static void
1248object_dealloc(PyObject *self)
1249{
1250 self->ob_type->tp_free(self);
1251}
1252
Guido van Rossum8e248182001-08-12 05:17:56 +00001253static PyObject *
1254object_repr(PyObject *self)
1255{
Guido van Rossum76e69632001-08-16 18:52:43 +00001256 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001257 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001258
Guido van Rossum76e69632001-08-16 18:52:43 +00001259 type = self->ob_type;
1260 mod = type_module(type, NULL);
1261 if (mod == NULL)
1262 PyErr_Clear();
1263 else if (!PyString_Check(mod)) {
1264 Py_DECREF(mod);
1265 mod = NULL;
1266 }
1267 name = type_name(type, NULL);
1268 if (name == NULL)
1269 return NULL;
1270 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001271 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001272 PyString_AS_STRING(mod),
1273 PyString_AS_STRING(name),
1274 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001275 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001276 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001277 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001278 Py_XDECREF(mod);
1279 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001280 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001281}
1282
Guido van Rossumb8f63662001-08-15 23:57:02 +00001283static PyObject *
1284object_str(PyObject *self)
1285{
1286 unaryfunc f;
1287
1288 f = self->ob_type->tp_repr;
1289 if (f == NULL)
1290 f = object_repr;
1291 return f(self);
1292}
1293
Guido van Rossum8e248182001-08-12 05:17:56 +00001294static long
1295object_hash(PyObject *self)
1296{
1297 return _Py_HashPointer(self);
1298}
Guido van Rossum8e248182001-08-12 05:17:56 +00001299
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001300static PyObject *
1301object_get_class(PyObject *self, void *closure)
1302{
1303 Py_INCREF(self->ob_type);
1304 return (PyObject *)(self->ob_type);
1305}
1306
1307static int
1308equiv_structs(PyTypeObject *a, PyTypeObject *b)
1309{
1310 return a == b ||
1311 (a != NULL &&
1312 b != NULL &&
1313 a->tp_basicsize == b->tp_basicsize &&
1314 a->tp_itemsize == b->tp_itemsize &&
1315 a->tp_dictoffset == b->tp_dictoffset &&
1316 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1317 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1318 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1319}
1320
1321static int
1322same_slots_added(PyTypeObject *a, PyTypeObject *b)
1323{
1324 PyTypeObject *base = a->tp_base;
1325 int size;
1326
1327 if (base != b->tp_base)
1328 return 0;
1329 if (equiv_structs(a, base) && equiv_structs(b, base))
1330 return 1;
1331 size = base->tp_basicsize;
1332 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1333 size += sizeof(PyObject *);
1334 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1335 size += sizeof(PyObject *);
1336 return size == a->tp_basicsize && size == b->tp_basicsize;
1337}
1338
1339static int
1340object_set_class(PyObject *self, PyObject *value, void *closure)
1341{
1342 PyTypeObject *old = self->ob_type;
1343 PyTypeObject *new, *newbase, *oldbase;
1344
1345 if (!PyType_Check(value)) {
1346 PyErr_Format(PyExc_TypeError,
1347 "__class__ must be set to new-style class, not '%s' object",
1348 value->ob_type->tp_name);
1349 return -1;
1350 }
1351 new = (PyTypeObject *)value;
1352 newbase = new;
1353 oldbase = old;
1354 while (equiv_structs(newbase, newbase->tp_base))
1355 newbase = newbase->tp_base;
1356 while (equiv_structs(oldbase, oldbase->tp_base))
1357 oldbase = oldbase->tp_base;
1358 if (newbase != oldbase &&
1359 (newbase->tp_base != oldbase->tp_base ||
1360 !same_slots_added(newbase, oldbase))) {
1361 PyErr_Format(PyExc_TypeError,
1362 "__class__ assignment: "
1363 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001364 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001365 old->tp_name);
1366 return -1;
1367 }
1368 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1369 Py_INCREF(new);
1370 }
1371 self->ob_type = new;
1372 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1373 Py_DECREF(old);
1374 }
1375 return 0;
1376}
1377
1378static PyGetSetDef object_getsets[] = {
1379 {"__class__", object_get_class, object_set_class,
1380 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 {0}
1382};
1383
Guido van Rossum3926a632001-09-25 16:25:58 +00001384static PyObject *
1385object_reduce(PyObject *self, PyObject *args)
1386{
1387 /* Call copy_reg._reduce(self) */
1388 static PyObject *copy_reg_str;
1389 PyObject *copy_reg, *res;
1390
1391 if (!copy_reg_str) {
1392 copy_reg_str = PyString_InternFromString("copy_reg");
1393 if (copy_reg_str == NULL)
1394 return NULL;
1395 }
1396 copy_reg = PyImport_Import(copy_reg_str);
1397 if (!copy_reg)
1398 return NULL;
1399 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1400 Py_DECREF(copy_reg);
1401 return res;
1402}
1403
1404static PyMethodDef object_methods[] = {
1405 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1406 {0}
1407};
1408
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409PyTypeObject PyBaseObject_Type = {
1410 PyObject_HEAD_INIT(&PyType_Type)
1411 0, /* ob_size */
1412 "object", /* tp_name */
1413 sizeof(PyObject), /* tp_basicsize */
1414 0, /* tp_itemsize */
1415 (destructor)object_dealloc, /* tp_dealloc */
1416 0, /* tp_print */
1417 0, /* tp_getattr */
1418 0, /* tp_setattr */
1419 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001420 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001421 0, /* tp_as_number */
1422 0, /* tp_as_sequence */
1423 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001424 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001426 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001427 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001428 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429 0, /* tp_as_buffer */
1430 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1431 "The most base type", /* tp_doc */
1432 0, /* tp_traverse */
1433 0, /* tp_clear */
1434 0, /* tp_richcompare */
1435 0, /* tp_weaklistoffset */
1436 0, /* tp_iter */
1437 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001438 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001439 0, /* tp_members */
1440 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441 0, /* tp_base */
1442 0, /* tp_dict */
1443 0, /* tp_descr_get */
1444 0, /* tp_descr_set */
1445 0, /* tp_dictoffset */
1446 object_init, /* tp_init */
1447 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001448 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001449 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001450};
1451
1452
1453/* Initialize the __dict__ in a type object */
1454
1455static int
1456add_methods(PyTypeObject *type, PyMethodDef *meth)
1457{
1458 PyObject *dict = type->tp_defined;
1459
1460 for (; meth->ml_name != NULL; meth++) {
1461 PyObject *descr;
1462 if (PyDict_GetItemString(dict, meth->ml_name))
1463 continue;
1464 descr = PyDescr_NewMethod(type, meth);
1465 if (descr == NULL)
1466 return -1;
1467 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1468 return -1;
1469 Py_DECREF(descr);
1470 }
1471 return 0;
1472}
1473
1474static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001475add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476{
1477 PyObject *dict = type->tp_defined;
1478
1479 for (; memb->name != NULL; memb++) {
1480 PyObject *descr;
1481 if (PyDict_GetItemString(dict, memb->name))
1482 continue;
1483 descr = PyDescr_NewMember(type, memb);
1484 if (descr == NULL)
1485 return -1;
1486 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1487 return -1;
1488 Py_DECREF(descr);
1489 }
1490 return 0;
1491}
1492
1493static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001494add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495{
1496 PyObject *dict = type->tp_defined;
1497
1498 for (; gsp->name != NULL; gsp++) {
1499 PyObject *descr;
1500 if (PyDict_GetItemString(dict, gsp->name))
1501 continue;
1502 descr = PyDescr_NewGetSet(type, gsp);
1503
1504 if (descr == NULL)
1505 return -1;
1506 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1507 return -1;
1508 Py_DECREF(descr);
1509 }
1510 return 0;
1511}
1512
Guido van Rossum13d52f02001-08-10 21:24:08 +00001513static void
1514inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515{
1516 int oldsize, newsize;
1517
Guido van Rossum13d52f02001-08-10 21:24:08 +00001518 /* Special flag magic */
1519 if (!type->tp_as_buffer && base->tp_as_buffer) {
1520 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1521 type->tp_flags |=
1522 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1523 }
1524 if (!type->tp_as_sequence && base->tp_as_sequence) {
1525 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1526 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1527 }
1528 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1529 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1530 if ((!type->tp_as_number && base->tp_as_number) ||
1531 (!type->tp_as_sequence && base->tp_as_sequence)) {
1532 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1533 if (!type->tp_as_number && !type->tp_as_sequence) {
1534 type->tp_flags |= base->tp_flags &
1535 Py_TPFLAGS_HAVE_INPLACEOPS;
1536 }
1537 }
1538 /* Wow */
1539 }
1540 if (!type->tp_as_number && base->tp_as_number) {
1541 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1542 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1543 }
1544
1545 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001546 oldsize = base->tp_basicsize;
1547 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1548 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1549 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001550 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1551 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001552 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001553 if (type->tp_traverse == NULL)
1554 type->tp_traverse = base->tp_traverse;
1555 if (type->tp_clear == NULL)
1556 type->tp_clear = base->tp_clear;
1557 }
1558 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1559 if (base != &PyBaseObject_Type ||
1560 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1561 if (type->tp_new == NULL)
1562 type->tp_new = base->tp_new;
1563 }
1564 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001565 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001566
1567 /* Copy other non-function slots */
1568
1569#undef COPYVAL
1570#define COPYVAL(SLOT) \
1571 if (type->SLOT == 0) type->SLOT = base->SLOT
1572
1573 COPYVAL(tp_itemsize);
1574 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1575 COPYVAL(tp_weaklistoffset);
1576 }
1577 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1578 COPYVAL(tp_dictoffset);
1579 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001580}
1581
1582static void
1583inherit_slots(PyTypeObject *type, PyTypeObject *base)
1584{
1585 PyTypeObject *basebase;
1586
1587#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588#undef COPYSLOT
1589#undef COPYNUM
1590#undef COPYSEQ
1591#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001592#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001593
1594#define SLOTDEFINED(SLOT) \
1595 (base->SLOT != 0 && \
1596 (basebase == NULL || base->SLOT != basebase->SLOT))
1597
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001599 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600
1601#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1602#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1603#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001604#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605
Guido van Rossum13d52f02001-08-10 21:24:08 +00001606 /* This won't inherit indirect slots (from tp_as_number etc.)
1607 if type doesn't provide the space. */
1608
1609 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1610 basebase = base->tp_base;
1611 if (basebase->tp_as_number == NULL)
1612 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 COPYNUM(nb_add);
1614 COPYNUM(nb_subtract);
1615 COPYNUM(nb_multiply);
1616 COPYNUM(nb_divide);
1617 COPYNUM(nb_remainder);
1618 COPYNUM(nb_divmod);
1619 COPYNUM(nb_power);
1620 COPYNUM(nb_negative);
1621 COPYNUM(nb_positive);
1622 COPYNUM(nb_absolute);
1623 COPYNUM(nb_nonzero);
1624 COPYNUM(nb_invert);
1625 COPYNUM(nb_lshift);
1626 COPYNUM(nb_rshift);
1627 COPYNUM(nb_and);
1628 COPYNUM(nb_xor);
1629 COPYNUM(nb_or);
1630 COPYNUM(nb_coerce);
1631 COPYNUM(nb_int);
1632 COPYNUM(nb_long);
1633 COPYNUM(nb_float);
1634 COPYNUM(nb_oct);
1635 COPYNUM(nb_hex);
1636 COPYNUM(nb_inplace_add);
1637 COPYNUM(nb_inplace_subtract);
1638 COPYNUM(nb_inplace_multiply);
1639 COPYNUM(nb_inplace_divide);
1640 COPYNUM(nb_inplace_remainder);
1641 COPYNUM(nb_inplace_power);
1642 COPYNUM(nb_inplace_lshift);
1643 COPYNUM(nb_inplace_rshift);
1644 COPYNUM(nb_inplace_and);
1645 COPYNUM(nb_inplace_xor);
1646 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001647 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1648 COPYNUM(nb_true_divide);
1649 COPYNUM(nb_floor_divide);
1650 COPYNUM(nb_inplace_true_divide);
1651 COPYNUM(nb_inplace_floor_divide);
1652 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 }
1654
Guido van Rossum13d52f02001-08-10 21:24:08 +00001655 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1656 basebase = base->tp_base;
1657 if (basebase->tp_as_sequence == NULL)
1658 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659 COPYSEQ(sq_length);
1660 COPYSEQ(sq_concat);
1661 COPYSEQ(sq_repeat);
1662 COPYSEQ(sq_item);
1663 COPYSEQ(sq_slice);
1664 COPYSEQ(sq_ass_item);
1665 COPYSEQ(sq_ass_slice);
1666 COPYSEQ(sq_contains);
1667 COPYSEQ(sq_inplace_concat);
1668 COPYSEQ(sq_inplace_repeat);
1669 }
1670
Guido van Rossum13d52f02001-08-10 21:24:08 +00001671 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1672 basebase = base->tp_base;
1673 if (basebase->tp_as_mapping == NULL)
1674 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675 COPYMAP(mp_length);
1676 COPYMAP(mp_subscript);
1677 COPYMAP(mp_ass_subscript);
1678 }
1679
Tim Petersfc57ccb2001-10-12 02:38:24 +00001680 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1681 basebase = base->tp_base;
1682 if (basebase->tp_as_buffer == NULL)
1683 basebase = NULL;
1684 COPYBUF(bf_getreadbuffer);
1685 COPYBUF(bf_getwritebuffer);
1686 COPYBUF(bf_getsegcount);
1687 COPYBUF(bf_getcharbuffer);
1688 }
1689
Guido van Rossum13d52f02001-08-10 21:24:08 +00001690 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691
Tim Peters6d6c1a32001-08-02 04:15:00 +00001692 COPYSLOT(tp_dealloc);
1693 COPYSLOT(tp_print);
1694 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1695 type->tp_getattr = base->tp_getattr;
1696 type->tp_getattro = base->tp_getattro;
1697 }
1698 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1699 type->tp_setattr = base->tp_setattr;
1700 type->tp_setattro = base->tp_setattro;
1701 }
1702 /* tp_compare see tp_richcompare */
1703 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001704 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001705 COPYSLOT(tp_call);
1706 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001707 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001708 if (type->tp_compare == NULL &&
1709 type->tp_richcompare == NULL &&
1710 type->tp_hash == NULL)
1711 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 type->tp_compare = base->tp_compare;
1713 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001714 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 }
1716 }
1717 else {
1718 COPYSLOT(tp_compare);
1719 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1721 COPYSLOT(tp_iter);
1722 COPYSLOT(tp_iternext);
1723 }
1724 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1725 COPYSLOT(tp_descr_get);
1726 COPYSLOT(tp_descr_set);
1727 COPYSLOT(tp_dictoffset);
1728 COPYSLOT(tp_init);
1729 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 COPYSLOT(tp_free);
1731 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732}
1733
Guido van Rossum13d52f02001-08-10 21:24:08 +00001734staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001735staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001736
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001738PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001740 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741 PyTypeObject *base;
1742 int i, n;
1743
Guido van Rossumd614f972001-08-10 17:39:49 +00001744 if (type->tp_flags & Py_TPFLAGS_READY) {
1745 assert(type->tp_dict != NULL);
1746 return 0;
1747 }
1748 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1749 assert(type->tp_dict == NULL);
1750
1751 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752
1753 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1754 base = type->tp_base;
1755 if (base == NULL && type != &PyBaseObject_Type)
1756 base = type->tp_base = &PyBaseObject_Type;
1757
1758 /* Initialize tp_bases */
1759 bases = type->tp_bases;
1760 if (bases == NULL) {
1761 if (base == NULL)
1762 bases = PyTuple_New(0);
1763 else
1764 bases = Py_BuildValue("(O)", base);
1765 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001766 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767 type->tp_bases = bases;
1768 }
1769
1770 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001771 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001772 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001773 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774 }
1775
1776 /* Initialize tp_defined */
1777 dict = type->tp_defined;
1778 if (dict == NULL) {
1779 dict = PyDict_New();
1780 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001781 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 type->tp_defined = dict;
1783 }
1784
1785 /* Add type-specific descriptors to tp_defined */
1786 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001787 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 if (type->tp_methods != NULL) {
1789 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001790 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791 }
1792 if (type->tp_members != NULL) {
1793 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001794 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795 }
1796 if (type->tp_getset != NULL) {
1797 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001798 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 }
1800
1801 /* Temporarily make tp_dict the same object as tp_defined.
1802 (This is needed to call mro(), and can stay this way for
1803 dynamic types). */
1804 Py_INCREF(type->tp_defined);
1805 type->tp_dict = type->tp_defined;
1806
1807 /* Calculate method resolution order */
1808 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001809 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 }
1811
Guido van Rossum13d52f02001-08-10 21:24:08 +00001812 /* Inherit special flags from dominant base */
1813 if (type->tp_base != NULL)
1814 inherit_special(type, type->tp_base);
1815
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001817 bases = type->tp_mro;
1818 assert(bases != NULL);
1819 assert(PyTuple_Check(bases));
1820 n = PyTuple_GET_SIZE(bases);
1821 for (i = 1; i < n; i++) {
1822 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1823 assert(PyType_Check(base));
1824 inherit_slots(type, base);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001825 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826
Guido van Rossum13d52f02001-08-10 21:24:08 +00001827 /* Some more special stuff */
1828 base = type->tp_base;
1829 if (base != NULL) {
1830 if (type->tp_as_number == NULL)
1831 type->tp_as_number = base->tp_as_number;
1832 if (type->tp_as_sequence == NULL)
1833 type->tp_as_sequence = base->tp_as_sequence;
1834 if (type->tp_as_mapping == NULL)
1835 type->tp_as_mapping = base->tp_as_mapping;
1836 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837
Guido van Rossum1c450732001-10-08 15:18:27 +00001838 /* Link into each base class's list of subclasses */
1839 bases = type->tp_bases;
1840 n = PyTuple_GET_SIZE(bases);
1841 for (i = 0; i < n; i++) {
1842 base = (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
1843 if (add_subclass((PyTypeObject *)base, type) < 0)
1844 goto error;
1845 }
1846
Guido van Rossum13d52f02001-08-10 21:24:08 +00001847 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001848 assert(type->tp_dict != NULL);
1849 type->tp_flags =
1850 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001852
1853 error:
1854 type->tp_flags &= ~Py_TPFLAGS_READYING;
1855 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856}
1857
Guido van Rossum1c450732001-10-08 15:18:27 +00001858static int
1859add_subclass(PyTypeObject *base, PyTypeObject *type)
1860{
1861 int i;
1862 PyObject *list, *ref, *new;
1863
1864 list = base->tp_subclasses;
1865 if (list == NULL) {
1866 base->tp_subclasses = list = PyList_New(0);
1867 if (list == NULL)
1868 return -1;
1869 }
1870 assert(PyList_Check(list));
1871 new = PyWeakref_NewRef((PyObject *)type, NULL);
1872 i = PyList_GET_SIZE(list);
1873 while (--i >= 0) {
1874 ref = PyList_GET_ITEM(list, i);
1875 assert(PyWeakref_CheckRef(ref));
1876 if (PyWeakref_GET_OBJECT(ref) == Py_None)
1877 return PyList_SetItem(list, i, new);
1878 }
1879 i = PyList_Append(list, new);
1880 Py_DECREF(new);
1881 return i;
1882}
1883
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884
1885/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1886
1887/* There's a wrapper *function* for each distinct function typedef used
1888 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1889 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1890 Most tables have only one entry; the tables for binary operators have two
1891 entries, one regular and one with reversed arguments. */
1892
1893static PyObject *
1894wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1895{
1896 inquiry func = (inquiry)wrapped;
1897 int res;
1898
1899 if (!PyArg_ParseTuple(args, ""))
1900 return NULL;
1901 res = (*func)(self);
1902 if (res == -1 && PyErr_Occurred())
1903 return NULL;
1904 return PyInt_FromLong((long)res);
1905}
1906
1907static struct wrapperbase tab_len[] = {
1908 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1909 {0}
1910};
1911
1912static PyObject *
1913wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1914{
1915 binaryfunc func = (binaryfunc)wrapped;
1916 PyObject *other;
1917
1918 if (!PyArg_ParseTuple(args, "O", &other))
1919 return NULL;
1920 return (*func)(self, other);
1921}
1922
1923static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001924wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
1925{
1926 binaryfunc func = (binaryfunc)wrapped;
1927 PyObject *other;
1928
1929 if (!PyArg_ParseTuple(args, "O", &other))
1930 return NULL;
1931 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001932 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001933 Py_INCREF(Py_NotImplemented);
1934 return Py_NotImplemented;
1935 }
1936 return (*func)(self, other);
1937}
1938
1939static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1941{
1942 binaryfunc func = (binaryfunc)wrapped;
1943 PyObject *other;
1944
1945 if (!PyArg_ParseTuple(args, "O", &other))
1946 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001947 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001948 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001949 Py_INCREF(Py_NotImplemented);
1950 return Py_NotImplemented;
1951 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 return (*func)(other, self);
1953}
1954
1955#undef BINARY
1956#define BINARY(NAME, OP) \
1957static struct wrapperbase tab_##NAME[] = { \
1958 {"__" #NAME "__", \
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001959 (wrapperfunc)wrap_binaryfunc_l, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00001960 "x.__" #NAME "__(y) <==> " #OP}, \
1961 {"__r" #NAME "__", \
1962 (wrapperfunc)wrap_binaryfunc_r, \
1963 "y.__r" #NAME "__(x) <==> " #OP}, \
1964 {0} \
1965}
1966
1967BINARY(add, "x+y");
1968BINARY(sub, "x-y");
1969BINARY(mul, "x*y");
1970BINARY(div, "x/y");
1971BINARY(mod, "x%y");
1972BINARY(divmod, "divmod(x,y)");
1973BINARY(lshift, "x<<y");
1974BINARY(rshift, "x>>y");
1975BINARY(and, "x&y");
1976BINARY(xor, "x^y");
1977BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001978
1979static PyObject *
1980wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1981{
1982 coercion func = (coercion)wrapped;
1983 PyObject *other, *res;
1984 int ok;
1985
1986 if (!PyArg_ParseTuple(args, "O", &other))
1987 return NULL;
1988 ok = func(&self, &other);
1989 if (ok < 0)
1990 return NULL;
1991 if (ok > 0) {
1992 Py_INCREF(Py_NotImplemented);
1993 return Py_NotImplemented;
1994 }
1995 res = PyTuple_New(2);
1996 if (res == NULL) {
1997 Py_DECREF(self);
1998 Py_DECREF(other);
1999 return NULL;
2000 }
2001 PyTuple_SET_ITEM(res, 0, self);
2002 PyTuple_SET_ITEM(res, 1, other);
2003 return res;
2004}
2005
2006static struct wrapperbase tab_coerce[] = {
2007 {"__coerce__", (wrapperfunc)wrap_coercefunc,
2008 "x.__coerce__(y) <==> coerce(x, y)"},
2009 {0}
2010};
2011
Guido van Rossum874f15a2001-09-25 21:16:33 +00002012BINARY(floordiv, "x//y");
2013BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014
2015static PyObject *
2016wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2017{
2018 ternaryfunc func = (ternaryfunc)wrapped;
2019 PyObject *other;
2020 PyObject *third = Py_None;
2021
2022 /* Note: This wrapper only works for __pow__() */
2023
2024 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2025 return NULL;
2026 return (*func)(self, other, third);
2027}
2028
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002029static PyObject *
2030wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2031{
2032 ternaryfunc func = (ternaryfunc)wrapped;
2033 PyObject *other;
2034 PyObject *third = Py_None;
2035
2036 /* Note: This wrapper only works for __pow__() */
2037
2038 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2039 return NULL;
2040 return (*func)(other, self, third);
2041}
2042
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043#undef TERNARY
2044#define TERNARY(NAME, OP) \
2045static struct wrapperbase tab_##NAME[] = { \
2046 {"__" #NAME "__", \
2047 (wrapperfunc)wrap_ternaryfunc, \
2048 "x.__" #NAME "__(y, z) <==> " #OP}, \
2049 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002050 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2052 {0} \
2053}
2054
2055TERNARY(pow, "(x**y) % z");
2056
2057#undef UNARY
2058#define UNARY(NAME, OP) \
2059static struct wrapperbase tab_##NAME[] = { \
2060 {"__" #NAME "__", \
2061 (wrapperfunc)wrap_unaryfunc, \
2062 "x.__" #NAME "__() <==> " #OP}, \
2063 {0} \
2064}
2065
2066static PyObject *
2067wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2068{
2069 unaryfunc func = (unaryfunc)wrapped;
2070
2071 if (!PyArg_ParseTuple(args, ""))
2072 return NULL;
2073 return (*func)(self);
2074}
2075
2076UNARY(neg, "-x");
2077UNARY(pos, "+x");
2078UNARY(abs, "abs(x)");
2079UNARY(nonzero, "x != 0");
2080UNARY(invert, "~x");
2081UNARY(int, "int(x)");
2082UNARY(long, "long(x)");
2083UNARY(float, "float(x)");
2084UNARY(oct, "oct(x)");
2085UNARY(hex, "hex(x)");
2086
2087#undef IBINARY
2088#define IBINARY(NAME, OP) \
2089static struct wrapperbase tab_##NAME[] = { \
2090 {"__" #NAME "__", \
2091 (wrapperfunc)wrap_binaryfunc, \
2092 "x.__" #NAME "__(y) <==> " #OP}, \
2093 {0} \
2094}
2095
2096IBINARY(iadd, "x+=y");
2097IBINARY(isub, "x-=y");
2098IBINARY(imul, "x*=y");
2099IBINARY(idiv, "x/=y");
2100IBINARY(imod, "x%=y");
2101IBINARY(ilshift, "x<<=y");
2102IBINARY(irshift, "x>>=y");
2103IBINARY(iand, "x&=y");
2104IBINARY(ixor, "x^=y");
2105IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002106IBINARY(ifloordiv, "x//=y");
2107IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108
2109#undef ITERNARY
2110#define ITERNARY(NAME, OP) \
2111static struct wrapperbase tab_##NAME[] = { \
2112 {"__" #NAME "__", \
2113 (wrapperfunc)wrap_ternaryfunc, \
2114 "x.__" #NAME "__(y) <==> " #OP}, \
2115 {0} \
2116}
2117
2118ITERNARY(ipow, "x = (x**y) % z");
2119
2120static struct wrapperbase tab_getitem[] = {
2121 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2122 "x.__getitem__(y) <==> x[y]"},
2123 {0}
2124};
2125
2126static PyObject *
2127wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2128{
2129 intargfunc func = (intargfunc)wrapped;
2130 int i;
2131
2132 if (!PyArg_ParseTuple(args, "i", &i))
2133 return NULL;
2134 return (*func)(self, i);
2135}
2136
2137static struct wrapperbase tab_mul_int[] = {
2138 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2139 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2140 {0}
2141};
2142
2143static struct wrapperbase tab_concat[] = {
2144 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2145 {0}
2146};
2147
2148static struct wrapperbase tab_imul_int[] = {
2149 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2150 {0}
2151};
2152
Guido van Rossum5d815f32001-08-17 21:57:47 +00002153static int
2154getindex(PyObject *self, PyObject *arg)
2155{
2156 int i;
2157
2158 i = PyInt_AsLong(arg);
2159 if (i == -1 && PyErr_Occurred())
2160 return -1;
2161 if (i < 0) {
2162 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2163 if (sq && sq->sq_length) {
2164 int n = (*sq->sq_length)(self);
2165 if (n < 0)
2166 return -1;
2167 i += n;
2168 }
2169 }
2170 return i;
2171}
2172
2173static PyObject *
2174wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2175{
2176 intargfunc func = (intargfunc)wrapped;
2177 PyObject *arg;
2178 int i;
2179
Guido van Rossumf4593e02001-10-03 12:09:30 +00002180 if (PyTuple_GET_SIZE(args) == 1) {
2181 arg = PyTuple_GET_ITEM(args, 0);
2182 i = getindex(self, arg);
2183 if (i == -1 && PyErr_Occurred())
2184 return NULL;
2185 return (*func)(self, i);
2186 }
2187 PyArg_ParseTuple(args, "O", &arg);
2188 assert(PyErr_Occurred());
2189 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002190}
2191
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002193 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002194 "x.__getitem__(i) <==> x[i]"},
2195 {0}
2196};
2197
2198static PyObject *
2199wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2200{
2201 intintargfunc func = (intintargfunc)wrapped;
2202 int i, j;
2203
2204 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2205 return NULL;
2206 return (*func)(self, i, j);
2207}
2208
2209static struct wrapperbase tab_getslice[] = {
2210 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2211 "x.__getslice__(i, j) <==> x[i:j]"},
2212 {0}
2213};
2214
2215static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002216wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217{
2218 intobjargproc func = (intobjargproc)wrapped;
2219 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002220 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002221
Guido van Rossum5d815f32001-08-17 21:57:47 +00002222 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2223 return NULL;
2224 i = getindex(self, arg);
2225 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002226 return NULL;
2227 res = (*func)(self, i, value);
2228 if (res == -1 && PyErr_Occurred())
2229 return NULL;
2230 Py_INCREF(Py_None);
2231 return Py_None;
2232}
2233
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002234static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002235wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002236{
2237 intobjargproc func = (intobjargproc)wrapped;
2238 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002239 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002240
Guido van Rossum5d815f32001-08-17 21:57:47 +00002241 if (!PyArg_ParseTuple(args, "O", &arg))
2242 return NULL;
2243 i = getindex(self, arg);
2244 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002245 return NULL;
2246 res = (*func)(self, i, NULL);
2247 if (res == -1 && PyErr_Occurred())
2248 return NULL;
2249 Py_INCREF(Py_None);
2250 return Py_None;
2251}
2252
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002254 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002255 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002256 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002257 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258 {0}
2259};
2260
2261static PyObject *
2262wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2263{
2264 intintobjargproc func = (intintobjargproc)wrapped;
2265 int i, j, res;
2266 PyObject *value;
2267
2268 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2269 return NULL;
2270 res = (*func)(self, i, j, value);
2271 if (res == -1 && PyErr_Occurred())
2272 return NULL;
2273 Py_INCREF(Py_None);
2274 return Py_None;
2275}
2276
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002277static PyObject *
2278wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2279{
2280 intintobjargproc func = (intintobjargproc)wrapped;
2281 int i, j, res;
2282
2283 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2284 return NULL;
2285 res = (*func)(self, i, j, NULL);
2286 if (res == -1 && PyErr_Occurred())
2287 return NULL;
2288 Py_INCREF(Py_None);
2289 return Py_None;
2290}
2291
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292static struct wrapperbase tab_setslice[] = {
2293 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2294 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002295 {"__delslice__", (wrapperfunc)wrap_delslice,
2296 "x.__delslice__(i, j) <==> del x[i:j]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297 {0}
2298};
2299
2300/* XXX objobjproc is a misnomer; should be objargpred */
2301static PyObject *
2302wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2303{
2304 objobjproc func = (objobjproc)wrapped;
2305 int res;
2306 PyObject *value;
2307
2308 if (!PyArg_ParseTuple(args, "O", &value))
2309 return NULL;
2310 res = (*func)(self, value);
2311 if (res == -1 && PyErr_Occurred())
2312 return NULL;
2313 return PyInt_FromLong((long)res);
2314}
2315
2316static struct wrapperbase tab_contains[] = {
2317 {"__contains__", (wrapperfunc)wrap_objobjproc,
2318 "x.__contains__(y) <==> y in x"},
2319 {0}
2320};
2321
2322static PyObject *
2323wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2324{
2325 objobjargproc func = (objobjargproc)wrapped;
2326 int res;
2327 PyObject *key, *value;
2328
2329 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2330 return NULL;
2331 res = (*func)(self, key, value);
2332 if (res == -1 && PyErr_Occurred())
2333 return NULL;
2334 Py_INCREF(Py_None);
2335 return Py_None;
2336}
2337
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002338static PyObject *
2339wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2340{
2341 objobjargproc func = (objobjargproc)wrapped;
2342 int res;
2343 PyObject *key;
2344
2345 if (!PyArg_ParseTuple(args, "O", &key))
2346 return NULL;
2347 res = (*func)(self, key, NULL);
2348 if (res == -1 && PyErr_Occurred())
2349 return NULL;
2350 Py_INCREF(Py_None);
2351 return Py_None;
2352}
2353
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354static struct wrapperbase tab_setitem[] = {
2355 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2356 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002357 {"__delitem__", (wrapperfunc)wrap_delitem,
2358 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359 {0}
2360};
2361
2362static PyObject *
2363wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2364{
2365 cmpfunc func = (cmpfunc)wrapped;
2366 int res;
2367 PyObject *other;
2368
2369 if (!PyArg_ParseTuple(args, "O", &other))
2370 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002371 if (other->ob_type->tp_compare != func &&
2372 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002373 PyErr_Format(
2374 PyExc_TypeError,
2375 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2376 self->ob_type->tp_name,
2377 self->ob_type->tp_name,
2378 other->ob_type->tp_name);
2379 return NULL;
2380 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381 res = (*func)(self, other);
2382 if (PyErr_Occurred())
2383 return NULL;
2384 return PyInt_FromLong((long)res);
2385}
2386
2387static struct wrapperbase tab_cmp[] = {
2388 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2389 "x.__cmp__(y) <==> cmp(x,y)"},
2390 {0}
2391};
2392
2393static struct wrapperbase tab_repr[] = {
2394 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2395 "x.__repr__() <==> repr(x)"},
2396 {0}
2397};
2398
2399static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002400 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2401 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402 {0}
2403};
2404
2405static PyObject *
2406wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2407{
2408 setattrofunc func = (setattrofunc)wrapped;
2409 int res;
2410 PyObject *name, *value;
2411
2412 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2413 return NULL;
2414 res = (*func)(self, name, value);
2415 if (res < 0)
2416 return NULL;
2417 Py_INCREF(Py_None);
2418 return Py_None;
2419}
2420
2421static PyObject *
2422wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2423{
2424 setattrofunc func = (setattrofunc)wrapped;
2425 int res;
2426 PyObject *name;
2427
2428 if (!PyArg_ParseTuple(args, "O", &name))
2429 return NULL;
2430 res = (*func)(self, name, NULL);
2431 if (res < 0)
2432 return NULL;
2433 Py_INCREF(Py_None);
2434 return Py_None;
2435}
2436
2437static struct wrapperbase tab_setattr[] = {
2438 {"__setattr__", (wrapperfunc)wrap_setattr,
2439 "x.__setattr__('name', value) <==> x.name = value"},
2440 {"__delattr__", (wrapperfunc)wrap_delattr,
2441 "x.__delattr__('name') <==> del x.name"},
2442 {0}
2443};
2444
2445static PyObject *
2446wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2447{
2448 hashfunc func = (hashfunc)wrapped;
2449 long res;
2450
2451 if (!PyArg_ParseTuple(args, ""))
2452 return NULL;
2453 res = (*func)(self);
2454 if (res == -1 && PyErr_Occurred())
2455 return NULL;
2456 return PyInt_FromLong(res);
2457}
2458
2459static struct wrapperbase tab_hash[] = {
2460 {"__hash__", (wrapperfunc)wrap_hashfunc,
2461 "x.__hash__() <==> hash(x)"},
2462 {0}
2463};
2464
2465static PyObject *
2466wrap_call(PyObject *self, PyObject *args, void *wrapped)
2467{
2468 ternaryfunc func = (ternaryfunc)wrapped;
2469
2470 /* XXX What about keyword arguments? */
2471 return (*func)(self, args, NULL);
2472}
2473
2474static struct wrapperbase tab_call[] = {
2475 {"__call__", (wrapperfunc)wrap_call,
2476 "x.__call__(...) <==> x(...)"},
2477 {0}
2478};
2479
2480static struct wrapperbase tab_str[] = {
2481 {"__str__", (wrapperfunc)wrap_unaryfunc,
2482 "x.__str__() <==> str(x)"},
2483 {0}
2484};
2485
2486static PyObject *
2487wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2488{
2489 richcmpfunc func = (richcmpfunc)wrapped;
2490 PyObject *other;
2491
2492 if (!PyArg_ParseTuple(args, "O", &other))
2493 return NULL;
2494 return (*func)(self, other, op);
2495}
2496
2497#undef RICHCMP_WRAPPER
2498#define RICHCMP_WRAPPER(NAME, OP) \
2499static PyObject * \
2500richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2501{ \
2502 return wrap_richcmpfunc(self, args, wrapped, OP); \
2503}
2504
Jack Jansen8e938b42001-08-08 15:29:49 +00002505RICHCMP_WRAPPER(lt, Py_LT)
2506RICHCMP_WRAPPER(le, Py_LE)
2507RICHCMP_WRAPPER(eq, Py_EQ)
2508RICHCMP_WRAPPER(ne, Py_NE)
2509RICHCMP_WRAPPER(gt, Py_GT)
2510RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002511
2512#undef RICHCMP_ENTRY
2513#define RICHCMP_ENTRY(NAME, EXPR) \
2514 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2515 "x.__" #NAME "__(y) <==> " EXPR}
2516
2517static struct wrapperbase tab_richcmp[] = {
2518 RICHCMP_ENTRY(lt, "x<y"),
2519 RICHCMP_ENTRY(le, "x<=y"),
2520 RICHCMP_ENTRY(eq, "x==y"),
2521 RICHCMP_ENTRY(ne, "x!=y"),
2522 RICHCMP_ENTRY(gt, "x>y"),
2523 RICHCMP_ENTRY(ge, "x>=y"),
2524 {0}
2525};
2526
2527static struct wrapperbase tab_iter[] = {
2528 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2529 {0}
2530};
2531
2532static PyObject *
2533wrap_next(PyObject *self, PyObject *args, void *wrapped)
2534{
2535 unaryfunc func = (unaryfunc)wrapped;
2536 PyObject *res;
2537
2538 if (!PyArg_ParseTuple(args, ""))
2539 return NULL;
2540 res = (*func)(self);
2541 if (res == NULL && !PyErr_Occurred())
2542 PyErr_SetNone(PyExc_StopIteration);
2543 return res;
2544}
2545
2546static struct wrapperbase tab_next[] = {
2547 {"next", (wrapperfunc)wrap_next,
2548 "x.next() -> the next value, or raise StopIteration"},
2549 {0}
2550};
2551
2552static PyObject *
2553wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2554{
2555 descrgetfunc func = (descrgetfunc)wrapped;
2556 PyObject *obj;
2557 PyObject *type = NULL;
2558
2559 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2560 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561 return (*func)(self, obj, type);
2562}
2563
2564static struct wrapperbase tab_descr_get[] = {
2565 {"__get__", (wrapperfunc)wrap_descr_get,
2566 "descr.__get__(obj, type) -> value"},
2567 {0}
2568};
2569
2570static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002571wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572{
2573 descrsetfunc func = (descrsetfunc)wrapped;
2574 PyObject *obj, *value;
2575 int ret;
2576
2577 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2578 return NULL;
2579 ret = (*func)(self, obj, value);
2580 if (ret < 0)
2581 return NULL;
2582 Py_INCREF(Py_None);
2583 return Py_None;
2584}
2585
2586static struct wrapperbase tab_descr_set[] = {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002587 {"__set__", (wrapperfunc)wrap_descr_set,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002588 "descr.__set__(obj, value)"},
2589 {0}
2590};
2591
2592static PyObject *
2593wrap_init(PyObject *self, PyObject *args, void *wrapped)
2594{
2595 initproc func = (initproc)wrapped;
2596
2597 /* XXX What about keyword arguments? */
2598 if (func(self, args, NULL) < 0)
2599 return NULL;
2600 Py_INCREF(Py_None);
2601 return Py_None;
2602}
2603
2604static struct wrapperbase tab_init[] = {
2605 {"__init__", (wrapperfunc)wrap_init,
2606 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002607 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002608 {0}
2609};
2610
2611static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002612tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613{
Barry Warsaw60f01882001-08-22 19:24:42 +00002614 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002615 PyObject *arg0, *res;
2616
2617 if (self == NULL || !PyType_Check(self))
2618 Py_FatalError("__new__() called with non-type 'self'");
2619 type = (PyTypeObject *)self;
2620 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002621 PyErr_Format(PyExc_TypeError,
2622 "%s.__new__(): not enough arguments",
2623 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002624 return NULL;
2625 }
2626 arg0 = PyTuple_GET_ITEM(args, 0);
2627 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002628 PyErr_Format(PyExc_TypeError,
2629 "%s.__new__(X): X is not a type object (%s)",
2630 type->tp_name,
2631 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002632 return NULL;
2633 }
2634 subtype = (PyTypeObject *)arg0;
2635 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002636 PyErr_Format(PyExc_TypeError,
2637 "%s.__new__(%s): %s is not a subtype of %s",
2638 type->tp_name,
2639 subtype->tp_name,
2640 subtype->tp_name,
2641 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002642 return NULL;
2643 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002644
2645 /* Check that the use doesn't do something silly and unsafe like
2646 object.__new__(dictionary). To do this, we check that the
2647 most derived base that's not a heap type is this type. */
2648 staticbase = subtype;
2649 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2650 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002651 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002652 PyErr_Format(PyExc_TypeError,
2653 "%s.__new__(%s) is not safe, use %s.__new__()",
2654 type->tp_name,
2655 subtype->tp_name,
2656 staticbase == NULL ? "?" : staticbase->tp_name);
2657 return NULL;
2658 }
2659
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002660 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2661 if (args == NULL)
2662 return NULL;
2663 res = type->tp_new(subtype, args, kwds);
2664 Py_DECREF(args);
2665 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666}
2667
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002668static struct PyMethodDef tp_new_methoddef[] = {
2669 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2670 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671 {0}
2672};
2673
2674static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002675add_tp_new_wrapper(PyTypeObject *type)
2676{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002677 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002678
Guido van Rossumf040ede2001-08-07 16:40:56 +00002679 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2680 return 0;
2681 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002682 if (func == NULL)
2683 return -1;
2684 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2685}
2686
Guido van Rossum13d52f02001-08-10 21:24:08 +00002687static int
2688add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2689{
2690 PyObject *dict = type->tp_defined;
2691
2692 for (; wraps->name != NULL; wraps++) {
2693 PyObject *descr;
2694 if (PyDict_GetItemString(dict, wraps->name))
2695 continue;
2696 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2697 if (descr == NULL)
2698 return -1;
2699 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2700 return -1;
2701 Py_DECREF(descr);
2702 }
2703 return 0;
2704}
2705
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002706/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002707 dictionary with method descriptors for function slots. For each
2708 function slot (like tp_repr) that's defined in the type, one or
2709 more corresponding descriptors are added in the type's tp_defined
2710 dictionary under the appropriate name (like __repr__). Some
2711 function slots cause more than one descriptor to be added (for
2712 example, the nb_add slot adds both __add__ and __radd__
2713 descriptors) and some function slots compete for the same
2714 descriptor (for example both sq_item and mp_subscript generate a
2715 __getitem__ descriptor). This only adds new descriptors and
2716 doesn't overwrite entries in tp_defined that were previously
2717 defined. The descriptors contain a reference to the C function
2718 they must call, so that it's safe if they are copied into a
2719 subtype's __dict__ and the subtype has a different C function in
2720 its slot -- calling the method defined by the descriptor will call
2721 the C function that was used to create it, rather than the C
2722 function present in the slot when it is called. (This is important
2723 because a subtype may have a C function in the slot that calls the
2724 method from the dictionary, and we want to avoid infinite recursion
2725 here.) */
2726
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002727static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728add_operators(PyTypeObject *type)
2729{
2730 PySequenceMethods *sq;
2731 PyMappingMethods *mp;
2732 PyNumberMethods *nb;
2733
2734#undef ADD
2735#define ADD(SLOT, TABLE) \
2736 if (SLOT) { \
2737 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2738 return -1; \
2739 }
2740
2741 if ((sq = type->tp_as_sequence) != NULL) {
2742 ADD(sq->sq_length, tab_len);
2743 ADD(sq->sq_concat, tab_concat);
2744 ADD(sq->sq_repeat, tab_mul_int);
2745 ADD(sq->sq_item, tab_getitem_int);
2746 ADD(sq->sq_slice, tab_getslice);
2747 ADD(sq->sq_ass_item, tab_setitem_int);
2748 ADD(sq->sq_ass_slice, tab_setslice);
2749 ADD(sq->sq_contains, tab_contains);
2750 ADD(sq->sq_inplace_concat, tab_iadd);
2751 ADD(sq->sq_inplace_repeat, tab_imul_int);
2752 }
2753
2754 if ((mp = type->tp_as_mapping) != NULL) {
2755 if (sq->sq_length == NULL)
2756 ADD(mp->mp_length, tab_len);
2757 ADD(mp->mp_subscript, tab_getitem);
2758 ADD(mp->mp_ass_subscript, tab_setitem);
2759 }
2760
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002761 if ((nb = type->tp_as_number) != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762 ADD(nb->nb_add, tab_add);
2763 ADD(nb->nb_subtract, tab_sub);
2764 ADD(nb->nb_multiply, tab_mul);
2765 ADD(nb->nb_divide, tab_div);
2766 ADD(nb->nb_remainder, tab_mod);
2767 ADD(nb->nb_divmod, tab_divmod);
2768 ADD(nb->nb_power, tab_pow);
2769 ADD(nb->nb_negative, tab_neg);
2770 ADD(nb->nb_positive, tab_pos);
2771 ADD(nb->nb_absolute, tab_abs);
2772 ADD(nb->nb_nonzero, tab_nonzero);
2773 ADD(nb->nb_invert, tab_invert);
2774 ADD(nb->nb_lshift, tab_lshift);
2775 ADD(nb->nb_rshift, tab_rshift);
2776 ADD(nb->nb_and, tab_and);
2777 ADD(nb->nb_xor, tab_xor);
2778 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002779 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780 ADD(nb->nb_int, tab_int);
2781 ADD(nb->nb_long, tab_long);
2782 ADD(nb->nb_float, tab_float);
2783 ADD(nb->nb_oct, tab_oct);
2784 ADD(nb->nb_hex, tab_hex);
2785 ADD(nb->nb_inplace_add, tab_iadd);
2786 ADD(nb->nb_inplace_subtract, tab_isub);
2787 ADD(nb->nb_inplace_multiply, tab_imul);
2788 ADD(nb->nb_inplace_divide, tab_idiv);
2789 ADD(nb->nb_inplace_remainder, tab_imod);
2790 ADD(nb->nb_inplace_power, tab_ipow);
2791 ADD(nb->nb_inplace_lshift, tab_ilshift);
2792 ADD(nb->nb_inplace_rshift, tab_irshift);
2793 ADD(nb->nb_inplace_and, tab_iand);
2794 ADD(nb->nb_inplace_xor, tab_ixor);
2795 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002796 if (type->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossum874f15a2001-09-25 21:16:33 +00002797 ADD(nb->nb_floor_divide, tab_floordiv);
2798 ADD(nb->nb_true_divide, tab_truediv);
2799 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2800 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2801 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002802 }
2803
2804 ADD(type->tp_getattro, tab_getattr);
2805 ADD(type->tp_setattro, tab_setattr);
2806 ADD(type->tp_compare, tab_cmp);
2807 ADD(type->tp_repr, tab_repr);
2808 ADD(type->tp_hash, tab_hash);
2809 ADD(type->tp_call, tab_call);
2810 ADD(type->tp_str, tab_str);
2811 ADD(type->tp_richcompare, tab_richcmp);
2812 ADD(type->tp_iter, tab_iter);
2813 ADD(type->tp_iternext, tab_next);
2814 ADD(type->tp_descr_get, tab_descr_get);
2815 ADD(type->tp_descr_set, tab_descr_set);
2816 ADD(type->tp_init, tab_init);
2817
Guido van Rossumf040ede2001-08-07 16:40:56 +00002818 if (type->tp_new != NULL) {
2819 if (add_tp_new_wrapper(type) < 0)
2820 return -1;
2821 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822
2823 return 0;
2824}
2825
Guido van Rossumf040ede2001-08-07 16:40:56 +00002826/* Slot wrappers that call the corresponding __foo__ slot. See comments
2827 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002828
Guido van Rossumdc91b992001-08-08 22:26:22 +00002829#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002831FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002833 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002834 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002835}
2836
Guido van Rossumdc91b992001-08-08 22:26:22 +00002837#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002838static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002839FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002840{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002841 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002842 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002843}
2844
Guido van Rossumdc91b992001-08-08 22:26:22 +00002845
2846#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002847static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002848FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002850 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002851 int do_other = self->ob_type != other->ob_type && \
2852 other->ob_type->tp_as_number != NULL && \
2853 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002854 if (self->ob_type->tp_as_number != NULL && \
2855 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2856 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002857 if (do_other && \
2858 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2859 r = call_maybe( \
2860 other, ROPSTR, &rcache_str, "(O)", self); \
2861 if (r != Py_NotImplemented) \
2862 return r; \
2863 Py_DECREF(r); \
2864 do_other = 0; \
2865 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002866 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002867 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002868 if (r != Py_NotImplemented || \
2869 other->ob_type == self->ob_type) \
2870 return r; \
2871 Py_DECREF(r); \
2872 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002873 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002874 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002875 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002876 } \
2877 Py_INCREF(Py_NotImplemented); \
2878 return Py_NotImplemented; \
2879}
2880
2881#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2882 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2883
2884#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2885static PyObject * \
2886FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2887{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002888 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002889 return call_method(self, OPSTR, &cache_str, \
2890 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891}
2892
2893static int
2894slot_sq_length(PyObject *self)
2895{
Guido van Rossum2730b132001-08-28 18:22:14 +00002896 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002897 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002898 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899
2900 if (res == NULL)
2901 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002902 len = (int)PyInt_AsLong(res);
2903 Py_DECREF(res);
2904 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002905}
2906
Guido van Rossumdc91b992001-08-08 22:26:22 +00002907SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2908SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002909
2910/* Super-optimized version of slot_sq_item.
2911 Other slots could do the same... */
2912static PyObject *
2913slot_sq_item(PyObject *self, int i)
2914{
2915 static PyObject *getitem_str;
2916 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2917 descrgetfunc f;
2918
2919 if (getitem_str == NULL) {
2920 getitem_str = PyString_InternFromString("__getitem__");
2921 if (getitem_str == NULL)
2922 return NULL;
2923 }
2924 func = _PyType_Lookup(self->ob_type, getitem_str);
2925 if (func != NULL) {
2926 if (func->ob_type == &PyWrapperDescr_Type) {
2927 PyWrapperDescrObject *wrapper =
2928 (PyWrapperDescrObject *)func;
2929 if (wrapper->d_base->wrapper == wrap_sq_item) {
2930 intargfunc f;
2931 f = (intargfunc)(wrapper->d_wrapped);
2932 return f(self, i);
2933 }
2934 }
2935 if ((f = func->ob_type->tp_descr_get) == NULL)
2936 Py_INCREF(func);
2937 else
2938 func = f(func, self, (PyObject *)(self->ob_type));
2939 ival = PyInt_FromLong(i);
2940 if (ival != NULL) {
2941 args = PyTuple_New(1);
2942 if (args != NULL) {
2943 PyTuple_SET_ITEM(args, 0, ival);
2944 retval = PyObject_Call(func, args, NULL);
2945 Py_XDECREF(args);
2946 Py_XDECREF(func);
2947 return retval;
2948 }
2949 }
2950 }
2951 else {
2952 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2953 }
2954 Py_XDECREF(args);
2955 Py_XDECREF(ival);
2956 Py_XDECREF(func);
2957 return NULL;
2958}
2959
Guido van Rossumdc91b992001-08-08 22:26:22 +00002960SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961
2962static int
2963slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2964{
2965 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002966 static PyObject *delitem_str, *setitem_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, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002970 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002972 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002973 "(iO)", index, 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_ass_slice(PyObject *self, int i, int j, PyObject *value)
2982{
2983 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002984 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985
2986 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002987 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002988 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002990 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002991 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992 if (res == NULL)
2993 return -1;
2994 Py_DECREF(res);
2995 return 0;
2996}
2997
2998static int
2999slot_sq_contains(PyObject *self, PyObject *value)
3000{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003001 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003002 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003
Guido van Rossum55f20992001-10-01 17:18:22 +00003004 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003005
3006 if (func != NULL) {
3007 args = Py_BuildValue("(O)", value);
3008 if (args == NULL)
3009 res = NULL;
3010 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003011 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003012 Py_DECREF(args);
3013 }
3014 Py_DECREF(func);
3015 if (res == NULL)
3016 return -1;
3017 return PyObject_IsTrue(res);
3018 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003019 else if (PyErr_Occurred())
3020 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003021 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003022 return _PySequence_IterSearch(self, value,
3023 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003024 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025}
3026
Guido van Rossumdc91b992001-08-08 22:26:22 +00003027SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3028SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003029
3030#define slot_mp_length slot_sq_length
3031
Guido van Rossumdc91b992001-08-08 22:26:22 +00003032SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033
3034static int
3035slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3036{
3037 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003038 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039
3040 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003041 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003042 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003044 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003045 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046 if (res == NULL)
3047 return -1;
3048 Py_DECREF(res);
3049 return 0;
3050}
3051
Guido van Rossumdc91b992001-08-08 22:26:22 +00003052SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3053SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3054SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3055SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3056SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3057SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3058
3059staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3060
3061SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3062 nb_power, "__pow__", "__rpow__")
3063
3064static PyObject *
3065slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3066{
Guido van Rossum2730b132001-08-28 18:22:14 +00003067 static PyObject *pow_str;
3068
Guido van Rossumdc91b992001-08-08 22:26:22 +00003069 if (modulus == Py_None)
3070 return slot_nb_power_binary(self, other);
3071 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003072 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003073 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003074}
3075
3076SLOT0(slot_nb_negative, "__neg__")
3077SLOT0(slot_nb_positive, "__pos__")
3078SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079
3080static int
3081slot_nb_nonzero(PyObject *self)
3082{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003083 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003084 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085
Guido van Rossum55f20992001-10-01 17:18:22 +00003086 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003087 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003088 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003089 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003090 func = lookup_maybe(self, "__len__", &len_str);
3091 if (func == NULL) {
3092 if (PyErr_Occurred())
3093 return -1;
3094 else
3095 return 1;
3096 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003097 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003098 res = PyObject_CallObject(func, NULL);
3099 Py_DECREF(func);
3100 if (res == NULL)
3101 return -1;
3102 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103}
3104
Guido van Rossumdc91b992001-08-08 22:26:22 +00003105SLOT0(slot_nb_invert, "__invert__")
3106SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3107SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3108SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3109SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3110SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003111
3112static int
3113slot_nb_coerce(PyObject **a, PyObject **b)
3114{
3115 static PyObject *coerce_str;
3116 PyObject *self = *a, *other = *b;
3117
3118 if (self->ob_type->tp_as_number != NULL &&
3119 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3120 PyObject *r;
3121 r = call_maybe(
3122 self, "__coerce__", &coerce_str, "(O)", other);
3123 if (r == NULL)
3124 return -1;
3125 if (r == Py_NotImplemented) {
3126 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003127 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003128 else {
3129 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3130 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003131 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003132 Py_DECREF(r);
3133 return -1;
3134 }
3135 *a = PyTuple_GET_ITEM(r, 0);
3136 Py_INCREF(*a);
3137 *b = PyTuple_GET_ITEM(r, 1);
3138 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003139 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003140 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003141 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003142 }
3143 if (other->ob_type->tp_as_number != NULL &&
3144 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3145 PyObject *r;
3146 r = call_maybe(
3147 other, "__coerce__", &coerce_str, "(O)", self);
3148 if (r == NULL)
3149 return -1;
3150 if (r == Py_NotImplemented) {
3151 Py_DECREF(r);
3152 return 1;
3153 }
3154 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3155 PyErr_SetString(PyExc_TypeError,
3156 "__coerce__ didn't return a 2-tuple");
3157 Py_DECREF(r);
3158 return -1;
3159 }
3160 *a = PyTuple_GET_ITEM(r, 1);
3161 Py_INCREF(*a);
3162 *b = PyTuple_GET_ITEM(r, 0);
3163 Py_INCREF(*b);
3164 Py_DECREF(r);
3165 return 0;
3166 }
3167 return 1;
3168}
3169
Guido van Rossumdc91b992001-08-08 22:26:22 +00003170SLOT0(slot_nb_int, "__int__")
3171SLOT0(slot_nb_long, "__long__")
3172SLOT0(slot_nb_float, "__float__")
3173SLOT0(slot_nb_oct, "__oct__")
3174SLOT0(slot_nb_hex, "__hex__")
3175SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3176SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3177SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3178SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3179SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3180SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3181SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3182SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3183SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3184SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3185SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3186SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3187 "__floordiv__", "__rfloordiv__")
3188SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3189SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3190SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191
3192static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003193half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003195 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003196 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003197 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003198
Guido van Rossum60718732001-08-28 17:47:51 +00003199 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003200 if (func == NULL) {
3201 PyErr_Clear();
3202 }
3203 else {
3204 args = Py_BuildValue("(O)", other);
3205 if (args == NULL)
3206 res = NULL;
3207 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003208 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003209 Py_DECREF(args);
3210 }
3211 if (res != Py_NotImplemented) {
3212 if (res == NULL)
3213 return -2;
3214 c = PyInt_AsLong(res);
3215 Py_DECREF(res);
3216 if (c == -1 && PyErr_Occurred())
3217 return -2;
3218 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3219 }
3220 Py_DECREF(res);
3221 }
3222 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003223}
3224
Guido van Rossumab3b0342001-09-18 20:38:53 +00003225/* This slot is published for the benefit of try_3way_compare in object.c */
3226int
3227_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003228{
3229 int c;
3230
Guido van Rossumab3b0342001-09-18 20:38:53 +00003231 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003232 c = half_compare(self, other);
3233 if (c <= 1)
3234 return c;
3235 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003236 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003237 c = half_compare(other, self);
3238 if (c < -1)
3239 return -2;
3240 if (c <= 1)
3241 return -c;
3242 }
3243 return (void *)self < (void *)other ? -1 :
3244 (void *)self > (void *)other ? 1 : 0;
3245}
3246
3247static PyObject *
3248slot_tp_repr(PyObject *self)
3249{
3250 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003251 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003252
Guido van Rossum60718732001-08-28 17:47:51 +00003253 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003254 if (func != NULL) {
3255 res = PyEval_CallObject(func, NULL);
3256 Py_DECREF(func);
3257 return res;
3258 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003259 PyErr_Clear();
3260 return PyString_FromFormat("<%s object at %p>",
3261 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003262}
3263
3264static PyObject *
3265slot_tp_str(PyObject *self)
3266{
3267 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003268 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003269
Guido van Rossum60718732001-08-28 17:47:51 +00003270 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003271 if (func != NULL) {
3272 res = PyEval_CallObject(func, NULL);
3273 Py_DECREF(func);
3274 return res;
3275 }
3276 else {
3277 PyErr_Clear();
3278 return slot_tp_repr(self);
3279 }
3280}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281
3282static long
3283slot_tp_hash(PyObject *self)
3284{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003285 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003286 static PyObject *hash_str, *eq_str, *cmp_str;
3287
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288 long h;
3289
Guido van Rossum60718732001-08-28 17:47:51 +00003290 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003291
3292 if (func != NULL) {
3293 res = PyEval_CallObject(func, NULL);
3294 Py_DECREF(func);
3295 if (res == NULL)
3296 return -1;
3297 h = PyInt_AsLong(res);
3298 }
3299 else {
3300 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003301 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003302 if (func == NULL) {
3303 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003304 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003305 }
3306 if (func != NULL) {
3307 Py_DECREF(func);
3308 PyErr_SetString(PyExc_TypeError, "unhashable type");
3309 return -1;
3310 }
3311 PyErr_Clear();
3312 h = _Py_HashPointer((void *)self);
3313 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003314 if (h == -1 && !PyErr_Occurred())
3315 h = -2;
3316 return h;
3317}
3318
3319static PyObject *
3320slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3321{
Guido van Rossum60718732001-08-28 17:47:51 +00003322 static PyObject *call_str;
3323 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324 PyObject *res;
3325
3326 if (meth == NULL)
3327 return NULL;
3328 res = PyObject_Call(meth, args, kwds);
3329 Py_DECREF(meth);
3330 return res;
3331}
3332
Tim Peters6d6c1a32001-08-02 04:15:00 +00003333static PyObject *
3334slot_tp_getattro(PyObject *self, PyObject *name)
3335{
3336 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003337 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003338 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339
Guido van Rossum8e248182001-08-12 05:17:56 +00003340 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003341 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003342 if (getattr_str == NULL)
3343 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003344 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003345 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003346 if (getattr == NULL) {
3347 /* Avoid further slowdowns */
3348 if (tp->tp_getattro == slot_tp_getattro)
3349 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003350 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003351 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352 return PyObject_CallFunction(getattr, "OO", self, name);
3353}
3354
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003355static PyObject *
3356slot_tp_getattr_hook(PyObject *self, PyObject *name)
3357{
3358 PyTypeObject *tp = self->ob_type;
3359 PyObject *getattr, *getattribute, *res;
3360 static PyObject *getattribute_str = NULL;
3361 static PyObject *getattr_str = NULL;
3362
3363 if (getattr_str == NULL) {
3364 getattr_str = PyString_InternFromString("__getattr__");
3365 if (getattr_str == NULL)
3366 return NULL;
3367 }
3368 if (getattribute_str == NULL) {
3369 getattribute_str =
3370 PyString_InternFromString("__getattribute__");
3371 if (getattribute_str == NULL)
3372 return NULL;
3373 }
3374 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003375 if (getattr == NULL && tp->tp_getattro == slot_tp_getattr_hook) {
3376 /* No __getattr__ hook: use a simpler dispatcher */
3377 tp->tp_getattro = slot_tp_getattro;
3378 return slot_tp_getattro(self, name);
3379 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003380 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003381 if (getattribute != NULL &&
3382 getattribute->ob_type == &PyWrapperDescr_Type &&
3383 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
Guido van Rossum825d8752001-10-15 19:44:24 +00003384 (void *)PyObject_GenericGetAttr)
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003385 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003386 if (getattr == NULL && getattribute == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003387 /* Use the default dispatcher */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003388 if (tp->tp_getattro == slot_tp_getattr_hook)
3389 tp->tp_getattro = PyObject_GenericGetAttr;
3390 return PyObject_GenericGetAttr(self, name);
3391 }
3392 if (getattribute == NULL)
3393 res = PyObject_GenericGetAttr(self, name);
3394 else
3395 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003396 if (getattr != NULL &&
3397 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003398 PyErr_Clear();
3399 res = PyObject_CallFunction(getattr, "OO", self, name);
3400 }
3401 return res;
3402}
3403
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404static int
3405slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3406{
3407 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003408 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409
3410 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003411 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003412 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003414 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003415 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 if (res == NULL)
3417 return -1;
3418 Py_DECREF(res);
3419 return 0;
3420}
3421
3422/* Map rich comparison operators to their __xx__ namesakes */
3423static char *name_op[] = {
3424 "__lt__",
3425 "__le__",
3426 "__eq__",
3427 "__ne__",
3428 "__gt__",
3429 "__ge__",
3430};
3431
3432static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003433half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003435 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003436 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437
Guido van Rossum60718732001-08-28 17:47:51 +00003438 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003439 if (func == NULL) {
3440 PyErr_Clear();
3441 Py_INCREF(Py_NotImplemented);
3442 return Py_NotImplemented;
3443 }
3444 args = Py_BuildValue("(O)", other);
3445 if (args == NULL)
3446 res = NULL;
3447 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003448 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003449 Py_DECREF(args);
3450 }
3451 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003452 return res;
3453}
3454
Guido van Rossumb8f63662001-08-15 23:57:02 +00003455/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3456static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3457
3458static PyObject *
3459slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3460{
3461 PyObject *res;
3462
3463 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3464 res = half_richcompare(self, other, op);
3465 if (res != Py_NotImplemented)
3466 return res;
3467 Py_DECREF(res);
3468 }
3469 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3470 res = half_richcompare(other, self, swapped_op[op]);
3471 if (res != Py_NotImplemented) {
3472 return res;
3473 }
3474 Py_DECREF(res);
3475 }
3476 Py_INCREF(Py_NotImplemented);
3477 return Py_NotImplemented;
3478}
3479
3480static PyObject *
3481slot_tp_iter(PyObject *self)
3482{
3483 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003484 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003485
Guido van Rossum60718732001-08-28 17:47:51 +00003486 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003487 if (func != NULL) {
3488 res = PyObject_CallObject(func, NULL);
3489 Py_DECREF(func);
3490 return res;
3491 }
3492 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003493 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003494 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003495 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003496 return NULL;
3497 }
3498 Py_DECREF(func);
3499 return PySeqIter_New(self);
3500}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003501
3502static PyObject *
3503slot_tp_iternext(PyObject *self)
3504{
Guido van Rossum2730b132001-08-28 18:22:14 +00003505 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003506 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003507}
3508
Guido van Rossum1a493502001-08-17 16:47:50 +00003509static PyObject *
3510slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3511{
3512 PyTypeObject *tp = self->ob_type;
3513 PyObject *get;
3514 static PyObject *get_str = NULL;
3515
3516 if (get_str == NULL) {
3517 get_str = PyString_InternFromString("__get__");
3518 if (get_str == NULL)
3519 return NULL;
3520 }
3521 get = _PyType_Lookup(tp, get_str);
3522 if (get == NULL) {
3523 /* Avoid further slowdowns */
3524 if (tp->tp_descr_get == slot_tp_descr_get)
3525 tp->tp_descr_get = NULL;
3526 Py_INCREF(self);
3527 return self;
3528 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003529 if (obj == NULL)
3530 obj = Py_None;
3531 if (type == NULL)
3532 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003533 return PyObject_CallFunction(get, "OOO", self, obj, type);
3534}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003535
3536static int
3537slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3538{
Guido van Rossum2c252392001-08-24 10:13:31 +00003539 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003540 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003541
3542 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003543 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003544 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003545 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003546 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003547 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003548 if (res == NULL)
3549 return -1;
3550 Py_DECREF(res);
3551 return 0;
3552}
3553
3554static int
3555slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3556{
Guido van Rossum60718732001-08-28 17:47:51 +00003557 static PyObject *init_str;
3558 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003559 PyObject *res;
3560
3561 if (meth == NULL)
3562 return -1;
3563 res = PyObject_Call(meth, args, kwds);
3564 Py_DECREF(meth);
3565 if (res == NULL)
3566 return -1;
3567 Py_DECREF(res);
3568 return 0;
3569}
3570
3571static PyObject *
3572slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3573{
3574 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3575 PyObject *newargs, *x;
3576 int i, n;
3577
3578 if (func == NULL)
3579 return NULL;
3580 assert(PyTuple_Check(args));
3581 n = PyTuple_GET_SIZE(args);
3582 newargs = PyTuple_New(n+1);
3583 if (newargs == NULL)
3584 return NULL;
3585 Py_INCREF(type);
3586 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3587 for (i = 0; i < n; i++) {
3588 x = PyTuple_GET_ITEM(args, i);
3589 Py_INCREF(x);
3590 PyTuple_SET_ITEM(newargs, i+1, x);
3591 }
3592 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003593 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003594 Py_DECREF(func);
3595 return x;
3596}
3597
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003598
3599/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3600 functions. The offsets here are relative to the 'etype' structure, which
3601 incorporates the additional structures used for numbers, sequences and
3602 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3603 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3604 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3605
3606typedef struct {
3607 char *name;
3608 int offset;
3609 void *function;
3610 wrapperfunc wrapper;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003611 PyObject *name_strobj;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003612} slotdef;
3613
3614#undef TPSLOT
3615#undef ETSLOT
3616#undef SQSLOT
3617#undef MPSLOT
3618#undef NBSLOT
3619#undef BINSLOT
3620#undef RBINSLOT
3621
3622#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
Guido van Rossum825d8752001-10-15 19:44:24 +00003623 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003624#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
Guido van Rossum825d8752001-10-15 19:44:24 +00003625 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003626#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3627 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER)
3628#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3629 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER)
3630#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3631 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER)
3632#define BINSLOT(NAME, SLOT, FUNCTION) \
3633 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l)
3634#define RBINSLOT(NAME, SLOT, FUNCTION) \
3635 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r)
3636
3637static slotdef slotdefs[] = {
3638 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry),
3639 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc),
3640 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3641 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3642 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item),
3643 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc),
3644 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem),
3645 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem),
3646 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3647 wrap_intintobjargproc),
3648 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice),
3649 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc),
3650 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3651 wrap_binaryfunc),
3652 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3653 wrap_intargfunc),
3654
3655 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003656 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3657 wrap_binaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003658 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3659 wrap_objobjargproc),
3660 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3661 wrap_delitem),
3662
3663 BINSLOT("__add__", nb_add, slot_nb_add),
3664 RBINSLOT("__radd__", nb_add, slot_nb_add),
3665 BINSLOT("__sub__", nb_subtract, slot_nb_subtract),
3666 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract),
3667 BINSLOT("__mul__", nb_multiply, slot_nb_multiply),
3668 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply),
3669 BINSLOT("__div__", nb_divide, slot_nb_divide),
3670 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide),
3671 BINSLOT("__mod__", nb_remainder, slot_nb_remainder),
3672 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder),
3673 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod),
3674 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod),
3675 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc),
3676 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r),
3677 NBSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc),
3678 NBSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc),
3679 NBSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc),
3680 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc),
3681 NBSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc),
3682 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift),
3683 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift),
3684 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift),
3685 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift),
3686 BINSLOT("__and__", nb_and, slot_nb_and),
3687 RBINSLOT("__rand__", nb_and, slot_nb_and),
3688 BINSLOT("__xor__", nb_xor, slot_nb_xor),
3689 RBINSLOT("__rxor__", nb_xor, slot_nb_xor),
3690 BINSLOT("__or__", nb_or, slot_nb_or),
3691 RBINSLOT("__ror__", nb_or, slot_nb_or),
3692 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc),
3693 NBSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc),
3694 NBSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc),
3695 NBSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc),
3696 NBSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc),
3697 NBSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc),
3698 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3699 wrap_binaryfunc),
3700 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3701 wrap_binaryfunc),
3702 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3703 wrap_binaryfunc),
3704 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3705 wrap_binaryfunc),
3706 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3707 wrap_binaryfunc),
3708 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3709 wrap_ternaryfunc),
3710 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3711 wrap_binaryfunc),
3712 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3713 wrap_binaryfunc),
3714 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3715 wrap_binaryfunc),
3716 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3717 wrap_binaryfunc),
3718 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3719 wrap_binaryfunc),
3720 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide),
3721 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide),
3722 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide),
3723 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide),
3724 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3725 slot_nb_inplace_floor_divide, wrap_binaryfunc),
3726 NBSLOT("__itruediv__", nb_inplace_true_divide,
3727 slot_nb_inplace_true_divide, wrap_binaryfunc),
3728
3729 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003730 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003731 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc),
3732 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc),
3733 TPSLOT("__call__", tp_call, slot_tp_call, wrap_call),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003734 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003735 wrap_binaryfunc),
3736 TPSLOT("__getattribute__", tp_getattr, NULL, NULL),
3737 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL),
3738 TPSLOT("__getattr__", tp_getattr, NULL, NULL),
3739 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr),
3740 TPSLOT("__setattr__", tp_setattr, NULL, NULL),
3741 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr),
3742 TPSLOT("__delattr__", tp_setattr, NULL, NULL),
3743 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt),
3744 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le),
3745 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq),
3746 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne),
3747 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt),
3748 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge),
3749 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc),
3750 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next),
3751 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get),
3752 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set),
3753 TPSLOT("__init__", tp_init, slot_tp_init, wrap_init),
3754 TPSLOT("__new__", tp_new, slot_tp_new, NULL),
3755 {NULL}
3756};
3757
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003758static void **
3759slotptr(PyTypeObject *type, int offset)
3760{
3761 char *ptr;
3762
3763 assert(offset >= 0);
3764 assert(offset < offsetof(etype, as_buffer));
3765 if (offset >= offsetof(etype, as_mapping)) {
3766 ptr = (void *)type->tp_as_mapping;
3767 offset -= offsetof(etype, as_mapping);
3768 }
3769 else if (offset >= offsetof(etype, as_sequence)) {
3770 ptr = (void *)type->tp_as_sequence;
3771 offset -= offsetof(etype, as_sequence);
3772 }
3773 else if (offset >= offsetof(etype, as_number)) {
3774 ptr = (void *)type->tp_as_number;
3775 offset -= offsetof(etype, as_number);
3776 }
3777 else {
3778 ptr = (void *)type;
3779 }
3780 if (ptr != NULL)
3781 ptr += offset;
3782 return (void **)ptr;
3783}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003784
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003785staticforward int recurse_down_subclasses(PyTypeObject *type, slotdef *p);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003786
3787static int
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003788update_one_slot(PyTypeObject *type, slotdef *p0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003789{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003790 slotdef *p = p0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003791 PyObject *descr;
3792 PyWrapperDescrObject *d;
3793 void *generic = NULL, *specific = NULL;
3794 int use_generic = 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003795 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003796 void **ptr;
3797
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003798 offset = p->offset;
3799 ptr = slotptr(type, offset);
3800 if (ptr == NULL)
3801 return recurse_down_subclasses(type, p);
3802 do {
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003803 descr = _PyType_Lookup(type, p->name_strobj);
3804 if (descr == NULL)
3805 continue;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003806 generic = p->function;
3807 if (descr->ob_type == &PyWrapperDescr_Type) {
3808 d = (PyWrapperDescrObject *)descr;
3809 if (d->d_base->wrapper == p->wrapper &&
3810 PyType_IsSubtype(type, d->d_type)) {
3811 if (specific == NULL ||
3812 specific == d->d_wrapped)
3813 specific = d->d_wrapped;
3814 else
3815 use_generic = 1;
3816 }
3817 }
3818 else
3819 use_generic = 1;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003820 } while ((++p)->offset == offset);
3821 if (specific && !use_generic)
3822 *ptr = specific;
3823 else
3824 *ptr = generic;
3825 return recurse_down_subclasses(type, p0);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003826}
3827
3828static int
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003829recurse_down_subclasses(PyTypeObject *type, slotdef *p)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003830{
3831 PyTypeObject *subclass;
3832 PyObject *ref, *subclasses;
3833 int i, n;
3834
3835 subclasses = type->tp_subclasses;
3836 if (subclasses == NULL)
3837 return 0;
3838 assert(PyList_Check(subclasses));
3839 n = PyList_GET_SIZE(subclasses);
3840 for (i = 0; i < n; i++) {
3841 ref = PyList_GET_ITEM(subclasses, i);
3842 assert(PyWeakref_CheckRef(ref));
3843 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3844 if (subclass == NULL)
3845 continue;
3846 assert(PyType_Check(subclass));
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003847 if (update_one_slot(subclass, p) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003848 return -1;
3849 }
3850 return 0;
3851}
3852
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003853static int
3854slotdef_cmp(const void *aa, const void *bb)
3855{
3856 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3857 int c = a->offset - b->offset;
3858 if (c != 0)
3859 return c;
3860 else
3861 return a - b;
3862}
3863
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003864static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003865init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003866{
3867 slotdef *p;
3868 static int initialized = 0;
3869
3870 if (initialized)
3871 return;
3872 for (p = slotdefs; p->name; p++) {
3873 p->name_strobj = PyString_InternFromString(p->name);
3874 if (!p->name_strobj)
3875 Py_FatalError("XXX ouch");
3876 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003877 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003878 initialized = 1;
3879}
3880
3881static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003882collect_ptrs(PyObject *name, slotdef *ptrs[])
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003883{
3884 slotdef *p;
3885
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003886 init_slotdefs();
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003887 for (p = slotdefs; p->name; p++) {
3888 if (name == p->name_strobj)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003889 *ptrs++ = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003890 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003891 *ptrs = NULL;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003892}
3893
3894static int
3895update_slot(PyTypeObject *type, PyObject *name)
3896{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003897 slotdef *ptrs[10];
3898 slotdef *p;
3899 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003900
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003901 collect_ptrs(name, ptrs);
3902 for (pp = ptrs; *pp; pp++) {
3903 p = *pp;
3904 while (p > slotdefs && p->offset == (p-1)->offset)
3905 --p;
3906 if (update_one_slot(type, p) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003907 return -1;
3908 }
3909 return 0;
3910}
3911
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003913fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003914{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003915 slotdef *p;
3916 PyObject *mro, *descr;
3917 PyTypeObject *base;
3918 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003919 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003920 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003921 void *generic, *specific;
3922 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003923
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003924 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003925 mro = type->tp_mro;
3926 assert(PyTuple_Check(mro));
3927 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003928 for (p = slotdefs; p->name; ) {
3929 offset = p->offset;
3930 ptr = slotptr(type, offset);
3931 if (!ptr) {
3932 do {
3933 ++p;
3934 } while (p->offset == offset);
3935 continue;
3936 }
3937 generic = specific = NULL;
3938 use_generic = 0;
3939 do {
3940 descr = NULL;
3941 for (i = 0; i < n; i++) {
3942 base = (PyTypeObject *)PyTuple_GET_ITEM(mro, i);
3943 assert(PyType_Check(base));
3944 descr = PyDict_GetItem(
3945 base->tp_defined, p->name_strobj);
3946 if (descr != NULL)
3947 break;
3948 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003949 if (descr == NULL)
3950 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003951 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003952 if (descr->ob_type == &PyWrapperDescr_Type) {
3953 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003954 if (d->d_base->wrapper == p->wrapper &&
3955 PyType_IsSubtype(type, d->d_type)) {
3956 if (specific == NULL ||
3957 specific == d->d_wrapped)
3958 specific = d->d_wrapped;
3959 else
3960 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003961 }
3962 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003963 else
3964 use_generic = 1;
3965 } while ((++p)->offset == offset);
3966 if (specific && !use_generic)
3967 *ptr = specific;
3968 else
3969 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003972
3973
3974/* Cooperative 'super' */
3975
3976typedef struct {
3977 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003978 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003979 PyObject *obj;
3980} superobject;
3981
Guido van Rossum6f799372001-09-20 20:46:19 +00003982static PyMemberDef super_members[] = {
3983 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3984 "the class invoking super()"},
3985 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3986 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003987 {0}
3988};
3989
Guido van Rossum705f0f52001-08-24 16:47:00 +00003990static void
3991super_dealloc(PyObject *self)
3992{
3993 superobject *su = (superobject *)self;
3994
Guido van Rossum048eb752001-10-02 21:24:57 +00003995 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003996 Py_XDECREF(su->obj);
3997 Py_XDECREF(su->type);
3998 self->ob_type->tp_free(self);
3999}
4000
4001static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004002super_repr(PyObject *self)
4003{
4004 superobject *su = (superobject *)self;
4005
4006 if (su->obj)
4007 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004008 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004009 su->type ? su->type->tp_name : "NULL",
4010 su->obj->ob_type->tp_name);
4011 else
4012 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004013 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004014 su->type ? su->type->tp_name : "NULL");
4015}
4016
4017static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004018super_getattro(PyObject *self, PyObject *name)
4019{
4020 superobject *su = (superobject *)self;
4021
4022 if (su->obj != NULL) {
4023 PyObject *mro, *res, *tmp;
4024 descrgetfunc f;
4025 int i, n;
4026
Guido van Rossume705ef12001-08-29 15:47:06 +00004027 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004028 if (mro == NULL)
4029 n = 0;
4030 else {
4031 assert(PyTuple_Check(mro));
4032 n = PyTuple_GET_SIZE(mro);
4033 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004034 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004035 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004036 break;
4037 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004038 if (i >= n && PyType_Check(su->obj)) {
4039 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004040 if (mro == NULL)
4041 n = 0;
4042 else {
4043 assert(PyTuple_Check(mro));
4044 n = PyTuple_GET_SIZE(mro);
4045 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004046 for (i = 0; i < n; i++) {
4047 if ((PyObject *)(su->type) ==
4048 PyTuple_GET_ITEM(mro, i))
4049 break;
4050 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004051 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004052 i++;
4053 res = NULL;
4054 for (; i < n; i++) {
4055 tmp = PyTuple_GET_ITEM(mro, i);
4056 assert(PyType_Check(tmp));
4057 res = PyDict_GetItem(
4058 ((PyTypeObject *)tmp)->tp_defined, name);
4059 if (res != NULL) {
4060 Py_INCREF(res);
4061 f = res->ob_type->tp_descr_get;
4062 if (f != NULL) {
4063 tmp = f(res, su->obj, res);
4064 Py_DECREF(res);
4065 res = tmp;
4066 }
4067 return res;
4068 }
4069 }
4070 }
4071 return PyObject_GenericGetAttr(self, name);
4072}
4073
4074static PyObject *
4075super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4076{
4077 superobject *su = (superobject *)self;
4078 superobject *new;
4079
4080 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4081 /* Not binding to an object, or already bound */
4082 Py_INCREF(self);
4083 return self;
4084 }
4085 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
4086 if (new == NULL)
4087 return NULL;
4088 Py_INCREF(su->type);
4089 Py_INCREF(obj);
4090 new->type = su->type;
4091 new->obj = obj;
4092 return (PyObject *)new;
4093}
4094
4095static int
4096super_init(PyObject *self, PyObject *args, PyObject *kwds)
4097{
4098 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004099 PyTypeObject *type;
4100 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004101
4102 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4103 return -1;
4104 if (obj == Py_None)
4105 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00004106 if (obj != NULL &&
4107 !PyType_IsSubtype(obj->ob_type, type) &&
4108 !(PyType_Check(obj) &&
4109 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004110 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00004111 "super(type, obj): "
4112 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004113 return -1;
4114 }
4115 Py_INCREF(type);
4116 Py_XINCREF(obj);
4117 su->type = type;
4118 su->obj = obj;
4119 return 0;
4120}
4121
4122static char super_doc[] =
4123"super(type) -> unbound super object\n"
4124"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004125"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004126"Typical use to call a cooperative superclass method:\n"
4127"class C(B):\n"
4128" def meth(self, arg):\n"
4129" super(C, self).meth(arg)";
4130
Guido van Rossum048eb752001-10-02 21:24:57 +00004131static int
4132super_traverse(PyObject *self, visitproc visit, void *arg)
4133{
4134 superobject *su = (superobject *)self;
4135 int err;
4136
4137#define VISIT(SLOT) \
4138 if (SLOT) { \
4139 err = visit((PyObject *)(SLOT), arg); \
4140 if (err) \
4141 return err; \
4142 }
4143
4144 VISIT(su->obj);
4145 VISIT(su->type);
4146
4147#undef VISIT
4148
4149 return 0;
4150}
4151
Guido van Rossum705f0f52001-08-24 16:47:00 +00004152PyTypeObject PySuper_Type = {
4153 PyObject_HEAD_INIT(&PyType_Type)
4154 0, /* ob_size */
4155 "super", /* tp_name */
4156 sizeof(superobject), /* tp_basicsize */
4157 0, /* tp_itemsize */
4158 /* methods */
4159 super_dealloc, /* tp_dealloc */
4160 0, /* tp_print */
4161 0, /* tp_getattr */
4162 0, /* tp_setattr */
4163 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004164 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004165 0, /* tp_as_number */
4166 0, /* tp_as_sequence */
4167 0, /* tp_as_mapping */
4168 0, /* tp_hash */
4169 0, /* tp_call */
4170 0, /* tp_str */
4171 super_getattro, /* tp_getattro */
4172 0, /* tp_setattro */
4173 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004174 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4175 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004176 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004177 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004178 0, /* tp_clear */
4179 0, /* tp_richcompare */
4180 0, /* tp_weaklistoffset */
4181 0, /* tp_iter */
4182 0, /* tp_iternext */
4183 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004184 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004185 0, /* tp_getset */
4186 0, /* tp_base */
4187 0, /* tp_dict */
4188 super_descr_get, /* tp_descr_get */
4189 0, /* tp_descr_set */
4190 0, /* tp_dictoffset */
4191 super_init, /* tp_init */
4192 PyType_GenericAlloc, /* tp_alloc */
4193 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004194 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004195};