blob: 59ec5882942eb554e21bd247d32de11711e1fd8b [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{
59 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ||
60 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 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
81 Py_INCREF(type->tp_dict);
82 return type->tp_dict;
83 }
84 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000085}
86
Tim Peters6d6c1a32001-08-02 04:15:00 +000087static PyObject *
88type_defined(PyTypeObject *type, void *context)
89{
90 if (type->tp_defined == NULL) {
91 Py_INCREF(Py_None);
92 return Py_None;
93 }
94 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
95 Py_INCREF(type->tp_defined);
96 return type->tp_defined;
97 }
98 return PyDictProxy_New(type->tp_defined);
99}
100
101static PyObject *
102type_dynamic(PyTypeObject *type, void *context)
103{
104 PyObject *res;
105
106 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
107 Py_INCREF(res);
108 return res;
109}
110
Guido van Rossum32d34c82001-09-20 21:45:26 +0000111PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000112 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000113 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114 {"__dict__", (getter)type_dict, NULL, NULL},
115 {"__defined__", (getter)type_defined, NULL, NULL},
116 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
117 {0}
118};
119
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000120static int
121type_compare(PyObject *v, PyObject *w)
122{
123 /* This is called with type objects only. So we
124 can just compare the addresses. */
125 Py_uintptr_t vv = (Py_uintptr_t)v;
126 Py_uintptr_t ww = (Py_uintptr_t)w;
127 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
128}
129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000131type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000134 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000135
136 mod = type_module(type, NULL);
137 if (mod == NULL)
138 PyErr_Clear();
139 else if (!PyString_Check(mod)) {
140 Py_DECREF(mod);
141 mod = NULL;
142 }
143 name = type_name(type, NULL);
144 if (name == NULL)
145 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000146
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000147 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
148 kind = "class";
149 else
150 kind = "type";
151
Barry Warsaw7ce36942001-08-24 18:34:26 +0000152 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000153 rtn = PyString_FromFormat("<%s '%s.%s'>",
154 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000155 PyString_AS_STRING(mod),
156 PyString_AS_STRING(name));
157 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000158 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000159 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000160
Guido van Rossumc3542212001-08-16 09:18:56 +0000161 Py_XDECREF(mod);
162 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000163 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Tim Peters6d6c1a32001-08-02 04:15:00 +0000166static PyObject *
167type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
168{
169 PyObject *obj;
170
171 if (type->tp_new == NULL) {
172 PyErr_Format(PyExc_TypeError,
173 "cannot create '%.100s' instances",
174 type->tp_name);
175 return NULL;
176 }
177
Tim Peters3f996e72001-09-13 19:18:27 +0000178 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 if (obj != NULL) {
180 type = obj->ob_type;
181 if (type->tp_init != NULL &&
182 type->tp_init(obj, args, kwds) < 0) {
183 Py_DECREF(obj);
184 obj = NULL;
185 }
186 }
187 return obj;
188}
189
190PyObject *
191PyType_GenericAlloc(PyTypeObject *type, int nitems)
192{
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000193#define PTRSIZE (sizeof(PyObject *))
194
Tim Peters406fe3b2001-10-06 19:04:01 +0000195 size_t size = (size_t)_PyObject_VAR_SIZE(type, nitems);
196 size_t padding = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000197 PyObject *obj;
198
Tim Peters406fe3b2001-10-06 19:04:01 +0000199 /* Round up size, if necessary, so that the __dict__ pointer
200 following the variable part is properly aligned for the platform.
201 This is needed only for types with a vrbl number of items
202 before the __dict__ pointer == types that record the dict offset
203 as a negative offset from the end of the object. If tp_dictoffset
204 is 0, there is no __dict__; if positive, tp_dict was declared in a C
205 struct so the compiler already took care of aligning it. */
206 if (type->tp_dictoffset < 0) {
207 padding = PTRSIZE - size % PTRSIZE;
208 if (padding == PTRSIZE)
209 padding = 0;
210 size += padding;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000211 }
Tim Peters406fe3b2001-10-06 19:04:01 +0000212
213 if (PyType_IS_GC(type))
214 obj = _PyObject_GC_Malloc(type, nitems, padding);
215 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000216 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000217
Neil Schemenauerc806c882001-08-29 23:54:54 +0000218 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000219 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000220
Neil Schemenauerc806c882001-08-29 23:54:54 +0000221 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000222
Tim Peters6d6c1a32001-08-02 04:15:00 +0000223 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
224 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000225
Tim Peters6d6c1a32001-08-02 04:15:00 +0000226 if (type->tp_itemsize == 0)
227 PyObject_INIT(obj, type);
228 else
229 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000230
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000232 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000233 return obj;
234}
235
236PyObject *
237PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
238{
239 return type->tp_alloc(type, 0);
240}
241
Guido van Rossum9475a232001-10-05 20:51:39 +0000242/* Helpers for subtyping */
243
244static int
245subtype_traverse(PyObject *self, visitproc visit, void *arg)
246{
247 PyTypeObject *type, *base;
248 traverseproc f;
249 int err;
250
251 /* Find the nearest base with a different tp_traverse */
252 type = self->ob_type;
253 base = type->tp_base;
254 while ((f = base->tp_traverse) == subtype_traverse) {
255 base = base->tp_base;
256 assert(base);
257 }
258
259 if (type->tp_dictoffset != base->tp_dictoffset) {
260 PyObject **dictptr = _PyObject_GetDictPtr(self);
261 if (dictptr && *dictptr) {
262 err = visit(*dictptr, arg);
263 if (err)
264 return err;
265 }
266 }
267
268 if (f)
269 return f(self, visit, arg);
270 return 0;
271}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000272
273static void
274subtype_dealloc(PyObject *self)
275{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000276 PyTypeObject *type, *base;
277 destructor f;
278
279 /* This exists so we can DECREF self->ob_type */
280
281 /* Find the nearest base with a different tp_dealloc */
282 type = self->ob_type;
283 base = type->tp_base;
284 while ((f = base->tp_dealloc) == subtype_dealloc) {
285 base = base->tp_base;
286 assert(base);
287 }
288
289 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000290 if (type->tp_dictoffset && !base->tp_dictoffset) {
291 PyObject **dictptr = _PyObject_GetDictPtr(self);
292 if (dictptr != NULL) {
293 PyObject *dict = *dictptr;
294 if (dict != NULL) {
295 Py_DECREF(dict);
296 *dictptr = NULL;
297 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000298 }
299 }
300
Guido van Rossum9676b222001-08-17 20:32:36 +0000301 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000302 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000303 PyObject_ClearWeakRefs(self);
304
Tim Peters6d6c1a32001-08-02 04:15:00 +0000305 /* Finalize GC if the base doesn't do GC and we do */
306 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000307 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000308
309 /* Call the base tp_dealloc() */
310 assert(f);
311 f(self);
312
313 /* Can't reference self beyond this point */
314 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
315 Py_DECREF(type);
316 }
317}
318
319staticforward void override_slots(PyTypeObject *type, PyObject *dict);
320staticforward PyTypeObject *solid_base(PyTypeObject *type);
321
322typedef struct {
323 PyTypeObject type;
324 PyNumberMethods as_number;
325 PySequenceMethods as_sequence;
326 PyMappingMethods as_mapping;
327 PyBufferProcs as_buffer;
328 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000329 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000330} etype;
331
332/* type test with subclassing support */
333
334int
335PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
336{
337 PyObject *mro;
338
Guido van Rossum9478d072001-09-07 18:52:13 +0000339 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
340 return b == a || b == &PyBaseObject_Type;
341
Tim Peters6d6c1a32001-08-02 04:15:00 +0000342 mro = a->tp_mro;
343 if (mro != NULL) {
344 /* Deal with multiple inheritance without recursion
345 by walking the MRO tuple */
346 int i, n;
347 assert(PyTuple_Check(mro));
348 n = PyTuple_GET_SIZE(mro);
349 for (i = 0; i < n; i++) {
350 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
351 return 1;
352 }
353 return 0;
354 }
355 else {
356 /* a is not completely initilized yet; follow tp_base */
357 do {
358 if (a == b)
359 return 1;
360 a = a->tp_base;
361 } while (a != NULL);
362 return b == &PyBaseObject_Type;
363 }
364}
365
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000366/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000367 without looking in the instance dictionary
368 (so we can't use PyObject_GetAttr) but still binding
369 it to the instance. The arguments are the object,
370 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000371 static variable used to cache the interned Python string.
372
373 Two variants:
374
375 - lookup_maybe() returns NULL without raising an exception
376 when the _PyType_Lookup() call fails;
377
378 - lookup_method() always raises an exception upon errors.
379*/
Guido van Rossum60718732001-08-28 17:47:51 +0000380
381static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000382lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000383{
384 PyObject *res;
385
386 if (*attrobj == NULL) {
387 *attrobj = PyString_InternFromString(attrstr);
388 if (*attrobj == NULL)
389 return NULL;
390 }
391 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000392 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000393 descrgetfunc f;
394 if ((f = res->ob_type->tp_descr_get) == NULL)
395 Py_INCREF(res);
396 else
397 res = f(res, self, (PyObject *)(self->ob_type));
398 }
399 return res;
400}
401
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000402static PyObject *
403lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
404{
405 PyObject *res = lookup_maybe(self, attrstr, attrobj);
406 if (res == NULL && !PyErr_Occurred())
407 PyErr_SetObject(PyExc_AttributeError, *attrobj);
408 return res;
409}
410
Guido van Rossum2730b132001-08-28 18:22:14 +0000411/* A variation of PyObject_CallMethod that uses lookup_method()
412 instead of PyObject_GetAttrString(). This uses the same convention
413 as lookup_method to cache the interned name string object. */
414
415PyObject *
416call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
417{
418 va_list va;
419 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000420 va_start(va, format);
421
Guido van Rossumda21c012001-10-03 00:50:18 +0000422 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000423 if (func == NULL) {
424 va_end(va);
425 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000426 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000427 return NULL;
428 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000429
430 if (format && *format)
431 args = Py_VaBuildValue(format, va);
432 else
433 args = PyTuple_New(0);
434
435 va_end(va);
436
437 if (args == NULL)
438 return NULL;
439
440 assert(PyTuple_Check(args));
441 retval = PyObject_Call(func, args, NULL);
442
443 Py_DECREF(args);
444 Py_DECREF(func);
445
446 return retval;
447}
448
449/* Clone of call_method() that returns NotImplemented when the lookup fails. */
450
451PyObject *
452call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
453{
454 va_list va;
455 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000456 va_start(va, format);
457
Guido van Rossumda21c012001-10-03 00:50:18 +0000458 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000459 if (func == NULL) {
460 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000461 if (!PyErr_Occurred()) {
462 Py_INCREF(Py_NotImplemented);
463 return Py_NotImplemented;
464 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000465 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000466 }
467
468 if (format && *format)
469 args = Py_VaBuildValue(format, va);
470 else
471 args = PyTuple_New(0);
472
473 va_end(va);
474
Guido van Rossum717ce002001-09-14 16:58:08 +0000475 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000476 return NULL;
477
Guido van Rossum717ce002001-09-14 16:58:08 +0000478 assert(PyTuple_Check(args));
479 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000480
481 Py_DECREF(args);
482 Py_DECREF(func);
483
484 return retval;
485}
486
Tim Peters6d6c1a32001-08-02 04:15:00 +0000487/* Method resolution order algorithm from "Putting Metaclasses to Work"
488 by Forman and Danforth (Addison-Wesley 1999). */
489
490static int
491conservative_merge(PyObject *left, PyObject *right)
492{
493 int left_size;
494 int right_size;
495 int i, j, r, ok;
496 PyObject *temp, *rr;
497
498 assert(PyList_Check(left));
499 assert(PyList_Check(right));
500
501 again:
502 left_size = PyList_GET_SIZE(left);
503 right_size = PyList_GET_SIZE(right);
504 for (i = 0; i < left_size; i++) {
505 for (j = 0; j < right_size; j++) {
506 if (PyList_GET_ITEM(left, i) ==
507 PyList_GET_ITEM(right, j)) {
508 /* found a merge point */
509 temp = PyList_New(0);
510 if (temp == NULL)
511 return -1;
512 for (r = 0; r < j; r++) {
513 rr = PyList_GET_ITEM(right, r);
514 ok = PySequence_Contains(left, rr);
515 if (ok < 0) {
516 Py_DECREF(temp);
517 return -1;
518 }
519 if (!ok) {
520 ok = PyList_Append(temp, rr);
521 if (ok < 0) {
522 Py_DECREF(temp);
523 return -1;
524 }
525 }
526 }
527 ok = PyList_SetSlice(left, i, i, temp);
528 Py_DECREF(temp);
529 if (ok < 0)
530 return -1;
531 ok = PyList_SetSlice(right, 0, j+1, NULL);
532 if (ok < 0)
533 return -1;
534 goto again;
535 }
536 }
537 }
538 return PyList_SetSlice(left, left_size, left_size, right);
539}
540
541static int
542serious_order_disagreements(PyObject *left, PyObject *right)
543{
544 return 0; /* XXX later -- for now, we cheat: "don't do that" */
545}
546
547static PyObject *
548mro_implementation(PyTypeObject *type)
549{
550 int i, n, ok;
551 PyObject *bases, *result;
552
553 bases = type->tp_bases;
554 n = PyTuple_GET_SIZE(bases);
555 result = Py_BuildValue("[O]", (PyObject *)type);
556 if (result == NULL)
557 return NULL;
558 for (i = 0; i < n; i++) {
559 PyTypeObject *base =
560 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
561 PyObject *parentMRO = PySequence_List(base->tp_mro);
562 if (parentMRO == NULL) {
563 Py_DECREF(result);
564 return NULL;
565 }
566 if (serious_order_disagreements(result, parentMRO)) {
567 Py_DECREF(result);
568 return NULL;
569 }
570 ok = conservative_merge(result, parentMRO);
571 Py_DECREF(parentMRO);
572 if (ok < 0) {
573 Py_DECREF(result);
574 return NULL;
575 }
576 }
577 return result;
578}
579
580static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000581mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000582{
583 PyTypeObject *type = (PyTypeObject *)self;
584
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585 return mro_implementation(type);
586}
587
588static int
589mro_internal(PyTypeObject *type)
590{
591 PyObject *mro, *result, *tuple;
592
593 if (type->ob_type == &PyType_Type) {
594 result = mro_implementation(type);
595 }
596 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000597 static PyObject *mro_str;
598 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000599 if (mro == NULL)
600 return -1;
601 result = PyObject_CallObject(mro, NULL);
602 Py_DECREF(mro);
603 }
604 if (result == NULL)
605 return -1;
606 tuple = PySequence_Tuple(result);
607 Py_DECREF(result);
608 type->tp_mro = tuple;
609 return 0;
610}
611
612
613/* Calculate the best base amongst multiple base classes.
614 This is the first one that's on the path to the "solid base". */
615
616static PyTypeObject *
617best_base(PyObject *bases)
618{
619 int i, n;
620 PyTypeObject *base, *winner, *candidate, *base_i;
621
622 assert(PyTuple_Check(bases));
623 n = PyTuple_GET_SIZE(bases);
624 assert(n > 0);
625 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
626 winner = &PyBaseObject_Type;
627 for (i = 0; i < n; i++) {
628 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
629 if (!PyType_Check((PyObject *)base_i)) {
630 PyErr_SetString(
631 PyExc_TypeError,
632 "bases must be types");
633 return NULL;
634 }
635 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000636 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000637 return NULL;
638 }
639 candidate = solid_base(base_i);
640 if (PyType_IsSubtype(winner, candidate))
641 ;
642 else if (PyType_IsSubtype(candidate, winner)) {
643 winner = candidate;
644 base = base_i;
645 }
646 else {
647 PyErr_SetString(
648 PyExc_TypeError,
649 "multiple bases have "
650 "instance lay-out conflict");
651 return NULL;
652 }
653 }
654 assert(base != NULL);
655 return base;
656}
657
658static int
659extra_ivars(PyTypeObject *type, PyTypeObject *base)
660{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000661 size_t t_size = type->tp_basicsize;
662 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663
Guido van Rossum9676b222001-08-17 20:32:36 +0000664 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665 if (type->tp_itemsize || base->tp_itemsize) {
666 /* If itemsize is involved, stricter rules */
667 return t_size != b_size ||
668 type->tp_itemsize != base->tp_itemsize;
669 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000670 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
671 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
672 t_size -= sizeof(PyObject *);
673 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
674 type->tp_dictoffset + sizeof(PyObject *) == t_size)
675 t_size -= sizeof(PyObject *);
676
677 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000678}
679
680static PyTypeObject *
681solid_base(PyTypeObject *type)
682{
683 PyTypeObject *base;
684
685 if (type->tp_base)
686 base = solid_base(type->tp_base);
687 else
688 base = &PyBaseObject_Type;
689 if (extra_ivars(type, base))
690 return type;
691 else
692 return base;
693}
694
695staticforward void object_dealloc(PyObject *);
696staticforward int object_init(PyObject *, PyObject *, PyObject *);
697
698static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000699subtype_dict(PyObject *obj, void *context)
700{
701 PyObject **dictptr = _PyObject_GetDictPtr(obj);
702 PyObject *dict;
703
704 if (dictptr == NULL) {
705 PyErr_SetString(PyExc_AttributeError,
706 "This object has no __dict__");
707 return NULL;
708 }
709 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000710 if (dict == NULL)
711 *dictptr = dict = PyDict_New();
712 Py_XINCREF(dict);
713 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000714}
715
Guido van Rossum32d34c82001-09-20 21:45:26 +0000716PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000717 {"__dict__", subtype_dict, NULL, NULL},
718 {0},
719};
720
721static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000722type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
723{
724 PyObject *name, *bases, *dict;
725 static char *kwlist[] = {"name", "bases", "dict", 0};
726 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000727 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000728 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000729 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000730 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000732 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733 if (metatype == &PyType_Type &&
734 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
735 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000736 PyObject *x = PyTuple_GET_ITEM(args, 0);
737 Py_INCREF(x->ob_type);
738 return (PyObject *) x->ob_type;
739 }
740
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000741 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000742 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
743 &name,
744 &PyTuple_Type, &bases,
745 &PyDict_Type, &dict))
746 return NULL;
747
748 /* Determine the proper metatype to deal with this,
749 and check for metatype conflicts while we're at it.
750 Note that if some other metatype wins to contract,
751 it's possible that its instances are not types. */
752 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000753 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000754 for (i = 0; i < nbases; i++) {
755 tmp = PyTuple_GET_ITEM(bases, i);
756 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000757 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000759 if (PyType_IsSubtype(tmptype, winner)) {
760 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761 continue;
762 }
763 PyErr_SetString(PyExc_TypeError,
764 "metatype conflict among bases");
765 return NULL;
766 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000767 if (winner != metatype) {
768 if (winner->tp_new != type_new) /* Pass it to the winner */
769 return winner->tp_new(winner, args, kwds);
770 metatype = winner;
771 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772
773 /* Adjust for empty tuple bases */
774 if (nbases == 0) {
775 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
776 if (bases == NULL)
777 return NULL;
778 nbases = 1;
779 }
780 else
781 Py_INCREF(bases);
782
783 /* XXX From here until type is allocated, "return NULL" leaks bases! */
784
785 /* Calculate best base, and check that all bases are type objects */
786 base = best_base(bases);
787 if (base == NULL)
788 return NULL;
789 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
790 PyErr_Format(PyExc_TypeError,
791 "type '%.100s' is not an acceptable base type",
792 base->tp_name);
793 return NULL;
794 }
795
Guido van Rossum1a493502001-08-17 16:47:50 +0000796 /* Should this be a dynamic class (i.e. modifiable __dict__)?
797 Look in two places for a variable named __dynamic__:
798 1) in the class dict
799 2) in the module dict (globals)
800 The first variable that is an int >= 0 is used.
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000801 Otherwise, the default is dynamic. */
Guido van Rossum1a493502001-08-17 16:47:50 +0000802 dynamic = -1; /* Not yet determined */
803 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000804 tmp = PyDict_GetItemString(dict, "__dynamic__");
805 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000806 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000808 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000810 if (dynamic < 0) {
811 /* Look in the module globals */
812 tmp = PyEval_GetGlobals();
813 if (tmp != NULL) {
814 tmp = PyDict_GetItemString(tmp, "__dynamic__");
815 if (tmp != NULL) {
816 dynamic = PyInt_AsLong(tmp);
817 if (dynamic < 0)
818 PyErr_Clear();
819 }
820 }
821 }
822 if (dynamic < 0) {
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000823 /* Default to dynamic */
824 dynamic = 1;
825
Tim Peters6d6c1a32001-08-02 04:15:00 +0000826 }
827
828 /* Check for a __slots__ sequence variable in dict, and count it */
829 slots = PyDict_GetItemString(dict, "__slots__");
830 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000831 add_dict = 0;
832 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000833 if (slots != NULL) {
834 /* Make it into a tuple */
835 if (PyString_Check(slots))
836 slots = Py_BuildValue("(O)", slots);
837 else
838 slots = PySequence_Tuple(slots);
839 if (slots == NULL)
840 return NULL;
841 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000842 if (nslots > 0 && base->tp_itemsize != 0) {
843 PyErr_Format(PyExc_TypeError,
844 "nonempty __slots__ "
845 "not supported for subtype of '%s'",
846 base->tp_name);
847 return NULL;
848 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000849 for (i = 0; i < nslots; i++) {
850 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
851 PyErr_SetString(PyExc_TypeError,
852 "__slots__ must be a sequence of strings");
853 Py_DECREF(slots);
854 return NULL;
855 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000856 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857 }
858 }
859 if (slots == NULL && base->tp_dictoffset == 0 &&
860 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000861 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000862 add_dict++;
863 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000864 if (slots == NULL && base->tp_weaklistoffset == 0 &&
865 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000866 nslots++;
867 add_weak++;
868 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869
870 /* XXX From here until type is safely allocated,
871 "return NULL" may leak slots! */
872
873 /* Allocate the type object */
874 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
875 if (type == NULL)
876 return NULL;
877
878 /* Keep name and slots alive in the extended type object */
879 et = (etype *)type;
880 Py_INCREF(name);
881 et->name = name;
882 et->slots = slots;
883
Guido van Rossumdc91b992001-08-08 22:26:22 +0000884 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000885 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
886 Py_TPFLAGS_BASETYPE;
887 if (dynamic)
888 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000889 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
890 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000891
892 /* It's a new-style number unless it specifically inherits any
893 old-style numeric behavior */
894 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
895 (base->tp_as_number == NULL))
896 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
897
898 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000899 type->tp_as_number = &et->as_number;
900 type->tp_as_sequence = &et->as_sequence;
901 type->tp_as_mapping = &et->as_mapping;
902 type->tp_as_buffer = &et->as_buffer;
903 type->tp_name = PyString_AS_STRING(name);
904
905 /* Set tp_base and tp_bases */
906 type->tp_bases = bases;
907 Py_INCREF(base);
908 type->tp_base = base;
909
910 /* Initialize tp_defined from passed-in dict */
911 type->tp_defined = dict = PyDict_Copy(dict);
912 if (dict == NULL) {
913 Py_DECREF(type);
914 return NULL;
915 }
916
Guido van Rossumc3542212001-08-16 09:18:56 +0000917 /* Set __module__ in the dict */
918 if (PyDict_GetItemString(dict, "__module__") == NULL) {
919 tmp = PyEval_GetGlobals();
920 if (tmp != NULL) {
921 tmp = PyDict_GetItemString(tmp, "__name__");
922 if (tmp != NULL) {
923 if (PyDict_SetItemString(dict, "__module__",
924 tmp) < 0)
925 return NULL;
926 }
927 }
928 }
929
Tim Peters2f93e282001-10-04 05:27:00 +0000930 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
931 and is a string (tp_doc is a char* -- can't copy a general object
932 into it).
933 XXX What if it's a Unicode string? Don't know -- this ignores it.
934 */
935 {
936 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
937 if (doc != NULL && PyString_Check(doc)) {
938 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000939 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000940 if (type->tp_doc == NULL) {
941 Py_DECREF(type);
942 return NULL;
943 }
944 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
945 }
946 }
947
Tim Peters6d6c1a32001-08-02 04:15:00 +0000948 /* Special-case __new__: if it's a plain function,
949 make it a static function */
950 tmp = PyDict_GetItemString(dict, "__new__");
951 if (tmp != NULL && PyFunction_Check(tmp)) {
952 tmp = PyStaticMethod_New(tmp);
953 if (tmp == NULL) {
954 Py_DECREF(type);
955 return NULL;
956 }
957 PyDict_SetItemString(dict, "__new__", tmp);
958 Py_DECREF(tmp);
959 }
960
961 /* Add descriptors for custom slots from __slots__, or for __dict__ */
962 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000963 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000964 if (slots != NULL) {
965 for (i = 0; i < nslots; i++, mp++) {
966 mp->name = PyString_AS_STRING(
967 PyTuple_GET_ITEM(slots, i));
968 mp->type = T_OBJECT;
969 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000970 if (base->tp_weaklistoffset == 0 &&
971 strcmp(mp->name, "__weakref__") == 0)
972 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000973 slotoffset += sizeof(PyObject *);
974 }
975 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000976 else {
977 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000978 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000979 type->tp_dictoffset =
980 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000981 else
982 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000983 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000984 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000985 }
986 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000987 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000988 type->tp_weaklistoffset = slotoffset;
989 mp->name = "__weakref__";
990 mp->type = T_OBJECT;
991 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000992 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000993 mp++;
994 slotoffset += sizeof(PyObject *);
995 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000996 }
997 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000998 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000999 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000
1001 /* Special case some slots */
1002 if (type->tp_dictoffset != 0 || nslots > 0) {
1003 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1004 type->tp_getattro = PyObject_GenericGetAttr;
1005 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1006 type->tp_setattro = PyObject_GenericSetAttr;
1007 }
1008 type->tp_dealloc = subtype_dealloc;
1009
Guido van Rossum9475a232001-10-05 20:51:39 +00001010 /* Enable GC unless there are really no instance variables possible */
1011 if (!(type->tp_basicsize == sizeof(PyObject) &&
1012 type->tp_itemsize == 0))
1013 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1014
Tim Peters6d6c1a32001-08-02 04:15:00 +00001015 /* Always override allocation strategy to use regular heap */
1016 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001017 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1018 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001019 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001020 type->tp_clear = base->tp_clear;
1021 }
1022 else
1023 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024
1025 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001026 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027 Py_DECREF(type);
1028 return NULL;
1029 }
1030
1031 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +00001032 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
1033 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001034
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 return (PyObject *)type;
1036}
1037
1038/* Internal API to look for a name through the MRO.
1039 This returns a borrowed reference, and doesn't set an exception! */
1040PyObject *
1041_PyType_Lookup(PyTypeObject *type, PyObject *name)
1042{
1043 int i, n;
1044 PyObject *mro, *res, *dict;
1045
1046 /* For static types, look in tp_dict */
1047 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
1048 dict = type->tp_dict;
1049 assert(dict && PyDict_Check(dict));
1050 return PyDict_GetItem(dict, name);
1051 }
1052
1053 /* For dynamic types, look in tp_defined of types in MRO */
1054 mro = type->tp_mro;
1055 assert(PyTuple_Check(mro));
1056 n = PyTuple_GET_SIZE(mro);
1057 for (i = 0; i < n; i++) {
1058 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1059 assert(PyType_Check(type));
1060 dict = type->tp_defined;
1061 assert(dict && PyDict_Check(dict));
1062 res = PyDict_GetItem(dict, name);
1063 if (res != NULL)
1064 return res;
1065 }
1066 return NULL;
1067}
1068
1069/* This is similar to PyObject_GenericGetAttr(),
1070 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1071static PyObject *
1072type_getattro(PyTypeObject *type, PyObject *name)
1073{
1074 PyTypeObject *metatype = type->ob_type;
1075 PyObject *descr, *res;
1076 descrgetfunc f;
1077
1078 /* Initialize this type (we'll assume the metatype is initialized) */
1079 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001080 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081 return NULL;
1082 }
1083
1084 /* Get a descriptor from the metatype */
1085 descr = _PyType_Lookup(metatype, name);
1086 f = NULL;
1087 if (descr != NULL) {
1088 f = descr->ob_type->tp_descr_get;
1089 if (f != NULL && PyDescr_IsData(descr))
1090 return f(descr,
1091 (PyObject *)type, (PyObject *)metatype);
1092 }
1093
1094 /* Look in tp_defined of this type and its bases */
1095 res = _PyType_Lookup(type, name);
1096 if (res != NULL) {
1097 f = res->ob_type->tp_descr_get;
1098 if (f != NULL)
1099 return f(res, (PyObject *)NULL, (PyObject *)type);
1100 Py_INCREF(res);
1101 return res;
1102 }
1103
1104 /* Use the descriptor from the metatype */
1105 if (f != NULL) {
1106 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1107 return res;
1108 }
1109 if (descr != NULL) {
1110 Py_INCREF(descr);
1111 return descr;
1112 }
1113
1114 /* Give up */
1115 PyErr_Format(PyExc_AttributeError,
1116 "type object '%.50s' has no attribute '%.400s'",
1117 type->tp_name, PyString_AS_STRING(name));
1118 return NULL;
1119}
1120
1121static int
1122type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1123{
1124 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1125 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1126 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1127 return -1;
1128}
1129
1130static void
1131type_dealloc(PyTypeObject *type)
1132{
1133 etype *et;
1134
1135 /* Assert this is a heap-allocated type object */
1136 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001137 _PyObject_GC_UNTRACK(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138 et = (etype *)type;
1139 Py_XDECREF(type->tp_base);
1140 Py_XDECREF(type->tp_dict);
1141 Py_XDECREF(type->tp_bases);
1142 Py_XDECREF(type->tp_mro);
1143 Py_XDECREF(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144 Py_XDECREF(et->name);
1145 Py_XDECREF(et->slots);
1146 type->ob_type->tp_free((PyObject *)type);
1147}
1148
1149static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001150 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 "mro() -> list\nreturn a type's method resolution order"},
1152 {0}
1153};
1154
1155static char type_doc[] =
1156"type(object) -> the object's type\n"
1157"type(name, bases, dict) -> a new type";
1158
Guido van Rossum048eb752001-10-02 21:24:57 +00001159static int
1160type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1161{
1162 etype *et;
1163 int err;
1164
1165 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1166 return 0;
1167
1168 et = (etype *)type;
1169
1170#define VISIT(SLOT) \
1171 if (SLOT) { \
1172 err = visit((PyObject *)(SLOT), arg); \
1173 if (err) \
1174 return err; \
1175 }
1176
1177 VISIT(type->tp_dict);
1178 VISIT(type->tp_defined);
1179 VISIT(type->tp_mro);
1180 VISIT(type->tp_bases);
1181 VISIT(type->tp_base);
1182 VISIT(et->slots);
1183
1184#undef VISIT
1185
1186 return 0;
1187}
1188
1189static int
1190type_clear(PyTypeObject *type)
1191{
1192 etype *et;
1193 PyObject *tmp;
1194
1195 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1196 return 0;
1197
1198 et = (etype *)type;
1199
1200#define CLEAR(SLOT) \
1201 if (SLOT) { \
1202 tmp = (PyObject *)(SLOT); \
1203 SLOT = NULL; \
1204 Py_DECREF(tmp); \
1205 }
1206
1207 CLEAR(type->tp_dict);
1208 CLEAR(type->tp_defined);
1209 CLEAR(type->tp_mro);
1210 CLEAR(type->tp_bases);
1211 CLEAR(type->tp_base);
1212 CLEAR(et->slots);
1213
Tim Peters2f93e282001-10-04 05:27:00 +00001214 if (type->tp_doc != NULL) {
1215 PyObject_FREE(type->tp_doc);
1216 type->tp_doc = NULL;
1217 }
1218
Guido van Rossum048eb752001-10-02 21:24:57 +00001219#undef CLEAR
1220
1221 return 0;
1222}
1223
1224static int
1225type_is_gc(PyTypeObject *type)
1226{
1227 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1228}
1229
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001230PyTypeObject PyType_Type = {
1231 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 0, /* ob_size */
1233 "type", /* tp_name */
1234 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001235 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 (destructor)type_dealloc, /* tp_dealloc */
1237 0, /* tp_print */
1238 0, /* tp_getattr */
1239 0, /* tp_setattr */
1240 type_compare, /* tp_compare */
1241 (reprfunc)type_repr, /* tp_repr */
1242 0, /* tp_as_number */
1243 0, /* tp_as_sequence */
1244 0, /* tp_as_mapping */
1245 (hashfunc)_Py_HashPointer, /* tp_hash */
1246 (ternaryfunc)type_call, /* tp_call */
1247 0, /* tp_str */
1248 (getattrofunc)type_getattro, /* tp_getattro */
1249 (setattrofunc)type_setattro, /* tp_setattro */
1250 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001251 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1252 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001254 (traverseproc)type_traverse, /* tp_traverse */
1255 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001256 0, /* tp_richcompare */
1257 0, /* tp_weaklistoffset */
1258 0, /* tp_iter */
1259 0, /* tp_iternext */
1260 type_methods, /* tp_methods */
1261 type_members, /* tp_members */
1262 type_getsets, /* tp_getset */
1263 0, /* tp_base */
1264 0, /* tp_dict */
1265 0, /* tp_descr_get */
1266 0, /* tp_descr_set */
1267 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1268 0, /* tp_init */
1269 0, /* tp_alloc */
1270 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001271 _PyObject_GC_Del, /* tp_free */
1272 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001273};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274
1275
1276/* The base type of all types (eventually)... except itself. */
1277
1278static int
1279object_init(PyObject *self, PyObject *args, PyObject *kwds)
1280{
1281 return 0;
1282}
1283
1284static void
1285object_dealloc(PyObject *self)
1286{
1287 self->ob_type->tp_free(self);
1288}
1289
Guido van Rossum8e248182001-08-12 05:17:56 +00001290static PyObject *
1291object_repr(PyObject *self)
1292{
Guido van Rossum76e69632001-08-16 18:52:43 +00001293 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001294 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001295
Guido van Rossum76e69632001-08-16 18:52:43 +00001296 type = self->ob_type;
1297 mod = type_module(type, NULL);
1298 if (mod == NULL)
1299 PyErr_Clear();
1300 else if (!PyString_Check(mod)) {
1301 Py_DECREF(mod);
1302 mod = NULL;
1303 }
1304 name = type_name(type, NULL);
1305 if (name == NULL)
1306 return NULL;
1307 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001308 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001309 PyString_AS_STRING(mod),
1310 PyString_AS_STRING(name),
1311 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001312 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001313 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001314 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001315 Py_XDECREF(mod);
1316 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001317 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001318}
1319
Guido van Rossumb8f63662001-08-15 23:57:02 +00001320static PyObject *
1321object_str(PyObject *self)
1322{
1323 unaryfunc f;
1324
1325 f = self->ob_type->tp_repr;
1326 if (f == NULL)
1327 f = object_repr;
1328 return f(self);
1329}
1330
Guido van Rossum8e248182001-08-12 05:17:56 +00001331static long
1332object_hash(PyObject *self)
1333{
1334 return _Py_HashPointer(self);
1335}
Guido van Rossum8e248182001-08-12 05:17:56 +00001336
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001337static PyObject *
1338object_get_class(PyObject *self, void *closure)
1339{
1340 Py_INCREF(self->ob_type);
1341 return (PyObject *)(self->ob_type);
1342}
1343
1344static int
1345equiv_structs(PyTypeObject *a, PyTypeObject *b)
1346{
1347 return a == b ||
1348 (a != NULL &&
1349 b != NULL &&
1350 a->tp_basicsize == b->tp_basicsize &&
1351 a->tp_itemsize == b->tp_itemsize &&
1352 a->tp_dictoffset == b->tp_dictoffset &&
1353 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1354 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1355 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1356}
1357
1358static int
1359same_slots_added(PyTypeObject *a, PyTypeObject *b)
1360{
1361 PyTypeObject *base = a->tp_base;
1362 int size;
1363
1364 if (base != b->tp_base)
1365 return 0;
1366 if (equiv_structs(a, base) && equiv_structs(b, base))
1367 return 1;
1368 size = base->tp_basicsize;
1369 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1370 size += sizeof(PyObject *);
1371 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1372 size += sizeof(PyObject *);
1373 return size == a->tp_basicsize && size == b->tp_basicsize;
1374}
1375
1376static int
1377object_set_class(PyObject *self, PyObject *value, void *closure)
1378{
1379 PyTypeObject *old = self->ob_type;
1380 PyTypeObject *new, *newbase, *oldbase;
1381
1382 if (!PyType_Check(value)) {
1383 PyErr_Format(PyExc_TypeError,
1384 "__class__ must be set to new-style class, not '%s' object",
1385 value->ob_type->tp_name);
1386 return -1;
1387 }
1388 new = (PyTypeObject *)value;
1389 newbase = new;
1390 oldbase = old;
1391 while (equiv_structs(newbase, newbase->tp_base))
1392 newbase = newbase->tp_base;
1393 while (equiv_structs(oldbase, oldbase->tp_base))
1394 oldbase = oldbase->tp_base;
1395 if (newbase != oldbase &&
1396 (newbase->tp_base != oldbase->tp_base ||
1397 !same_slots_added(newbase, oldbase))) {
1398 PyErr_Format(PyExc_TypeError,
1399 "__class__ assignment: "
1400 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001401 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001402 old->tp_name);
1403 return -1;
1404 }
1405 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1406 Py_INCREF(new);
1407 }
1408 self->ob_type = new;
1409 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1410 Py_DECREF(old);
1411 }
1412 return 0;
1413}
1414
1415static PyGetSetDef object_getsets[] = {
1416 {"__class__", object_get_class, object_set_class,
1417 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 {0}
1419};
1420
Guido van Rossum3926a632001-09-25 16:25:58 +00001421static PyObject *
1422object_reduce(PyObject *self, PyObject *args)
1423{
1424 /* Call copy_reg._reduce(self) */
1425 static PyObject *copy_reg_str;
1426 PyObject *copy_reg, *res;
1427
1428 if (!copy_reg_str) {
1429 copy_reg_str = PyString_InternFromString("copy_reg");
1430 if (copy_reg_str == NULL)
1431 return NULL;
1432 }
1433 copy_reg = PyImport_Import(copy_reg_str);
1434 if (!copy_reg)
1435 return NULL;
1436 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1437 Py_DECREF(copy_reg);
1438 return res;
1439}
1440
1441static PyMethodDef object_methods[] = {
1442 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1443 {0}
1444};
1445
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446PyTypeObject PyBaseObject_Type = {
1447 PyObject_HEAD_INIT(&PyType_Type)
1448 0, /* ob_size */
1449 "object", /* tp_name */
1450 sizeof(PyObject), /* tp_basicsize */
1451 0, /* tp_itemsize */
1452 (destructor)object_dealloc, /* tp_dealloc */
1453 0, /* tp_print */
1454 0, /* tp_getattr */
1455 0, /* tp_setattr */
1456 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001457 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 0, /* tp_as_number */
1459 0, /* tp_as_sequence */
1460 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001461 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001462 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001463 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001465 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466 0, /* tp_as_buffer */
1467 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1468 "The most base type", /* tp_doc */
1469 0, /* tp_traverse */
1470 0, /* tp_clear */
1471 0, /* tp_richcompare */
1472 0, /* tp_weaklistoffset */
1473 0, /* tp_iter */
1474 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001475 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001476 0, /* tp_members */
1477 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478 0, /* tp_base */
1479 0, /* tp_dict */
1480 0, /* tp_descr_get */
1481 0, /* tp_descr_set */
1482 0, /* tp_dictoffset */
1483 object_init, /* tp_init */
1484 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001485 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001486 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487};
1488
1489
1490/* Initialize the __dict__ in a type object */
1491
1492static int
1493add_methods(PyTypeObject *type, PyMethodDef *meth)
1494{
1495 PyObject *dict = type->tp_defined;
1496
1497 for (; meth->ml_name != NULL; meth++) {
1498 PyObject *descr;
1499 if (PyDict_GetItemString(dict, meth->ml_name))
1500 continue;
1501 descr = PyDescr_NewMethod(type, meth);
1502 if (descr == NULL)
1503 return -1;
1504 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1505 return -1;
1506 Py_DECREF(descr);
1507 }
1508 return 0;
1509}
1510
1511static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001512add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001513{
1514 PyObject *dict = type->tp_defined;
1515
1516 for (; memb->name != NULL; memb++) {
1517 PyObject *descr;
1518 if (PyDict_GetItemString(dict, memb->name))
1519 continue;
1520 descr = PyDescr_NewMember(type, memb);
1521 if (descr == NULL)
1522 return -1;
1523 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1524 return -1;
1525 Py_DECREF(descr);
1526 }
1527 return 0;
1528}
1529
1530static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001531add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532{
1533 PyObject *dict = type->tp_defined;
1534
1535 for (; gsp->name != NULL; gsp++) {
1536 PyObject *descr;
1537 if (PyDict_GetItemString(dict, gsp->name))
1538 continue;
1539 descr = PyDescr_NewGetSet(type, gsp);
1540
1541 if (descr == NULL)
1542 return -1;
1543 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1544 return -1;
1545 Py_DECREF(descr);
1546 }
1547 return 0;
1548}
1549
Guido van Rossum13d52f02001-08-10 21:24:08 +00001550static void
1551inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552{
1553 int oldsize, newsize;
1554
Guido van Rossum13d52f02001-08-10 21:24:08 +00001555 /* Special flag magic */
1556 if (!type->tp_as_buffer && base->tp_as_buffer) {
1557 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1558 type->tp_flags |=
1559 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1560 }
1561 if (!type->tp_as_sequence && base->tp_as_sequence) {
1562 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1563 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1564 }
1565 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1566 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1567 if ((!type->tp_as_number && base->tp_as_number) ||
1568 (!type->tp_as_sequence && base->tp_as_sequence)) {
1569 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1570 if (!type->tp_as_number && !type->tp_as_sequence) {
1571 type->tp_flags |= base->tp_flags &
1572 Py_TPFLAGS_HAVE_INPLACEOPS;
1573 }
1574 }
1575 /* Wow */
1576 }
1577 if (!type->tp_as_number && base->tp_as_number) {
1578 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1579 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1580 }
1581
1582 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001583 oldsize = base->tp_basicsize;
1584 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1585 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1586 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001587 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1588 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001589 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001590 if (type->tp_traverse == NULL)
1591 type->tp_traverse = base->tp_traverse;
1592 if (type->tp_clear == NULL)
1593 type->tp_clear = base->tp_clear;
1594 }
1595 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1596 if (base != &PyBaseObject_Type ||
1597 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1598 if (type->tp_new == NULL)
1599 type->tp_new = base->tp_new;
1600 }
1601 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001602 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001603
1604 /* Copy other non-function slots */
1605
1606#undef COPYVAL
1607#define COPYVAL(SLOT) \
1608 if (type->SLOT == 0) type->SLOT = base->SLOT
1609
1610 COPYVAL(tp_itemsize);
1611 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1612 COPYVAL(tp_weaklistoffset);
1613 }
1614 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1615 COPYVAL(tp_dictoffset);
1616 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001617}
1618
1619static void
1620inherit_slots(PyTypeObject *type, PyTypeObject *base)
1621{
1622 PyTypeObject *basebase;
1623
1624#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625#undef COPYSLOT
1626#undef COPYNUM
1627#undef COPYSEQ
1628#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001629
1630#define SLOTDEFINED(SLOT) \
1631 (base->SLOT != 0 && \
1632 (basebase == NULL || base->SLOT != basebase->SLOT))
1633
Tim Peters6d6c1a32001-08-02 04:15:00 +00001634#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001635 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636
1637#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1638#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1639#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1640
Guido van Rossum13d52f02001-08-10 21:24:08 +00001641 /* This won't inherit indirect slots (from tp_as_number etc.)
1642 if type doesn't provide the space. */
1643
1644 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1645 basebase = base->tp_base;
1646 if (basebase->tp_as_number == NULL)
1647 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001648 COPYNUM(nb_add);
1649 COPYNUM(nb_subtract);
1650 COPYNUM(nb_multiply);
1651 COPYNUM(nb_divide);
1652 COPYNUM(nb_remainder);
1653 COPYNUM(nb_divmod);
1654 COPYNUM(nb_power);
1655 COPYNUM(nb_negative);
1656 COPYNUM(nb_positive);
1657 COPYNUM(nb_absolute);
1658 COPYNUM(nb_nonzero);
1659 COPYNUM(nb_invert);
1660 COPYNUM(nb_lshift);
1661 COPYNUM(nb_rshift);
1662 COPYNUM(nb_and);
1663 COPYNUM(nb_xor);
1664 COPYNUM(nb_or);
1665 COPYNUM(nb_coerce);
1666 COPYNUM(nb_int);
1667 COPYNUM(nb_long);
1668 COPYNUM(nb_float);
1669 COPYNUM(nb_oct);
1670 COPYNUM(nb_hex);
1671 COPYNUM(nb_inplace_add);
1672 COPYNUM(nb_inplace_subtract);
1673 COPYNUM(nb_inplace_multiply);
1674 COPYNUM(nb_inplace_divide);
1675 COPYNUM(nb_inplace_remainder);
1676 COPYNUM(nb_inplace_power);
1677 COPYNUM(nb_inplace_lshift);
1678 COPYNUM(nb_inplace_rshift);
1679 COPYNUM(nb_inplace_and);
1680 COPYNUM(nb_inplace_xor);
1681 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001682 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1683 COPYNUM(nb_true_divide);
1684 COPYNUM(nb_floor_divide);
1685 COPYNUM(nb_inplace_true_divide);
1686 COPYNUM(nb_inplace_floor_divide);
1687 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 }
1689
Guido van Rossum13d52f02001-08-10 21:24:08 +00001690 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1691 basebase = base->tp_base;
1692 if (basebase->tp_as_sequence == NULL)
1693 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 COPYSEQ(sq_length);
1695 COPYSEQ(sq_concat);
1696 COPYSEQ(sq_repeat);
1697 COPYSEQ(sq_item);
1698 COPYSEQ(sq_slice);
1699 COPYSEQ(sq_ass_item);
1700 COPYSEQ(sq_ass_slice);
1701 COPYSEQ(sq_contains);
1702 COPYSEQ(sq_inplace_concat);
1703 COPYSEQ(sq_inplace_repeat);
1704 }
1705
Guido van Rossum13d52f02001-08-10 21:24:08 +00001706 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1707 basebase = base->tp_base;
1708 if (basebase->tp_as_mapping == NULL)
1709 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710 COPYMAP(mp_length);
1711 COPYMAP(mp_subscript);
1712 COPYMAP(mp_ass_subscript);
1713 }
1714
Guido van Rossum13d52f02001-08-10 21:24:08 +00001715 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717 COPYSLOT(tp_dealloc);
1718 COPYSLOT(tp_print);
1719 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1720 type->tp_getattr = base->tp_getattr;
1721 type->tp_getattro = base->tp_getattro;
1722 }
1723 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1724 type->tp_setattr = base->tp_setattr;
1725 type->tp_setattro = base->tp_setattro;
1726 }
1727 /* tp_compare see tp_richcompare */
1728 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001729 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 COPYSLOT(tp_call);
1731 COPYSLOT(tp_str);
1732 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001734 if (type->tp_compare == NULL &&
1735 type->tp_richcompare == NULL &&
1736 type->tp_hash == NULL)
1737 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001738 type->tp_compare = base->tp_compare;
1739 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001740 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741 }
1742 }
1743 else {
1744 COPYSLOT(tp_compare);
1745 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001746 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1747 COPYSLOT(tp_iter);
1748 COPYSLOT(tp_iternext);
1749 }
1750 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1751 COPYSLOT(tp_descr_get);
1752 COPYSLOT(tp_descr_set);
1753 COPYSLOT(tp_dictoffset);
1754 COPYSLOT(tp_init);
1755 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756 COPYSLOT(tp_free);
1757 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758}
1759
Guido van Rossum13d52f02001-08-10 21:24:08 +00001760staticforward int add_operators(PyTypeObject *);
1761
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001763PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764{
1765 PyObject *dict, *bases, *x;
1766 PyTypeObject *base;
1767 int i, n;
1768
Guido van Rossumd614f972001-08-10 17:39:49 +00001769 if (type->tp_flags & Py_TPFLAGS_READY) {
1770 assert(type->tp_dict != NULL);
1771 return 0;
1772 }
1773 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1774 assert(type->tp_dict == NULL);
1775
1776 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777
1778 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1779 base = type->tp_base;
1780 if (base == NULL && type != &PyBaseObject_Type)
1781 base = type->tp_base = &PyBaseObject_Type;
1782
1783 /* Initialize tp_bases */
1784 bases = type->tp_bases;
1785 if (bases == NULL) {
1786 if (base == NULL)
1787 bases = PyTuple_New(0);
1788 else
1789 bases = Py_BuildValue("(O)", base);
1790 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001791 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792 type->tp_bases = bases;
1793 }
1794
1795 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001796 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001797 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001798 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 }
1800
1801 /* Initialize tp_defined */
1802 dict = type->tp_defined;
1803 if (dict == NULL) {
1804 dict = PyDict_New();
1805 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001806 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807 type->tp_defined = dict;
1808 }
1809
1810 /* Add type-specific descriptors to tp_defined */
1811 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001812 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001813 if (type->tp_methods != NULL) {
1814 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001815 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816 }
1817 if (type->tp_members != NULL) {
1818 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001819 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 }
1821 if (type->tp_getset != NULL) {
1822 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001823 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824 }
1825
1826 /* Temporarily make tp_dict the same object as tp_defined.
1827 (This is needed to call mro(), and can stay this way for
1828 dynamic types). */
1829 Py_INCREF(type->tp_defined);
1830 type->tp_dict = type->tp_defined;
1831
1832 /* Calculate method resolution order */
1833 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001834 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001835 }
1836
Guido van Rossum13d52f02001-08-10 21:24:08 +00001837 /* Inherit special flags from dominant base */
1838 if (type->tp_base != NULL)
1839 inherit_special(type, type->tp_base);
1840
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001842 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001843 /* For a dynamic type, all slots are overridden */
1844 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001845 }
1846 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001848 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001849 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001850 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001852 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 bases = type->tp_mro;
1854 assert(bases != NULL);
1855 assert(PyTuple_Check(bases));
1856 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001857 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1859 assert(PyType_Check(base));
1860 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001861 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001862 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001863 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001864 }
1865 }
1866
Guido van Rossum13d52f02001-08-10 21:24:08 +00001867 /* Some more special stuff */
1868 base = type->tp_base;
1869 if (base != NULL) {
1870 if (type->tp_as_number == NULL)
1871 type->tp_as_number = base->tp_as_number;
1872 if (type->tp_as_sequence == NULL)
1873 type->tp_as_sequence = base->tp_as_sequence;
1874 if (type->tp_as_mapping == NULL)
1875 type->tp_as_mapping = base->tp_as_mapping;
1876 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877
Guido van Rossum13d52f02001-08-10 21:24:08 +00001878 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001879 assert(type->tp_dict != NULL);
1880 type->tp_flags =
1881 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001883
1884 error:
1885 type->tp_flags &= ~Py_TPFLAGS_READYING;
1886 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887}
1888
1889
1890/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1891
1892/* There's a wrapper *function* for each distinct function typedef used
1893 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1894 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1895 Most tables have only one entry; the tables for binary operators have two
1896 entries, one regular and one with reversed arguments. */
1897
1898static PyObject *
1899wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1900{
1901 inquiry func = (inquiry)wrapped;
1902 int res;
1903
1904 if (!PyArg_ParseTuple(args, ""))
1905 return NULL;
1906 res = (*func)(self);
1907 if (res == -1 && PyErr_Occurred())
1908 return NULL;
1909 return PyInt_FromLong((long)res);
1910}
1911
1912static struct wrapperbase tab_len[] = {
1913 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1914 {0}
1915};
1916
1917static PyObject *
1918wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1919{
1920 binaryfunc func = (binaryfunc)wrapped;
1921 PyObject *other;
1922
1923 if (!PyArg_ParseTuple(args, "O", &other))
1924 return NULL;
1925 return (*func)(self, other);
1926}
1927
1928static PyObject *
1929wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1930{
1931 binaryfunc func = (binaryfunc)wrapped;
1932 PyObject *other;
1933
1934 if (!PyArg_ParseTuple(args, "O", &other))
1935 return NULL;
1936 return (*func)(other, self);
1937}
1938
1939#undef BINARY
1940#define BINARY(NAME, OP) \
1941static struct wrapperbase tab_##NAME[] = { \
1942 {"__" #NAME "__", \
1943 (wrapperfunc)wrap_binaryfunc, \
1944 "x.__" #NAME "__(y) <==> " #OP}, \
1945 {"__r" #NAME "__", \
1946 (wrapperfunc)wrap_binaryfunc_r, \
1947 "y.__r" #NAME "__(x) <==> " #OP}, \
1948 {0} \
1949}
1950
1951BINARY(add, "x+y");
1952BINARY(sub, "x-y");
1953BINARY(mul, "x*y");
1954BINARY(div, "x/y");
1955BINARY(mod, "x%y");
1956BINARY(divmod, "divmod(x,y)");
1957BINARY(lshift, "x<<y");
1958BINARY(rshift, "x>>y");
1959BINARY(and, "x&y");
1960BINARY(xor, "x^y");
1961BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001962
1963static PyObject *
1964wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1965{
1966 coercion func = (coercion)wrapped;
1967 PyObject *other, *res;
1968 int ok;
1969
1970 if (!PyArg_ParseTuple(args, "O", &other))
1971 return NULL;
1972 ok = func(&self, &other);
1973 if (ok < 0)
1974 return NULL;
1975 if (ok > 0) {
1976 Py_INCREF(Py_NotImplemented);
1977 return Py_NotImplemented;
1978 }
1979 res = PyTuple_New(2);
1980 if (res == NULL) {
1981 Py_DECREF(self);
1982 Py_DECREF(other);
1983 return NULL;
1984 }
1985 PyTuple_SET_ITEM(res, 0, self);
1986 PyTuple_SET_ITEM(res, 1, other);
1987 return res;
1988}
1989
1990static struct wrapperbase tab_coerce[] = {
1991 {"__coerce__", (wrapperfunc)wrap_coercefunc,
1992 "x.__coerce__(y) <==> coerce(x, y)"},
1993 {0}
1994};
1995
Guido van Rossum874f15a2001-09-25 21:16:33 +00001996BINARY(floordiv, "x//y");
1997BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001998
1999static PyObject *
2000wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2001{
2002 ternaryfunc func = (ternaryfunc)wrapped;
2003 PyObject *other;
2004 PyObject *third = Py_None;
2005
2006 /* Note: This wrapper only works for __pow__() */
2007
2008 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2009 return NULL;
2010 return (*func)(self, other, third);
2011}
2012
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002013static PyObject *
2014wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2015{
2016 ternaryfunc func = (ternaryfunc)wrapped;
2017 PyObject *other;
2018 PyObject *third = Py_None;
2019
2020 /* Note: This wrapper only works for __pow__() */
2021
2022 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2023 return NULL;
2024 return (*func)(other, self, third);
2025}
2026
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027#undef TERNARY
2028#define TERNARY(NAME, OP) \
2029static struct wrapperbase tab_##NAME[] = { \
2030 {"__" #NAME "__", \
2031 (wrapperfunc)wrap_ternaryfunc, \
2032 "x.__" #NAME "__(y, z) <==> " #OP}, \
2033 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002034 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2036 {0} \
2037}
2038
2039TERNARY(pow, "(x**y) % z");
2040
2041#undef UNARY
2042#define UNARY(NAME, OP) \
2043static struct wrapperbase tab_##NAME[] = { \
2044 {"__" #NAME "__", \
2045 (wrapperfunc)wrap_unaryfunc, \
2046 "x.__" #NAME "__() <==> " #OP}, \
2047 {0} \
2048}
2049
2050static PyObject *
2051wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2052{
2053 unaryfunc func = (unaryfunc)wrapped;
2054
2055 if (!PyArg_ParseTuple(args, ""))
2056 return NULL;
2057 return (*func)(self);
2058}
2059
2060UNARY(neg, "-x");
2061UNARY(pos, "+x");
2062UNARY(abs, "abs(x)");
2063UNARY(nonzero, "x != 0");
2064UNARY(invert, "~x");
2065UNARY(int, "int(x)");
2066UNARY(long, "long(x)");
2067UNARY(float, "float(x)");
2068UNARY(oct, "oct(x)");
2069UNARY(hex, "hex(x)");
2070
2071#undef IBINARY
2072#define IBINARY(NAME, OP) \
2073static struct wrapperbase tab_##NAME[] = { \
2074 {"__" #NAME "__", \
2075 (wrapperfunc)wrap_binaryfunc, \
2076 "x.__" #NAME "__(y) <==> " #OP}, \
2077 {0} \
2078}
2079
2080IBINARY(iadd, "x+=y");
2081IBINARY(isub, "x-=y");
2082IBINARY(imul, "x*=y");
2083IBINARY(idiv, "x/=y");
2084IBINARY(imod, "x%=y");
2085IBINARY(ilshift, "x<<=y");
2086IBINARY(irshift, "x>>=y");
2087IBINARY(iand, "x&=y");
2088IBINARY(ixor, "x^=y");
2089IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002090IBINARY(ifloordiv, "x//=y");
2091IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092
2093#undef ITERNARY
2094#define ITERNARY(NAME, OP) \
2095static struct wrapperbase tab_##NAME[] = { \
2096 {"__" #NAME "__", \
2097 (wrapperfunc)wrap_ternaryfunc, \
2098 "x.__" #NAME "__(y) <==> " #OP}, \
2099 {0} \
2100}
2101
2102ITERNARY(ipow, "x = (x**y) % z");
2103
2104static struct wrapperbase tab_getitem[] = {
2105 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2106 "x.__getitem__(y) <==> x[y]"},
2107 {0}
2108};
2109
2110static PyObject *
2111wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2112{
2113 intargfunc func = (intargfunc)wrapped;
2114 int i;
2115
2116 if (!PyArg_ParseTuple(args, "i", &i))
2117 return NULL;
2118 return (*func)(self, i);
2119}
2120
2121static struct wrapperbase tab_mul_int[] = {
2122 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2123 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2124 {0}
2125};
2126
2127static struct wrapperbase tab_concat[] = {
2128 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2129 {0}
2130};
2131
2132static struct wrapperbase tab_imul_int[] = {
2133 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2134 {0}
2135};
2136
Guido van Rossum5d815f32001-08-17 21:57:47 +00002137static int
2138getindex(PyObject *self, PyObject *arg)
2139{
2140 int i;
2141
2142 i = PyInt_AsLong(arg);
2143 if (i == -1 && PyErr_Occurred())
2144 return -1;
2145 if (i < 0) {
2146 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2147 if (sq && sq->sq_length) {
2148 int n = (*sq->sq_length)(self);
2149 if (n < 0)
2150 return -1;
2151 i += n;
2152 }
2153 }
2154 return i;
2155}
2156
2157static PyObject *
2158wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2159{
2160 intargfunc func = (intargfunc)wrapped;
2161 PyObject *arg;
2162 int i;
2163
Guido van Rossumf4593e02001-10-03 12:09:30 +00002164 if (PyTuple_GET_SIZE(args) == 1) {
2165 arg = PyTuple_GET_ITEM(args, 0);
2166 i = getindex(self, arg);
2167 if (i == -1 && PyErr_Occurred())
2168 return NULL;
2169 return (*func)(self, i);
2170 }
2171 PyArg_ParseTuple(args, "O", &arg);
2172 assert(PyErr_Occurred());
2173 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002174}
2175
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002177 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178 "x.__getitem__(i) <==> x[i]"},
2179 {0}
2180};
2181
2182static PyObject *
2183wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2184{
2185 intintargfunc func = (intintargfunc)wrapped;
2186 int i, j;
2187
2188 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2189 return NULL;
2190 return (*func)(self, i, j);
2191}
2192
2193static struct wrapperbase tab_getslice[] = {
2194 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2195 "x.__getslice__(i, j) <==> x[i:j]"},
2196 {0}
2197};
2198
2199static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002200wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002201{
2202 intobjargproc func = (intobjargproc)wrapped;
2203 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002204 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002205
Guido van Rossum5d815f32001-08-17 21:57:47 +00002206 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2207 return NULL;
2208 i = getindex(self, arg);
2209 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210 return NULL;
2211 res = (*func)(self, i, value);
2212 if (res == -1 && PyErr_Occurred())
2213 return NULL;
2214 Py_INCREF(Py_None);
2215 return Py_None;
2216}
2217
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002218static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002219wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002220{
2221 intobjargproc func = (intobjargproc)wrapped;
2222 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002223 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002224
Guido van Rossum5d815f32001-08-17 21:57:47 +00002225 if (!PyArg_ParseTuple(args, "O", &arg))
2226 return NULL;
2227 i = getindex(self, arg);
2228 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002229 return NULL;
2230 res = (*func)(self, i, NULL);
2231 if (res == -1 && PyErr_Occurred())
2232 return NULL;
2233 Py_INCREF(Py_None);
2234 return Py_None;
2235}
2236
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002238 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002240 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002241 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002242 {0}
2243};
2244
2245static PyObject *
2246wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2247{
2248 intintobjargproc func = (intintobjargproc)wrapped;
2249 int i, j, res;
2250 PyObject *value;
2251
2252 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2253 return NULL;
2254 res = (*func)(self, i, j, value);
2255 if (res == -1 && PyErr_Occurred())
2256 return NULL;
2257 Py_INCREF(Py_None);
2258 return Py_None;
2259}
2260
2261static struct wrapperbase tab_setslice[] = {
2262 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2263 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2264 {0}
2265};
2266
2267/* XXX objobjproc is a misnomer; should be objargpred */
2268static PyObject *
2269wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2270{
2271 objobjproc func = (objobjproc)wrapped;
2272 int res;
2273 PyObject *value;
2274
2275 if (!PyArg_ParseTuple(args, "O", &value))
2276 return NULL;
2277 res = (*func)(self, value);
2278 if (res == -1 && PyErr_Occurred())
2279 return NULL;
2280 return PyInt_FromLong((long)res);
2281}
2282
2283static struct wrapperbase tab_contains[] = {
2284 {"__contains__", (wrapperfunc)wrap_objobjproc,
2285 "x.__contains__(y) <==> y in x"},
2286 {0}
2287};
2288
2289static PyObject *
2290wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2291{
2292 objobjargproc func = (objobjargproc)wrapped;
2293 int res;
2294 PyObject *key, *value;
2295
2296 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2297 return NULL;
2298 res = (*func)(self, key, value);
2299 if (res == -1 && PyErr_Occurred())
2300 return NULL;
2301 Py_INCREF(Py_None);
2302 return Py_None;
2303}
2304
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002305static PyObject *
2306wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2307{
2308 objobjargproc func = (objobjargproc)wrapped;
2309 int res;
2310 PyObject *key;
2311
2312 if (!PyArg_ParseTuple(args, "O", &key))
2313 return NULL;
2314 res = (*func)(self, key, NULL);
2315 if (res == -1 && PyErr_Occurred())
2316 return NULL;
2317 Py_INCREF(Py_None);
2318 return Py_None;
2319}
2320
Tim Peters6d6c1a32001-08-02 04:15:00 +00002321static struct wrapperbase tab_setitem[] = {
2322 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2323 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002324 {"__delitem__", (wrapperfunc)wrap_delitem,
2325 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326 {0}
2327};
2328
2329static PyObject *
2330wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2331{
2332 cmpfunc func = (cmpfunc)wrapped;
2333 int res;
2334 PyObject *other;
2335
2336 if (!PyArg_ParseTuple(args, "O", &other))
2337 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002338 if (other->ob_type->tp_compare != func &&
2339 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002340 PyErr_Format(
2341 PyExc_TypeError,
2342 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2343 self->ob_type->tp_name,
2344 self->ob_type->tp_name,
2345 other->ob_type->tp_name);
2346 return NULL;
2347 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348 res = (*func)(self, other);
2349 if (PyErr_Occurred())
2350 return NULL;
2351 return PyInt_FromLong((long)res);
2352}
2353
2354static struct wrapperbase tab_cmp[] = {
2355 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2356 "x.__cmp__(y) <==> cmp(x,y)"},
2357 {0}
2358};
2359
2360static struct wrapperbase tab_repr[] = {
2361 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2362 "x.__repr__() <==> repr(x)"},
2363 {0}
2364};
2365
2366static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002367 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2368 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369 {0}
2370};
2371
2372static PyObject *
2373wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2374{
2375 setattrofunc func = (setattrofunc)wrapped;
2376 int res;
2377 PyObject *name, *value;
2378
2379 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2380 return NULL;
2381 res = (*func)(self, name, value);
2382 if (res < 0)
2383 return NULL;
2384 Py_INCREF(Py_None);
2385 return Py_None;
2386}
2387
2388static PyObject *
2389wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2390{
2391 setattrofunc func = (setattrofunc)wrapped;
2392 int res;
2393 PyObject *name;
2394
2395 if (!PyArg_ParseTuple(args, "O", &name))
2396 return NULL;
2397 res = (*func)(self, name, NULL);
2398 if (res < 0)
2399 return NULL;
2400 Py_INCREF(Py_None);
2401 return Py_None;
2402}
2403
2404static struct wrapperbase tab_setattr[] = {
2405 {"__setattr__", (wrapperfunc)wrap_setattr,
2406 "x.__setattr__('name', value) <==> x.name = value"},
2407 {"__delattr__", (wrapperfunc)wrap_delattr,
2408 "x.__delattr__('name') <==> del x.name"},
2409 {0}
2410};
2411
2412static PyObject *
2413wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2414{
2415 hashfunc func = (hashfunc)wrapped;
2416 long res;
2417
2418 if (!PyArg_ParseTuple(args, ""))
2419 return NULL;
2420 res = (*func)(self);
2421 if (res == -1 && PyErr_Occurred())
2422 return NULL;
2423 return PyInt_FromLong(res);
2424}
2425
2426static struct wrapperbase tab_hash[] = {
2427 {"__hash__", (wrapperfunc)wrap_hashfunc,
2428 "x.__hash__() <==> hash(x)"},
2429 {0}
2430};
2431
2432static PyObject *
2433wrap_call(PyObject *self, PyObject *args, void *wrapped)
2434{
2435 ternaryfunc func = (ternaryfunc)wrapped;
2436
2437 /* XXX What about keyword arguments? */
2438 return (*func)(self, args, NULL);
2439}
2440
2441static struct wrapperbase tab_call[] = {
2442 {"__call__", (wrapperfunc)wrap_call,
2443 "x.__call__(...) <==> x(...)"},
2444 {0}
2445};
2446
2447static struct wrapperbase tab_str[] = {
2448 {"__str__", (wrapperfunc)wrap_unaryfunc,
2449 "x.__str__() <==> str(x)"},
2450 {0}
2451};
2452
2453static PyObject *
2454wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2455{
2456 richcmpfunc func = (richcmpfunc)wrapped;
2457 PyObject *other;
2458
2459 if (!PyArg_ParseTuple(args, "O", &other))
2460 return NULL;
2461 return (*func)(self, other, op);
2462}
2463
2464#undef RICHCMP_WRAPPER
2465#define RICHCMP_WRAPPER(NAME, OP) \
2466static PyObject * \
2467richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2468{ \
2469 return wrap_richcmpfunc(self, args, wrapped, OP); \
2470}
2471
Jack Jansen8e938b42001-08-08 15:29:49 +00002472RICHCMP_WRAPPER(lt, Py_LT)
2473RICHCMP_WRAPPER(le, Py_LE)
2474RICHCMP_WRAPPER(eq, Py_EQ)
2475RICHCMP_WRAPPER(ne, Py_NE)
2476RICHCMP_WRAPPER(gt, Py_GT)
2477RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478
2479#undef RICHCMP_ENTRY
2480#define RICHCMP_ENTRY(NAME, EXPR) \
2481 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2482 "x.__" #NAME "__(y) <==> " EXPR}
2483
2484static struct wrapperbase tab_richcmp[] = {
2485 RICHCMP_ENTRY(lt, "x<y"),
2486 RICHCMP_ENTRY(le, "x<=y"),
2487 RICHCMP_ENTRY(eq, "x==y"),
2488 RICHCMP_ENTRY(ne, "x!=y"),
2489 RICHCMP_ENTRY(gt, "x>y"),
2490 RICHCMP_ENTRY(ge, "x>=y"),
2491 {0}
2492};
2493
2494static struct wrapperbase tab_iter[] = {
2495 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2496 {0}
2497};
2498
2499static PyObject *
2500wrap_next(PyObject *self, PyObject *args, void *wrapped)
2501{
2502 unaryfunc func = (unaryfunc)wrapped;
2503 PyObject *res;
2504
2505 if (!PyArg_ParseTuple(args, ""))
2506 return NULL;
2507 res = (*func)(self);
2508 if (res == NULL && !PyErr_Occurred())
2509 PyErr_SetNone(PyExc_StopIteration);
2510 return res;
2511}
2512
2513static struct wrapperbase tab_next[] = {
2514 {"next", (wrapperfunc)wrap_next,
2515 "x.next() -> the next value, or raise StopIteration"},
2516 {0}
2517};
2518
2519static PyObject *
2520wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2521{
2522 descrgetfunc func = (descrgetfunc)wrapped;
2523 PyObject *obj;
2524 PyObject *type = NULL;
2525
2526 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2527 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002528 return (*func)(self, obj, type);
2529}
2530
2531static struct wrapperbase tab_descr_get[] = {
2532 {"__get__", (wrapperfunc)wrap_descr_get,
2533 "descr.__get__(obj, type) -> value"},
2534 {0}
2535};
2536
2537static PyObject *
2538wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2539{
2540 descrsetfunc func = (descrsetfunc)wrapped;
2541 PyObject *obj, *value;
2542 int ret;
2543
2544 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2545 return NULL;
2546 ret = (*func)(self, obj, value);
2547 if (ret < 0)
2548 return NULL;
2549 Py_INCREF(Py_None);
2550 return Py_None;
2551}
2552
2553static struct wrapperbase tab_descr_set[] = {
2554 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2555 "descr.__set__(obj, value)"},
2556 {0}
2557};
2558
2559static PyObject *
2560wrap_init(PyObject *self, PyObject *args, void *wrapped)
2561{
2562 initproc func = (initproc)wrapped;
2563
2564 /* XXX What about keyword arguments? */
2565 if (func(self, args, NULL) < 0)
2566 return NULL;
2567 Py_INCREF(Py_None);
2568 return Py_None;
2569}
2570
2571static struct wrapperbase tab_init[] = {
2572 {"__init__", (wrapperfunc)wrap_init,
2573 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002574 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575 {0}
2576};
2577
2578static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002579tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580{
Barry Warsaw60f01882001-08-22 19:24:42 +00002581 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002582 PyObject *arg0, *res;
2583
2584 if (self == NULL || !PyType_Check(self))
2585 Py_FatalError("__new__() called with non-type 'self'");
2586 type = (PyTypeObject *)self;
2587 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002588 PyErr_Format(PyExc_TypeError,
2589 "%s.__new__(): not enough arguments",
2590 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002591 return NULL;
2592 }
2593 arg0 = PyTuple_GET_ITEM(args, 0);
2594 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002595 PyErr_Format(PyExc_TypeError,
2596 "%s.__new__(X): X is not a type object (%s)",
2597 type->tp_name,
2598 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002599 return NULL;
2600 }
2601 subtype = (PyTypeObject *)arg0;
2602 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002603 PyErr_Format(PyExc_TypeError,
2604 "%s.__new__(%s): %s is not a subtype of %s",
2605 type->tp_name,
2606 subtype->tp_name,
2607 subtype->tp_name,
2608 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002609 return NULL;
2610 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002611
2612 /* Check that the use doesn't do something silly and unsafe like
2613 object.__new__(dictionary). To do this, we check that the
2614 most derived base that's not a heap type is this type. */
2615 staticbase = subtype;
2616 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2617 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002618 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002619 PyErr_Format(PyExc_TypeError,
2620 "%s.__new__(%s) is not safe, use %s.__new__()",
2621 type->tp_name,
2622 subtype->tp_name,
2623 staticbase == NULL ? "?" : staticbase->tp_name);
2624 return NULL;
2625 }
2626
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002627 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2628 if (args == NULL)
2629 return NULL;
2630 res = type->tp_new(subtype, args, kwds);
2631 Py_DECREF(args);
2632 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633}
2634
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002635static struct PyMethodDef tp_new_methoddef[] = {
2636 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2637 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002638 {0}
2639};
2640
2641static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002642add_tp_new_wrapper(PyTypeObject *type)
2643{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002644 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002645
Guido van Rossumf040ede2001-08-07 16:40:56 +00002646 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2647 return 0;
2648 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002649 if (func == NULL)
2650 return -1;
2651 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2652}
2653
Guido van Rossum13d52f02001-08-10 21:24:08 +00002654static int
2655add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2656{
2657 PyObject *dict = type->tp_defined;
2658
2659 for (; wraps->name != NULL; wraps++) {
2660 PyObject *descr;
2661 if (PyDict_GetItemString(dict, wraps->name))
2662 continue;
2663 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2664 if (descr == NULL)
2665 return -1;
2666 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2667 return -1;
2668 Py_DECREF(descr);
2669 }
2670 return 0;
2671}
2672
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002673/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002674 dictionary with method descriptors for function slots. For each
2675 function slot (like tp_repr) that's defined in the type, one or
2676 more corresponding descriptors are added in the type's tp_defined
2677 dictionary under the appropriate name (like __repr__). Some
2678 function slots cause more than one descriptor to be added (for
2679 example, the nb_add slot adds both __add__ and __radd__
2680 descriptors) and some function slots compete for the same
2681 descriptor (for example both sq_item and mp_subscript generate a
2682 __getitem__ descriptor). This only adds new descriptors and
2683 doesn't overwrite entries in tp_defined that were previously
2684 defined. The descriptors contain a reference to the C function
2685 they must call, so that it's safe if they are copied into a
2686 subtype's __dict__ and the subtype has a different C function in
2687 its slot -- calling the method defined by the descriptor will call
2688 the C function that was used to create it, rather than the C
2689 function present in the slot when it is called. (This is important
2690 because a subtype may have a C function in the slot that calls the
2691 method from the dictionary, and we want to avoid infinite recursion
2692 here.) */
2693
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002694static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695add_operators(PyTypeObject *type)
2696{
2697 PySequenceMethods *sq;
2698 PyMappingMethods *mp;
2699 PyNumberMethods *nb;
2700
2701#undef ADD
2702#define ADD(SLOT, TABLE) \
2703 if (SLOT) { \
2704 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2705 return -1; \
2706 }
2707
2708 if ((sq = type->tp_as_sequence) != NULL) {
2709 ADD(sq->sq_length, tab_len);
2710 ADD(sq->sq_concat, tab_concat);
2711 ADD(sq->sq_repeat, tab_mul_int);
2712 ADD(sq->sq_item, tab_getitem_int);
2713 ADD(sq->sq_slice, tab_getslice);
2714 ADD(sq->sq_ass_item, tab_setitem_int);
2715 ADD(sq->sq_ass_slice, tab_setslice);
2716 ADD(sq->sq_contains, tab_contains);
2717 ADD(sq->sq_inplace_concat, tab_iadd);
2718 ADD(sq->sq_inplace_repeat, tab_imul_int);
2719 }
2720
2721 if ((mp = type->tp_as_mapping) != NULL) {
2722 if (sq->sq_length == NULL)
2723 ADD(mp->mp_length, tab_len);
2724 ADD(mp->mp_subscript, tab_getitem);
2725 ADD(mp->mp_ass_subscript, tab_setitem);
2726 }
2727
2728 /* We don't support "old-style numbers" because their binary
2729 operators require that both arguments have the same type;
2730 the wrappers here only work for new-style numbers. */
2731 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2732 (nb = type->tp_as_number) != NULL) {
2733 ADD(nb->nb_add, tab_add);
2734 ADD(nb->nb_subtract, tab_sub);
2735 ADD(nb->nb_multiply, tab_mul);
2736 ADD(nb->nb_divide, tab_div);
2737 ADD(nb->nb_remainder, tab_mod);
2738 ADD(nb->nb_divmod, tab_divmod);
2739 ADD(nb->nb_power, tab_pow);
2740 ADD(nb->nb_negative, tab_neg);
2741 ADD(nb->nb_positive, tab_pos);
2742 ADD(nb->nb_absolute, tab_abs);
2743 ADD(nb->nb_nonzero, tab_nonzero);
2744 ADD(nb->nb_invert, tab_invert);
2745 ADD(nb->nb_lshift, tab_lshift);
2746 ADD(nb->nb_rshift, tab_rshift);
2747 ADD(nb->nb_and, tab_and);
2748 ADD(nb->nb_xor, tab_xor);
2749 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002750 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751 ADD(nb->nb_int, tab_int);
2752 ADD(nb->nb_long, tab_long);
2753 ADD(nb->nb_float, tab_float);
2754 ADD(nb->nb_oct, tab_oct);
2755 ADD(nb->nb_hex, tab_hex);
2756 ADD(nb->nb_inplace_add, tab_iadd);
2757 ADD(nb->nb_inplace_subtract, tab_isub);
2758 ADD(nb->nb_inplace_multiply, tab_imul);
2759 ADD(nb->nb_inplace_divide, tab_idiv);
2760 ADD(nb->nb_inplace_remainder, tab_imod);
2761 ADD(nb->nb_inplace_power, tab_ipow);
2762 ADD(nb->nb_inplace_lshift, tab_ilshift);
2763 ADD(nb->nb_inplace_rshift, tab_irshift);
2764 ADD(nb->nb_inplace_and, tab_iand);
2765 ADD(nb->nb_inplace_xor, tab_ixor);
2766 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum874f15a2001-09-25 21:16:33 +00002767 if (type->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2768 ADD(nb->nb_floor_divide, tab_floordiv);
2769 ADD(nb->nb_true_divide, tab_truediv);
2770 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2771 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2772 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002773 }
2774
2775 ADD(type->tp_getattro, tab_getattr);
2776 ADD(type->tp_setattro, tab_setattr);
2777 ADD(type->tp_compare, tab_cmp);
2778 ADD(type->tp_repr, tab_repr);
2779 ADD(type->tp_hash, tab_hash);
2780 ADD(type->tp_call, tab_call);
2781 ADD(type->tp_str, tab_str);
2782 ADD(type->tp_richcompare, tab_richcmp);
2783 ADD(type->tp_iter, tab_iter);
2784 ADD(type->tp_iternext, tab_next);
2785 ADD(type->tp_descr_get, tab_descr_get);
2786 ADD(type->tp_descr_set, tab_descr_set);
2787 ADD(type->tp_init, tab_init);
2788
Guido van Rossumf040ede2001-08-07 16:40:56 +00002789 if (type->tp_new != NULL) {
2790 if (add_tp_new_wrapper(type) < 0)
2791 return -1;
2792 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002793
2794 return 0;
2795}
2796
Guido van Rossumf040ede2001-08-07 16:40:56 +00002797/* Slot wrappers that call the corresponding __foo__ slot. See comments
2798 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799
Guido van Rossumdc91b992001-08-08 22:26:22 +00002800#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002802FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002804 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002805 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002806}
2807
Guido van Rossumdc91b992001-08-08 22:26:22 +00002808#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002809static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002810FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002811{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002812 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002813 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814}
2815
Guido van Rossumdc91b992001-08-08 22:26:22 +00002816
2817#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002818static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002819FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002821 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002822 int do_other = self->ob_type != other->ob_type && \
2823 other->ob_type->tp_as_number != NULL && \
2824 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002825 if (self->ob_type->tp_as_number != NULL && \
2826 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2827 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002828 if (do_other && \
2829 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2830 r = call_maybe( \
2831 other, ROPSTR, &rcache_str, "(O)", self); \
2832 if (r != Py_NotImplemented) \
2833 return r; \
2834 Py_DECREF(r); \
2835 do_other = 0; \
2836 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002837 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002838 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002839 if (r != Py_NotImplemented || \
2840 other->ob_type == self->ob_type) \
2841 return r; \
2842 Py_DECREF(r); \
2843 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002844 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002845 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002846 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002847 } \
2848 Py_INCREF(Py_NotImplemented); \
2849 return Py_NotImplemented; \
2850}
2851
2852#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2853 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2854
2855#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2856static PyObject * \
2857FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2858{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002859 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002860 return call_method(self, OPSTR, &cache_str, \
2861 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002862}
2863
2864static int
2865slot_sq_length(PyObject *self)
2866{
Guido van Rossum2730b132001-08-28 18:22:14 +00002867 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002868 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002869 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002870
2871 if (res == NULL)
2872 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002873 len = (int)PyInt_AsLong(res);
2874 Py_DECREF(res);
2875 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002876}
2877
Guido van Rossumdc91b992001-08-08 22:26:22 +00002878SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2879SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002880
2881/* Super-optimized version of slot_sq_item.
2882 Other slots could do the same... */
2883static PyObject *
2884slot_sq_item(PyObject *self, int i)
2885{
2886 static PyObject *getitem_str;
2887 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2888 descrgetfunc f;
2889
2890 if (getitem_str == NULL) {
2891 getitem_str = PyString_InternFromString("__getitem__");
2892 if (getitem_str == NULL)
2893 return NULL;
2894 }
2895 func = _PyType_Lookup(self->ob_type, getitem_str);
2896 if (func != NULL) {
2897 if (func->ob_type == &PyWrapperDescr_Type) {
2898 PyWrapperDescrObject *wrapper =
2899 (PyWrapperDescrObject *)func;
2900 if (wrapper->d_base->wrapper == wrap_sq_item) {
2901 intargfunc f;
2902 f = (intargfunc)(wrapper->d_wrapped);
2903 return f(self, i);
2904 }
2905 }
2906 if ((f = func->ob_type->tp_descr_get) == NULL)
2907 Py_INCREF(func);
2908 else
2909 func = f(func, self, (PyObject *)(self->ob_type));
2910 ival = PyInt_FromLong(i);
2911 if (ival != NULL) {
2912 args = PyTuple_New(1);
2913 if (args != NULL) {
2914 PyTuple_SET_ITEM(args, 0, ival);
2915 retval = PyObject_Call(func, args, NULL);
2916 Py_XDECREF(args);
2917 Py_XDECREF(func);
2918 return retval;
2919 }
2920 }
2921 }
2922 else {
2923 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2924 }
2925 Py_XDECREF(args);
2926 Py_XDECREF(ival);
2927 Py_XDECREF(func);
2928 return NULL;
2929}
2930
Guido van Rossumdc91b992001-08-08 22:26:22 +00002931SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932
2933static int
2934slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2935{
2936 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002937 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002938
2939 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002940 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002941 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002943 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002944 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945 if (res == NULL)
2946 return -1;
2947 Py_DECREF(res);
2948 return 0;
2949}
2950
2951static int
2952slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2953{
2954 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002955 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956
2957 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002958 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002959 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002961 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002962 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963 if (res == NULL)
2964 return -1;
2965 Py_DECREF(res);
2966 return 0;
2967}
2968
2969static int
2970slot_sq_contains(PyObject *self, PyObject *value)
2971{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002972 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002973 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974
Guido van Rossum55f20992001-10-01 17:18:22 +00002975 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002976
2977 if (func != NULL) {
2978 args = Py_BuildValue("(O)", value);
2979 if (args == NULL)
2980 res = NULL;
2981 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002982 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002983 Py_DECREF(args);
2984 }
2985 Py_DECREF(func);
2986 if (res == NULL)
2987 return -1;
2988 return PyObject_IsTrue(res);
2989 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002990 else if (PyErr_Occurred())
2991 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002992 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002993 return _PySequence_IterSearch(self, value,
2994 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002995 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002996}
2997
Guido van Rossumdc91b992001-08-08 22:26:22 +00002998SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2999SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003000
3001#define slot_mp_length slot_sq_length
3002
Guido van Rossumdc91b992001-08-08 22:26:22 +00003003SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003004
3005static int
3006slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3007{
3008 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003009 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010
3011 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003012 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003013 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003014 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003015 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003016 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017 if (res == NULL)
3018 return -1;
3019 Py_DECREF(res);
3020 return 0;
3021}
3022
Guido van Rossumdc91b992001-08-08 22:26:22 +00003023SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3024SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3025SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3026SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3027SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3028SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3029
3030staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3031
3032SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3033 nb_power, "__pow__", "__rpow__")
3034
3035static PyObject *
3036slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3037{
Guido van Rossum2730b132001-08-28 18:22:14 +00003038 static PyObject *pow_str;
3039
Guido van Rossumdc91b992001-08-08 22:26:22 +00003040 if (modulus == Py_None)
3041 return slot_nb_power_binary(self, other);
3042 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003043 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003044 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003045}
3046
3047SLOT0(slot_nb_negative, "__neg__")
3048SLOT0(slot_nb_positive, "__pos__")
3049SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050
3051static int
3052slot_nb_nonzero(PyObject *self)
3053{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003054 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003055 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056
Guido van Rossum55f20992001-10-01 17:18:22 +00003057 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003058 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003059 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003060 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003061 func = lookup_maybe(self, "__len__", &len_str);
3062 if (func == NULL) {
3063 if (PyErr_Occurred())
3064 return -1;
3065 else
3066 return 1;
3067 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003068 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003069 res = PyObject_CallObject(func, NULL);
3070 Py_DECREF(func);
3071 if (res == NULL)
3072 return -1;
3073 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074}
3075
Guido van Rossumdc91b992001-08-08 22:26:22 +00003076SLOT0(slot_nb_invert, "__invert__")
3077SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3078SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3079SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3080SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3081SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003082
3083static int
3084slot_nb_coerce(PyObject **a, PyObject **b)
3085{
3086 static PyObject *coerce_str;
3087 PyObject *self = *a, *other = *b;
3088
3089 if (self->ob_type->tp_as_number != NULL &&
3090 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3091 PyObject *r;
3092 r = call_maybe(
3093 self, "__coerce__", &coerce_str, "(O)", other);
3094 if (r == NULL)
3095 return -1;
3096 if (r == Py_NotImplemented) {
3097 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003098 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003099 else {
3100 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3101 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003102 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003103 Py_DECREF(r);
3104 return -1;
3105 }
3106 *a = PyTuple_GET_ITEM(r, 0);
3107 Py_INCREF(*a);
3108 *b = PyTuple_GET_ITEM(r, 1);
3109 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003110 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003111 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003112 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003113 }
3114 if (other->ob_type->tp_as_number != NULL &&
3115 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3116 PyObject *r;
3117 r = call_maybe(
3118 other, "__coerce__", &coerce_str, "(O)", self);
3119 if (r == NULL)
3120 return -1;
3121 if (r == Py_NotImplemented) {
3122 Py_DECREF(r);
3123 return 1;
3124 }
3125 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3126 PyErr_SetString(PyExc_TypeError,
3127 "__coerce__ didn't return a 2-tuple");
3128 Py_DECREF(r);
3129 return -1;
3130 }
3131 *a = PyTuple_GET_ITEM(r, 1);
3132 Py_INCREF(*a);
3133 *b = PyTuple_GET_ITEM(r, 0);
3134 Py_INCREF(*b);
3135 Py_DECREF(r);
3136 return 0;
3137 }
3138 return 1;
3139}
3140
Guido van Rossumdc91b992001-08-08 22:26:22 +00003141SLOT0(slot_nb_int, "__int__")
3142SLOT0(slot_nb_long, "__long__")
3143SLOT0(slot_nb_float, "__float__")
3144SLOT0(slot_nb_oct, "__oct__")
3145SLOT0(slot_nb_hex, "__hex__")
3146SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3147SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3148SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3149SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3150SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3151SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3152SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3153SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3154SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3155SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3156SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3157SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3158 "__floordiv__", "__rfloordiv__")
3159SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3160SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3161SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162
3163static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003164half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003166 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003167 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003168 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003169
Guido van Rossum60718732001-08-28 17:47:51 +00003170 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003171 if (func == NULL) {
3172 PyErr_Clear();
3173 }
3174 else {
3175 args = Py_BuildValue("(O)", other);
3176 if (args == NULL)
3177 res = NULL;
3178 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003179 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003180 Py_DECREF(args);
3181 }
3182 if (res != Py_NotImplemented) {
3183 if (res == NULL)
3184 return -2;
3185 c = PyInt_AsLong(res);
3186 Py_DECREF(res);
3187 if (c == -1 && PyErr_Occurred())
3188 return -2;
3189 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3190 }
3191 Py_DECREF(res);
3192 }
3193 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194}
3195
Guido van Rossumab3b0342001-09-18 20:38:53 +00003196/* This slot is published for the benefit of try_3way_compare in object.c */
3197int
3198_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003199{
3200 int c;
3201
Guido van Rossumab3b0342001-09-18 20:38:53 +00003202 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003203 c = half_compare(self, other);
3204 if (c <= 1)
3205 return c;
3206 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003207 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003208 c = half_compare(other, self);
3209 if (c < -1)
3210 return -2;
3211 if (c <= 1)
3212 return -c;
3213 }
3214 return (void *)self < (void *)other ? -1 :
3215 (void *)self > (void *)other ? 1 : 0;
3216}
3217
3218static PyObject *
3219slot_tp_repr(PyObject *self)
3220{
3221 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003222 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003223
Guido van Rossum60718732001-08-28 17:47:51 +00003224 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003225 if (func != NULL) {
3226 res = PyEval_CallObject(func, NULL);
3227 Py_DECREF(func);
3228 return res;
3229 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003230 PyErr_Clear();
3231 return PyString_FromFormat("<%s object at %p>",
3232 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003233}
3234
3235static PyObject *
3236slot_tp_str(PyObject *self)
3237{
3238 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003239 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003240
Guido van Rossum60718732001-08-28 17:47:51 +00003241 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003242 if (func != NULL) {
3243 res = PyEval_CallObject(func, NULL);
3244 Py_DECREF(func);
3245 return res;
3246 }
3247 else {
3248 PyErr_Clear();
3249 return slot_tp_repr(self);
3250 }
3251}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003252
3253static long
3254slot_tp_hash(PyObject *self)
3255{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003256 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003257 static PyObject *hash_str, *eq_str, *cmp_str;
3258
Tim Peters6d6c1a32001-08-02 04:15:00 +00003259 long h;
3260
Guido van Rossum60718732001-08-28 17:47:51 +00003261 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003262
3263 if (func != NULL) {
3264 res = PyEval_CallObject(func, NULL);
3265 Py_DECREF(func);
3266 if (res == NULL)
3267 return -1;
3268 h = PyInt_AsLong(res);
3269 }
3270 else {
3271 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003272 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273 if (func == NULL) {
3274 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003275 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003276 }
3277 if (func != NULL) {
3278 Py_DECREF(func);
3279 PyErr_SetString(PyExc_TypeError, "unhashable type");
3280 return -1;
3281 }
3282 PyErr_Clear();
3283 h = _Py_HashPointer((void *)self);
3284 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285 if (h == -1 && !PyErr_Occurred())
3286 h = -2;
3287 return h;
3288}
3289
3290static PyObject *
3291slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3292{
Guido van Rossum60718732001-08-28 17:47:51 +00003293 static PyObject *call_str;
3294 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003295 PyObject *res;
3296
3297 if (meth == NULL)
3298 return NULL;
3299 res = PyObject_Call(meth, args, kwds);
3300 Py_DECREF(meth);
3301 return res;
3302}
3303
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304static PyObject *
3305slot_tp_getattro(PyObject *self, PyObject *name)
3306{
3307 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003309 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003310
Guido van Rossum8e248182001-08-12 05:17:56 +00003311 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003312 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003313 if (getattr_str == NULL)
3314 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003315 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003316 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003317 if (getattr == NULL) {
3318 /* Avoid further slowdowns */
3319 if (tp->tp_getattro == slot_tp_getattro)
3320 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003321 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003323 return PyObject_CallFunction(getattr, "OO", self, name);
3324}
3325
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003326static PyObject *
3327slot_tp_getattr_hook(PyObject *self, PyObject *name)
3328{
3329 PyTypeObject *tp = self->ob_type;
3330 PyObject *getattr, *getattribute, *res;
3331 static PyObject *getattribute_str = NULL;
3332 static PyObject *getattr_str = NULL;
3333
3334 if (getattr_str == NULL) {
3335 getattr_str = PyString_InternFromString("__getattr__");
3336 if (getattr_str == NULL)
3337 return NULL;
3338 }
3339 if (getattribute_str == NULL) {
3340 getattribute_str =
3341 PyString_InternFromString("__getattribute__");
3342 if (getattribute_str == NULL)
3343 return NULL;
3344 }
3345 getattr = _PyType_Lookup(tp, getattr_str);
3346 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003347 if (getattribute != NULL &&
3348 getattribute->ob_type == &PyWrapperDescr_Type &&
3349 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3350 PyObject_GenericGetAttr)
3351 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003352 if (getattr == NULL && getattribute == NULL) {
3353 /* Avoid further slowdowns */
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003354 /* XXX This is questionable: it means that a class that
3355 isn't born with __getattr__ or __getattribute__ cannot
3356 acquire them in later life. But it's a relatively big
3357 speedup, so I'm keeping it in for now. If this is
3358 removed, you can also remove the "def __getattr__" from
3359 class C (marked with another XXX comment) in dynamics()
3360 in Lib/test/test_descr.py. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003361 if (tp->tp_getattro == slot_tp_getattr_hook)
3362 tp->tp_getattro = PyObject_GenericGetAttr;
3363 return PyObject_GenericGetAttr(self, name);
3364 }
3365 if (getattribute == NULL)
3366 res = PyObject_GenericGetAttr(self, name);
3367 else
3368 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003369 if (getattr != NULL &&
3370 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003371 PyErr_Clear();
3372 res = PyObject_CallFunction(getattr, "OO", self, name);
3373 }
3374 return res;
3375}
3376
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377static int
3378slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3379{
3380 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003381 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382
3383 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003384 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003385 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003386 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003387 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003388 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389 if (res == NULL)
3390 return -1;
3391 Py_DECREF(res);
3392 return 0;
3393}
3394
3395/* Map rich comparison operators to their __xx__ namesakes */
3396static char *name_op[] = {
3397 "__lt__",
3398 "__le__",
3399 "__eq__",
3400 "__ne__",
3401 "__gt__",
3402 "__ge__",
3403};
3404
3405static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003406half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003407{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003408 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003409 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410
Guido van Rossum60718732001-08-28 17:47:51 +00003411 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003412 if (func == NULL) {
3413 PyErr_Clear();
3414 Py_INCREF(Py_NotImplemented);
3415 return Py_NotImplemented;
3416 }
3417 args = Py_BuildValue("(O)", other);
3418 if (args == NULL)
3419 res = NULL;
3420 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003421 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003422 Py_DECREF(args);
3423 }
3424 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003425 return res;
3426}
3427
Guido van Rossumb8f63662001-08-15 23:57:02 +00003428/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3429static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3430
3431static PyObject *
3432slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3433{
3434 PyObject *res;
3435
3436 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3437 res = half_richcompare(self, other, op);
3438 if (res != Py_NotImplemented)
3439 return res;
3440 Py_DECREF(res);
3441 }
3442 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3443 res = half_richcompare(other, self, swapped_op[op]);
3444 if (res != Py_NotImplemented) {
3445 return res;
3446 }
3447 Py_DECREF(res);
3448 }
3449 Py_INCREF(Py_NotImplemented);
3450 return Py_NotImplemented;
3451}
3452
3453static PyObject *
3454slot_tp_iter(PyObject *self)
3455{
3456 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003457 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003458
Guido van Rossum60718732001-08-28 17:47:51 +00003459 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003460 if (func != NULL) {
3461 res = PyObject_CallObject(func, NULL);
3462 Py_DECREF(func);
3463 return res;
3464 }
3465 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003466 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003467 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003468 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003469 return NULL;
3470 }
3471 Py_DECREF(func);
3472 return PySeqIter_New(self);
3473}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003474
3475static PyObject *
3476slot_tp_iternext(PyObject *self)
3477{
Guido van Rossum2730b132001-08-28 18:22:14 +00003478 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003479 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480}
3481
Guido van Rossum1a493502001-08-17 16:47:50 +00003482static PyObject *
3483slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3484{
3485 PyTypeObject *tp = self->ob_type;
3486 PyObject *get;
3487 static PyObject *get_str = NULL;
3488
3489 if (get_str == NULL) {
3490 get_str = PyString_InternFromString("__get__");
3491 if (get_str == NULL)
3492 return NULL;
3493 }
3494 get = _PyType_Lookup(tp, get_str);
3495 if (get == NULL) {
3496 /* Avoid further slowdowns */
3497 if (tp->tp_descr_get == slot_tp_descr_get)
3498 tp->tp_descr_get = NULL;
3499 Py_INCREF(self);
3500 return self;
3501 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003502 if (obj == NULL)
3503 obj = Py_None;
3504 if (type == NULL)
3505 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003506 return PyObject_CallFunction(get, "OOO", self, obj, type);
3507}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003508
3509static int
3510slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3511{
Guido van Rossum2c252392001-08-24 10:13:31 +00003512 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003513 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003514
3515 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003516 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003517 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003518 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003519 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003520 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521 if (res == NULL)
3522 return -1;
3523 Py_DECREF(res);
3524 return 0;
3525}
3526
3527static int
3528slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3529{
Guido van Rossum60718732001-08-28 17:47:51 +00003530 static PyObject *init_str;
3531 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532 PyObject *res;
3533
3534 if (meth == NULL)
3535 return -1;
3536 res = PyObject_Call(meth, args, kwds);
3537 Py_DECREF(meth);
3538 if (res == NULL)
3539 return -1;
3540 Py_DECREF(res);
3541 return 0;
3542}
3543
3544static PyObject *
3545slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3546{
3547 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3548 PyObject *newargs, *x;
3549 int i, n;
3550
3551 if (func == NULL)
3552 return NULL;
3553 assert(PyTuple_Check(args));
3554 n = PyTuple_GET_SIZE(args);
3555 newargs = PyTuple_New(n+1);
3556 if (newargs == NULL)
3557 return NULL;
3558 Py_INCREF(type);
3559 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3560 for (i = 0; i < n; i++) {
3561 x = PyTuple_GET_ITEM(args, i);
3562 Py_INCREF(x);
3563 PyTuple_SET_ITEM(newargs, i+1, x);
3564 }
3565 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003566 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003567 Py_DECREF(func);
3568 return x;
3569}
3570
Guido van Rossumf040ede2001-08-07 16:40:56 +00003571/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003572 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003573 The dict argument is the dictionary argument passed to type_new(),
3574 which is the local namespace of the class statement, in other
3575 words, it contains the methods. For each special method (like
3576 __repr__) defined in the dictionary, the corresponding function
3577 slot in the type object (like tp_repr) is set to a special function
3578 whose name is 'slot_' followed by the slot name and whose signature
3579 is whatever is required for that slot. These slot functions look
3580 up the corresponding method in the type's dictionary and call it.
3581 The slot functions have to take care of the various peculiarities
3582 of the mapping between slots and special methods, such as mapping
3583 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3584 etc.) or mapping multiple slots to a single method (sq_item,
3585 mp_subscript <--> __getitem__). */
3586
Tim Peters6d6c1a32001-08-02 04:15:00 +00003587static void
3588override_slots(PyTypeObject *type, PyObject *dict)
3589{
3590 PySequenceMethods *sq = type->tp_as_sequence;
3591 PyMappingMethods *mp = type->tp_as_mapping;
3592 PyNumberMethods *nb = type->tp_as_number;
3593
Guido van Rossumdc91b992001-08-08 22:26:22 +00003594#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003595 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003596 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597 }
3598
Guido van Rossumdc91b992001-08-08 22:26:22 +00003599#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003600 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003601 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602 }
3603
Guido van Rossumdc91b992001-08-08 22:26:22 +00003604#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003605 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003606 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607 }
3608
Guido van Rossumdc91b992001-08-08 22:26:22 +00003609#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003610 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003611 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612 }
3613
Guido van Rossumdc91b992001-08-08 22:26:22 +00003614 SQSLOT("__len__", sq_length, slot_sq_length);
3615 SQSLOT("__add__", sq_concat, slot_sq_concat);
3616 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3617 SQSLOT("__getitem__", sq_item, slot_sq_item);
3618 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3619 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3620 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3621 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3622 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3623 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3624 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3625 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626
Guido van Rossumdc91b992001-08-08 22:26:22 +00003627 MPSLOT("__len__", mp_length, slot_mp_length);
3628 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3629 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3630 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003631
Guido van Rossumdc91b992001-08-08 22:26:22 +00003632 NBSLOT("__add__", nb_add, slot_nb_add);
3633 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3634 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3635 NBSLOT("__div__", nb_divide, slot_nb_divide);
3636 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3637 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3638 NBSLOT("__pow__", nb_power, slot_nb_power);
3639 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3640 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3641 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3642 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3643 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3644 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3645 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3646 NBSLOT("__and__", nb_and, slot_nb_and);
3647 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3648 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003649 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003650 NBSLOT("__int__", nb_int, slot_nb_int);
3651 NBSLOT("__long__", nb_long, slot_nb_long);
3652 NBSLOT("__float__", nb_float, slot_nb_float);
3653 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3654 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3655 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3656 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3657 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3658 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3659 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3660 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3661 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3662 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3663 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3664 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3665 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3666 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3667 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3668 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3669 slot_nb_inplace_floor_divide);
3670 NBSLOT("__itruediv__", nb_inplace_true_divide,
3671 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672
Guido van Rossum8e248182001-08-12 05:17:56 +00003673 if (dict == NULL ||
3674 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003675 PyDict_GetItemString(dict, "__repr__"))
3676 type->tp_print = NULL;
3677
Guido van Rossumab3b0342001-09-18 20:38:53 +00003678 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003679 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3680 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3681 TPSLOT("__call__", tp_call, slot_tp_call);
3682 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003683 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003684 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003685 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3686 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3687 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3688 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3689 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3690 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3691 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3692 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3693 TPSLOT("next", tp_iternext, slot_tp_iternext);
3694 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3695 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3696 TPSLOT("__init__", tp_init, slot_tp_init);
3697 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003698}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003699
3700
3701/* Cooperative 'super' */
3702
3703typedef struct {
3704 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003705 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003706 PyObject *obj;
3707} superobject;
3708
Guido van Rossum6f799372001-09-20 20:46:19 +00003709static PyMemberDef super_members[] = {
3710 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3711 "the class invoking super()"},
3712 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3713 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003714 {0}
3715};
3716
Guido van Rossum705f0f52001-08-24 16:47:00 +00003717static void
3718super_dealloc(PyObject *self)
3719{
3720 superobject *su = (superobject *)self;
3721
Guido van Rossum048eb752001-10-02 21:24:57 +00003722 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003723 Py_XDECREF(su->obj);
3724 Py_XDECREF(su->type);
3725 self->ob_type->tp_free(self);
3726}
3727
3728static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003729super_repr(PyObject *self)
3730{
3731 superobject *su = (superobject *)self;
3732
3733 if (su->obj)
3734 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003735 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003736 su->type ? su->type->tp_name : "NULL",
3737 su->obj->ob_type->tp_name);
3738 else
3739 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003740 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003741 su->type ? su->type->tp_name : "NULL");
3742}
3743
3744static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003745super_getattro(PyObject *self, PyObject *name)
3746{
3747 superobject *su = (superobject *)self;
3748
3749 if (su->obj != NULL) {
3750 PyObject *mro, *res, *tmp;
3751 descrgetfunc f;
3752 int i, n;
3753
Guido van Rossume705ef12001-08-29 15:47:06 +00003754 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003755 if (mro == NULL)
3756 n = 0;
3757 else {
3758 assert(PyTuple_Check(mro));
3759 n = PyTuple_GET_SIZE(mro);
3760 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003761 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003762 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003763 break;
3764 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003765 if (i >= n && PyType_Check(su->obj)) {
3766 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003767 if (mro == NULL)
3768 n = 0;
3769 else {
3770 assert(PyTuple_Check(mro));
3771 n = PyTuple_GET_SIZE(mro);
3772 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003773 for (i = 0; i < n; i++) {
3774 if ((PyObject *)(su->type) ==
3775 PyTuple_GET_ITEM(mro, i))
3776 break;
3777 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003778 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003779 i++;
3780 res = NULL;
3781 for (; i < n; i++) {
3782 tmp = PyTuple_GET_ITEM(mro, i);
3783 assert(PyType_Check(tmp));
3784 res = PyDict_GetItem(
3785 ((PyTypeObject *)tmp)->tp_defined, name);
3786 if (res != NULL) {
3787 Py_INCREF(res);
3788 f = res->ob_type->tp_descr_get;
3789 if (f != NULL) {
3790 tmp = f(res, su->obj, res);
3791 Py_DECREF(res);
3792 res = tmp;
3793 }
3794 return res;
3795 }
3796 }
3797 }
3798 return PyObject_GenericGetAttr(self, name);
3799}
3800
3801static PyObject *
3802super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3803{
3804 superobject *su = (superobject *)self;
3805 superobject *new;
3806
3807 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3808 /* Not binding to an object, or already bound */
3809 Py_INCREF(self);
3810 return self;
3811 }
3812 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3813 if (new == NULL)
3814 return NULL;
3815 Py_INCREF(su->type);
3816 Py_INCREF(obj);
3817 new->type = su->type;
3818 new->obj = obj;
3819 return (PyObject *)new;
3820}
3821
3822static int
3823super_init(PyObject *self, PyObject *args, PyObject *kwds)
3824{
3825 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003826 PyTypeObject *type;
3827 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003828
3829 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3830 return -1;
3831 if (obj == Py_None)
3832 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003833 if (obj != NULL &&
3834 !PyType_IsSubtype(obj->ob_type, type) &&
3835 !(PyType_Check(obj) &&
3836 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003837 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003838 "super(type, obj): "
3839 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003840 return -1;
3841 }
3842 Py_INCREF(type);
3843 Py_XINCREF(obj);
3844 su->type = type;
3845 su->obj = obj;
3846 return 0;
3847}
3848
3849static char super_doc[] =
3850"super(type) -> unbound super object\n"
3851"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003852"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003853"Typical use to call a cooperative superclass method:\n"
3854"class C(B):\n"
3855" def meth(self, arg):\n"
3856" super(C, self).meth(arg)";
3857
Guido van Rossum048eb752001-10-02 21:24:57 +00003858static int
3859super_traverse(PyObject *self, visitproc visit, void *arg)
3860{
3861 superobject *su = (superobject *)self;
3862 int err;
3863
3864#define VISIT(SLOT) \
3865 if (SLOT) { \
3866 err = visit((PyObject *)(SLOT), arg); \
3867 if (err) \
3868 return err; \
3869 }
3870
3871 VISIT(su->obj);
3872 VISIT(su->type);
3873
3874#undef VISIT
3875
3876 return 0;
3877}
3878
Guido van Rossum705f0f52001-08-24 16:47:00 +00003879PyTypeObject PySuper_Type = {
3880 PyObject_HEAD_INIT(&PyType_Type)
3881 0, /* ob_size */
3882 "super", /* tp_name */
3883 sizeof(superobject), /* tp_basicsize */
3884 0, /* tp_itemsize */
3885 /* methods */
3886 super_dealloc, /* tp_dealloc */
3887 0, /* tp_print */
3888 0, /* tp_getattr */
3889 0, /* tp_setattr */
3890 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003891 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003892 0, /* tp_as_number */
3893 0, /* tp_as_sequence */
3894 0, /* tp_as_mapping */
3895 0, /* tp_hash */
3896 0, /* tp_call */
3897 0, /* tp_str */
3898 super_getattro, /* tp_getattro */
3899 0, /* tp_setattro */
3900 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003901 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3902 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003903 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003904 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003905 0, /* tp_clear */
3906 0, /* tp_richcompare */
3907 0, /* tp_weaklistoffset */
3908 0, /* tp_iter */
3909 0, /* tp_iternext */
3910 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003911 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003912 0, /* tp_getset */
3913 0, /* tp_base */
3914 0, /* tp_dict */
3915 super_descr_get, /* tp_descr_get */
3916 0, /* tp_descr_set */
3917 0, /* tp_dictoffset */
3918 super_init, /* tp_init */
3919 PyType_GenericAlloc, /* tp_alloc */
3920 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003921 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003922};