blob: 719a0a4021e697e4f4c2ca532efd8910e6b03ef7 [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
Tim Peters6d6c1a32001-08-02 04:15:00 +00007static struct memberlist 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
56static PyObject *
57type_dict(PyTypeObject *type, void *context)
58{
59 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000060 Py_INCREF(Py_None);
61 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000062 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000063 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
64 Py_INCREF(type->tp_dict);
65 return type->tp_dict;
66 }
67 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000068}
69
Tim Peters6d6c1a32001-08-02 04:15:00 +000070static PyObject *
71type_defined(PyTypeObject *type, void *context)
72{
73 if (type->tp_defined == NULL) {
74 Py_INCREF(Py_None);
75 return Py_None;
76 }
77 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
78 Py_INCREF(type->tp_defined);
79 return type->tp_defined;
80 }
81 return PyDictProxy_New(type->tp_defined);
82}
83
84static PyObject *
85type_dynamic(PyTypeObject *type, void *context)
86{
87 PyObject *res;
88
89 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
90 Py_INCREF(res);
91 return res;
92}
93
94struct getsetlist type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000095 {"__name__", (getter)type_name, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000096 {"__module__", (getter)type_module, NULL, NULL},
97 {"__dict__", (getter)type_dict, NULL, NULL},
98 {"__defined__", (getter)type_defined, NULL, NULL},
99 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
100 {0}
101};
102
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000103static int
104type_compare(PyObject *v, PyObject *w)
105{
106 /* This is called with type objects only. So we
107 can just compare the addresses. */
108 Py_uintptr_t vv = (Py_uintptr_t)v;
109 Py_uintptr_t ww = (Py_uintptr_t)w;
110 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
111}
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000117
118 mod = type_module(type, NULL);
119 if (mod == NULL)
120 PyErr_Clear();
121 else if (!PyString_Check(mod)) {
122 Py_DECREF(mod);
123 mod = NULL;
124 }
125 name = type_name(type, NULL);
126 if (name == NULL)
127 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000128
129 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
130 rtn = PyString_FromFormat("<type '%s.%s'>",
131 PyString_AS_STRING(mod),
132 PyString_AS_STRING(name));
133 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000134 else
Barry Warsaw7ce36942001-08-24 18:34:26 +0000135 rtn = PyString_FromFormat("<type '%s'>", type->tp_name);
136
Guido van Rossumc3542212001-08-16 09:18:56 +0000137 Py_XDECREF(mod);
138 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000139 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140}
141
Tim Peters6d6c1a32001-08-02 04:15:00 +0000142static PyObject *
143type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
144{
145 PyObject *obj;
146
147 if (type->tp_new == NULL) {
148 PyErr_Format(PyExc_TypeError,
149 "cannot create '%.100s' instances",
150 type->tp_name);
151 return NULL;
152 }
153
154 obj = type->tp_new(type, args, NULL);
155 if (obj != NULL) {
156 type = obj->ob_type;
157 if (type->tp_init != NULL &&
158 type->tp_init(obj, args, kwds) < 0) {
159 Py_DECREF(obj);
160 obj = NULL;
161 }
162 }
163 return obj;
164}
165
166PyObject *
167PyType_GenericAlloc(PyTypeObject *type, int nitems)
168{
169 int size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000170 PyObject *obj;
171
172 /* Inline PyObject_New() so we can zero the memory */
173 size = _PyObject_VAR_SIZE(type, nitems);
Neil Schemenauerc806c882001-08-29 23:54:54 +0000174 if (PyType_IS_GC(type)) {
175 obj = _PyObject_GC_Malloc(type, nitems);
176 }
177 else {
178 obj = PyObject_MALLOC(size);
179 }
180 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000181 return PyErr_NoMemory();
Neil Schemenauerc806c882001-08-29 23:54:54 +0000182 memset(obj, '\0', size);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000183 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
184 Py_INCREF(type);
185 if (type->tp_itemsize == 0)
186 PyObject_INIT(obj, type);
187 else
188 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
189 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000190 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000191 return obj;
192}
193
194PyObject *
195PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
196{
197 return type->tp_alloc(type, 0);
198}
199
200/* Helper for subtyping */
201
202static void
203subtype_dealloc(PyObject *self)
204{
205 int dictoffset = self->ob_type->tp_dictoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000206 int weaklistoffset = self->ob_type->tp_weaklistoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000207 PyTypeObject *type, *base;
208 destructor f;
209
210 /* This exists so we can DECREF self->ob_type */
211
212 /* Find the nearest base with a different tp_dealloc */
213 type = self->ob_type;
214 base = type->tp_base;
215 while ((f = base->tp_dealloc) == subtype_dealloc) {
216 base = base->tp_base;
217 assert(base);
218 }
219
220 /* If we added a dict, DECREF it */
221 if (dictoffset && !base->tp_dictoffset) {
222 PyObject **dictptr = (PyObject **) ((char *)self + dictoffset);
223 PyObject *dict = *dictptr;
224 if (dict != NULL) {
225 Py_DECREF(dict);
226 *dictptr = NULL;
227 }
228 }
229
Guido van Rossum9676b222001-08-17 20:32:36 +0000230 /* If we added weaklist, we clear it */
231 if (weaklistoffset && !base->tp_weaklistoffset)
232 PyObject_ClearWeakRefs(self);
233
Tim Peters6d6c1a32001-08-02 04:15:00 +0000234 /* Finalize GC if the base doesn't do GC and we do */
235 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
236 PyObject_GC_Fini(self);
237
238 /* Call the base tp_dealloc() */
239 assert(f);
240 f(self);
241
242 /* Can't reference self beyond this point */
243 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
244 Py_DECREF(type);
245 }
246}
247
248staticforward void override_slots(PyTypeObject *type, PyObject *dict);
249staticforward PyTypeObject *solid_base(PyTypeObject *type);
250
251typedef struct {
252 PyTypeObject type;
253 PyNumberMethods as_number;
254 PySequenceMethods as_sequence;
255 PyMappingMethods as_mapping;
256 PyBufferProcs as_buffer;
257 PyObject *name, *slots;
258 struct memberlist members[1];
259} etype;
260
261/* type test with subclassing support */
262
263int
264PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
265{
266 PyObject *mro;
267
268 mro = a->tp_mro;
269 if (mro != NULL) {
270 /* Deal with multiple inheritance without recursion
271 by walking the MRO tuple */
272 int i, n;
273 assert(PyTuple_Check(mro));
274 n = PyTuple_GET_SIZE(mro);
275 for (i = 0; i < n; i++) {
276 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
277 return 1;
278 }
279 return 0;
280 }
281 else {
282 /* a is not completely initilized yet; follow tp_base */
283 do {
284 if (a == b)
285 return 1;
286 a = a->tp_base;
287 } while (a != NULL);
288 return b == &PyBaseObject_Type;
289 }
290}
291
Guido van Rossum60718732001-08-28 17:47:51 +0000292/* Internal routine to do a method lookup in the type
293 without looking in the instance dictionary
294 (so we can't use PyObject_GetAttr) but still binding
295 it to the instance. The arguments are the object,
296 the method name as a C string, and the address of a
297 static variable used to cache the interned Python string. */
298
299static PyObject *
300lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
301{
302 PyObject *res;
303
304 if (*attrobj == NULL) {
305 *attrobj = PyString_InternFromString(attrstr);
306 if (*attrobj == NULL)
307 return NULL;
308 }
309 res = _PyType_Lookup(self->ob_type, *attrobj);
310 if (res == NULL)
311 PyErr_SetObject(PyExc_AttributeError, *attrobj);
312 else {
313 descrgetfunc f;
314 if ((f = res->ob_type->tp_descr_get) == NULL)
315 Py_INCREF(res);
316 else
317 res = f(res, self, (PyObject *)(self->ob_type));
318 }
319 return res;
320}
321
Guido van Rossum2730b132001-08-28 18:22:14 +0000322/* A variation of PyObject_CallMethod that uses lookup_method()
323 instead of PyObject_GetAttrString(). This uses the same convention
324 as lookup_method to cache the interned name string object. */
325
326PyObject *
327call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
328{
329 va_list va;
330 PyObject *args, *func = 0, *retval;
331 PyObject *dummy_str = NULL;
332 va_start(va, format);
333
334 func = lookup_method(o, name, &dummy_str);
335 Py_XDECREF(dummy_str);
336 if (func == NULL) {
337 va_end(va);
338 PyErr_SetString(PyExc_AttributeError, name);
339 return 0;
340 }
341
342 if (format && *format)
343 args = Py_VaBuildValue(format, va);
344 else
345 args = PyTuple_New(0);
346
347 va_end(va);
348
349 if (!args)
350 return NULL;
351
352 if (!PyTuple_Check(args)) {
353 PyObject *a;
354
355 a = PyTuple_New(1);
356 if (a == NULL)
357 return NULL;
358 if (PyTuple_SetItem(a, 0, args) < 0)
359 return NULL;
360 args = a;
361 }
362
363 retval = PyObject_CallObject(func, args);
364
365 Py_DECREF(args);
366 Py_DECREF(func);
367
368 return retval;
369}
370
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371/* Method resolution order algorithm from "Putting Metaclasses to Work"
372 by Forman and Danforth (Addison-Wesley 1999). */
373
374static int
375conservative_merge(PyObject *left, PyObject *right)
376{
377 int left_size;
378 int right_size;
379 int i, j, r, ok;
380 PyObject *temp, *rr;
381
382 assert(PyList_Check(left));
383 assert(PyList_Check(right));
384
385 again:
386 left_size = PyList_GET_SIZE(left);
387 right_size = PyList_GET_SIZE(right);
388 for (i = 0; i < left_size; i++) {
389 for (j = 0; j < right_size; j++) {
390 if (PyList_GET_ITEM(left, i) ==
391 PyList_GET_ITEM(right, j)) {
392 /* found a merge point */
393 temp = PyList_New(0);
394 if (temp == NULL)
395 return -1;
396 for (r = 0; r < j; r++) {
397 rr = PyList_GET_ITEM(right, r);
398 ok = PySequence_Contains(left, rr);
399 if (ok < 0) {
400 Py_DECREF(temp);
401 return -1;
402 }
403 if (!ok) {
404 ok = PyList_Append(temp, rr);
405 if (ok < 0) {
406 Py_DECREF(temp);
407 return -1;
408 }
409 }
410 }
411 ok = PyList_SetSlice(left, i, i, temp);
412 Py_DECREF(temp);
413 if (ok < 0)
414 return -1;
415 ok = PyList_SetSlice(right, 0, j+1, NULL);
416 if (ok < 0)
417 return -1;
418 goto again;
419 }
420 }
421 }
422 return PyList_SetSlice(left, left_size, left_size, right);
423}
424
425static int
426serious_order_disagreements(PyObject *left, PyObject *right)
427{
428 return 0; /* XXX later -- for now, we cheat: "don't do that" */
429}
430
431static PyObject *
432mro_implementation(PyTypeObject *type)
433{
434 int i, n, ok;
435 PyObject *bases, *result;
436
437 bases = type->tp_bases;
438 n = PyTuple_GET_SIZE(bases);
439 result = Py_BuildValue("[O]", (PyObject *)type);
440 if (result == NULL)
441 return NULL;
442 for (i = 0; i < n; i++) {
443 PyTypeObject *base =
444 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
445 PyObject *parentMRO = PySequence_List(base->tp_mro);
446 if (parentMRO == NULL) {
447 Py_DECREF(result);
448 return NULL;
449 }
450 if (serious_order_disagreements(result, parentMRO)) {
451 Py_DECREF(result);
452 return NULL;
453 }
454 ok = conservative_merge(result, parentMRO);
455 Py_DECREF(parentMRO);
456 if (ok < 0) {
457 Py_DECREF(result);
458 return NULL;
459 }
460 }
461 return result;
462}
463
464static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000465mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466{
467 PyTypeObject *type = (PyTypeObject *)self;
468
Tim Peters6d6c1a32001-08-02 04:15:00 +0000469 return mro_implementation(type);
470}
471
472static int
473mro_internal(PyTypeObject *type)
474{
475 PyObject *mro, *result, *tuple;
476
477 if (type->ob_type == &PyType_Type) {
478 result = mro_implementation(type);
479 }
480 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000481 static PyObject *mro_str;
482 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000483 if (mro == NULL)
484 return -1;
485 result = PyObject_CallObject(mro, NULL);
486 Py_DECREF(mro);
487 }
488 if (result == NULL)
489 return -1;
490 tuple = PySequence_Tuple(result);
491 Py_DECREF(result);
492 type->tp_mro = tuple;
493 return 0;
494}
495
496
497/* Calculate the best base amongst multiple base classes.
498 This is the first one that's on the path to the "solid base". */
499
500static PyTypeObject *
501best_base(PyObject *bases)
502{
503 int i, n;
504 PyTypeObject *base, *winner, *candidate, *base_i;
505
506 assert(PyTuple_Check(bases));
507 n = PyTuple_GET_SIZE(bases);
508 assert(n > 0);
509 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
510 winner = &PyBaseObject_Type;
511 for (i = 0; i < n; i++) {
512 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
513 if (!PyType_Check((PyObject *)base_i)) {
514 PyErr_SetString(
515 PyExc_TypeError,
516 "bases must be types");
517 return NULL;
518 }
519 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000520 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000521 return NULL;
522 }
523 candidate = solid_base(base_i);
524 if (PyType_IsSubtype(winner, candidate))
525 ;
526 else if (PyType_IsSubtype(candidate, winner)) {
527 winner = candidate;
528 base = base_i;
529 }
530 else {
531 PyErr_SetString(
532 PyExc_TypeError,
533 "multiple bases have "
534 "instance lay-out conflict");
535 return NULL;
536 }
537 }
538 assert(base != NULL);
539 return base;
540}
541
542static int
543extra_ivars(PyTypeObject *type, PyTypeObject *base)
544{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000545 size_t t_size = type->tp_basicsize;
546 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547
Guido van Rossum9676b222001-08-17 20:32:36 +0000548 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000549 if (type->tp_itemsize || base->tp_itemsize) {
550 /* If itemsize is involved, stricter rules */
551 return t_size != b_size ||
552 type->tp_itemsize != base->tp_itemsize;
553 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000554 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
555 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
556 t_size -= sizeof(PyObject *);
557 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
558 type->tp_dictoffset + sizeof(PyObject *) == t_size)
559 t_size -= sizeof(PyObject *);
560
561 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000562}
563
564static PyTypeObject *
565solid_base(PyTypeObject *type)
566{
567 PyTypeObject *base;
568
569 if (type->tp_base)
570 base = solid_base(type->tp_base);
571 else
572 base = &PyBaseObject_Type;
573 if (extra_ivars(type, base))
574 return type;
575 else
576 return base;
577}
578
579staticforward void object_dealloc(PyObject *);
580staticforward int object_init(PyObject *, PyObject *, PyObject *);
581
582static PyObject *
583type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
584{
585 PyObject *name, *bases, *dict;
586 static char *kwlist[] = {"name", "bases", "dict", 0};
587 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000588 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 etype *et;
590 struct memberlist *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000591 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000593 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594 if (metatype == &PyType_Type &&
595 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
596 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000597 PyObject *x = PyTuple_GET_ITEM(args, 0);
598 Py_INCREF(x->ob_type);
599 return (PyObject *) x->ob_type;
600 }
601
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000602 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000603 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
604 &name,
605 &PyTuple_Type, &bases,
606 &PyDict_Type, &dict))
607 return NULL;
608
609 /* Determine the proper metatype to deal with this,
610 and check for metatype conflicts while we're at it.
611 Note that if some other metatype wins to contract,
612 it's possible that its instances are not types. */
613 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000614 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000615 for (i = 0; i < nbases; i++) {
616 tmp = PyTuple_GET_ITEM(bases, i);
617 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000618 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000619 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000620 if (PyType_IsSubtype(tmptype, winner)) {
621 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622 continue;
623 }
624 PyErr_SetString(PyExc_TypeError,
625 "metatype conflict among bases");
626 return NULL;
627 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000628 if (winner != metatype) {
629 if (winner->tp_new != type_new) /* Pass it to the winner */
630 return winner->tp_new(winner, args, kwds);
631 metatype = winner;
632 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000633
634 /* Adjust for empty tuple bases */
635 if (nbases == 0) {
636 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
637 if (bases == NULL)
638 return NULL;
639 nbases = 1;
640 }
641 else
642 Py_INCREF(bases);
643
644 /* XXX From here until type is allocated, "return NULL" leaks bases! */
645
646 /* Calculate best base, and check that all bases are type objects */
647 base = best_base(bases);
648 if (base == NULL)
649 return NULL;
650 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
651 PyErr_Format(PyExc_TypeError,
652 "type '%.100s' is not an acceptable base type",
653 base->tp_name);
654 return NULL;
655 }
656
Guido van Rossum1a493502001-08-17 16:47:50 +0000657 /* Should this be a dynamic class (i.e. modifiable __dict__)?
658 Look in two places for a variable named __dynamic__:
659 1) in the class dict
660 2) in the module dict (globals)
661 The first variable that is an int >= 0 is used.
662 Otherwise, a default is calculated from the base classes:
663 if any base class is dynamic, this class is dynamic; otherwise
664 it is static. */
665 dynamic = -1; /* Not yet determined */
666 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 tmp = PyDict_GetItemString(dict, "__dynamic__");
668 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000669 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000670 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000671 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000673 if (dynamic < 0) {
674 /* Look in the module globals */
675 tmp = PyEval_GetGlobals();
676 if (tmp != NULL) {
677 tmp = PyDict_GetItemString(tmp, "__dynamic__");
678 if (tmp != NULL) {
679 dynamic = PyInt_AsLong(tmp);
680 if (dynamic < 0)
681 PyErr_Clear();
682 }
683 }
684 }
685 if (dynamic < 0) {
686 /* Make a new class dynamic if any of its bases is
687 dynamic. This is not always the same as inheriting
688 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 dynamic = 0;
690 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000691 tmptype = (PyTypeObject *)
692 PyTuple_GET_ITEM(bases, i);
693 if (tmptype->tp_flags &
694 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695 dynamic = 1;
696 break;
697 }
698 }
699 }
700
701 /* Check for a __slots__ sequence variable in dict, and count it */
702 slots = PyDict_GetItemString(dict, "__slots__");
703 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000704 add_dict = 0;
705 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706 if (slots != NULL) {
707 /* Make it into a tuple */
708 if (PyString_Check(slots))
709 slots = Py_BuildValue("(O)", slots);
710 else
711 slots = PySequence_Tuple(slots);
712 if (slots == NULL)
713 return NULL;
714 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000715 if (nslots > 0 && base->tp_itemsize != 0) {
716 PyErr_Format(PyExc_TypeError,
717 "nonempty __slots__ "
718 "not supported for subtype of '%s'",
719 base->tp_name);
720 return NULL;
721 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000722 for (i = 0; i < nslots; i++) {
723 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
724 PyErr_SetString(PyExc_TypeError,
725 "__slots__ must be a sequence of strings");
726 Py_DECREF(slots);
727 return NULL;
728 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000729 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000730 }
731 }
732 if (slots == NULL && base->tp_dictoffset == 0 &&
733 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000734 base->tp_setattro == NULL)) {
735 nslots++;
736 add_dict++;
737 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000738 if (slots == NULL && base->tp_weaklistoffset == 0 &&
739 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000740 nslots++;
741 add_weak++;
742 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000743
744 /* XXX From here until type is safely allocated,
745 "return NULL" may leak slots! */
746
747 /* Allocate the type object */
748 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
749 if (type == NULL)
750 return NULL;
751
752 /* Keep name and slots alive in the extended type object */
753 et = (etype *)type;
754 Py_INCREF(name);
755 et->name = name;
756 et->slots = slots;
757
Guido van Rossumdc91b992001-08-08 22:26:22 +0000758 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000759 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
760 Py_TPFLAGS_BASETYPE;
761 if (dynamic)
762 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000763
764 /* It's a new-style number unless it specifically inherits any
765 old-style numeric behavior */
766 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
767 (base->tp_as_number == NULL))
768 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
769
770 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000771 type->tp_as_number = &et->as_number;
772 type->tp_as_sequence = &et->as_sequence;
773 type->tp_as_mapping = &et->as_mapping;
774 type->tp_as_buffer = &et->as_buffer;
775 type->tp_name = PyString_AS_STRING(name);
776
777 /* Set tp_base and tp_bases */
778 type->tp_bases = bases;
779 Py_INCREF(base);
780 type->tp_base = base;
781
782 /* Initialize tp_defined from passed-in dict */
783 type->tp_defined = dict = PyDict_Copy(dict);
784 if (dict == NULL) {
785 Py_DECREF(type);
786 return NULL;
787 }
788
Guido van Rossumc3542212001-08-16 09:18:56 +0000789 /* Set __module__ in the dict */
790 if (PyDict_GetItemString(dict, "__module__") == NULL) {
791 tmp = PyEval_GetGlobals();
792 if (tmp != NULL) {
793 tmp = PyDict_GetItemString(tmp, "__name__");
794 if (tmp != NULL) {
795 if (PyDict_SetItemString(dict, "__module__",
796 tmp) < 0)
797 return NULL;
798 }
799 }
800 }
801
Tim Peters6d6c1a32001-08-02 04:15:00 +0000802 /* Special-case __new__: if it's a plain function,
803 make it a static function */
804 tmp = PyDict_GetItemString(dict, "__new__");
805 if (tmp != NULL && PyFunction_Check(tmp)) {
806 tmp = PyStaticMethod_New(tmp);
807 if (tmp == NULL) {
808 Py_DECREF(type);
809 return NULL;
810 }
811 PyDict_SetItemString(dict, "__new__", tmp);
812 Py_DECREF(tmp);
813 }
814
815 /* Add descriptors for custom slots from __slots__, or for __dict__ */
816 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000817 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 if (slots != NULL) {
819 for (i = 0; i < nslots; i++, mp++) {
820 mp->name = PyString_AS_STRING(
821 PyTuple_GET_ITEM(slots, i));
822 mp->type = T_OBJECT;
823 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000824 if (base->tp_weaklistoffset == 0 &&
825 strcmp(mp->name, "__weakref__") == 0)
826 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827 slotoffset += sizeof(PyObject *);
828 }
829 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000830 else {
831 if (add_dict) {
832 type->tp_dictoffset = slotoffset;
833 mp->name = "__dict__";
834 mp->type = T_OBJECT;
835 mp->offset = slotoffset;
836 mp->readonly = 1;
837 mp++;
838 slotoffset += sizeof(PyObject *);
839 }
840 if (add_weak) {
841 type->tp_weaklistoffset = slotoffset;
842 mp->name = "__weakref__";
843 mp->type = T_OBJECT;
844 mp->offset = slotoffset;
845 mp->readonly = 1;
846 mp++;
847 slotoffset += sizeof(PyObject *);
848 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000849 }
850 type->tp_basicsize = slotoffset;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000851 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
853 /* Special case some slots */
854 if (type->tp_dictoffset != 0 || nslots > 0) {
855 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
856 type->tp_getattro = PyObject_GenericGetAttr;
857 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
858 type->tp_setattro = PyObject_GenericSetAttr;
859 }
860 type->tp_dealloc = subtype_dealloc;
861
862 /* Always override allocation strategy to use regular heap */
863 type->tp_alloc = PyType_GenericAlloc;
864 type->tp_free = _PyObject_Del;
865
866 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000867 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 Py_DECREF(type);
869 return NULL;
870 }
871
872 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000873 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
874 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000875
Tim Peters6d6c1a32001-08-02 04:15:00 +0000876 return (PyObject *)type;
877}
878
879/* Internal API to look for a name through the MRO.
880 This returns a borrowed reference, and doesn't set an exception! */
881PyObject *
882_PyType_Lookup(PyTypeObject *type, PyObject *name)
883{
884 int i, n;
885 PyObject *mro, *res, *dict;
886
887 /* For static types, look in tp_dict */
888 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
889 dict = type->tp_dict;
890 assert(dict && PyDict_Check(dict));
891 return PyDict_GetItem(dict, name);
892 }
893
894 /* For dynamic types, look in tp_defined of types in MRO */
895 mro = type->tp_mro;
896 assert(PyTuple_Check(mro));
897 n = PyTuple_GET_SIZE(mro);
898 for (i = 0; i < n; i++) {
899 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
900 assert(PyType_Check(type));
901 dict = type->tp_defined;
902 assert(dict && PyDict_Check(dict));
903 res = PyDict_GetItem(dict, name);
904 if (res != NULL)
905 return res;
906 }
907 return NULL;
908}
909
910/* This is similar to PyObject_GenericGetAttr(),
911 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
912static PyObject *
913type_getattro(PyTypeObject *type, PyObject *name)
914{
915 PyTypeObject *metatype = type->ob_type;
916 PyObject *descr, *res;
917 descrgetfunc f;
918
919 /* Initialize this type (we'll assume the metatype is initialized) */
920 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000921 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000922 return NULL;
923 }
924
925 /* Get a descriptor from the metatype */
926 descr = _PyType_Lookup(metatype, name);
927 f = NULL;
928 if (descr != NULL) {
929 f = descr->ob_type->tp_descr_get;
930 if (f != NULL && PyDescr_IsData(descr))
931 return f(descr,
932 (PyObject *)type, (PyObject *)metatype);
933 }
934
935 /* Look in tp_defined of this type and its bases */
936 res = _PyType_Lookup(type, name);
937 if (res != NULL) {
938 f = res->ob_type->tp_descr_get;
939 if (f != NULL)
940 return f(res, (PyObject *)NULL, (PyObject *)type);
941 Py_INCREF(res);
942 return res;
943 }
944
945 /* Use the descriptor from the metatype */
946 if (f != NULL) {
947 res = f(descr, (PyObject *)type, (PyObject *)metatype);
948 return res;
949 }
950 if (descr != NULL) {
951 Py_INCREF(descr);
952 return descr;
953 }
954
955 /* Give up */
956 PyErr_Format(PyExc_AttributeError,
957 "type object '%.50s' has no attribute '%.400s'",
958 type->tp_name, PyString_AS_STRING(name));
959 return NULL;
960}
961
962static int
963type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
964{
965 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
966 return PyObject_GenericSetAttr((PyObject *)type, name, value);
967 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
968 return -1;
969}
970
971static void
972type_dealloc(PyTypeObject *type)
973{
974 etype *et;
975
976 /* Assert this is a heap-allocated type object */
977 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
978 et = (etype *)type;
979 Py_XDECREF(type->tp_base);
980 Py_XDECREF(type->tp_dict);
981 Py_XDECREF(type->tp_bases);
982 Py_XDECREF(type->tp_mro);
983 Py_XDECREF(type->tp_defined);
984 /* XXX more? */
985 Py_XDECREF(et->name);
986 Py_XDECREF(et->slots);
987 type->ob_type->tp_free((PyObject *)type);
988}
989
990static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000991 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000992 "mro() -> list\nreturn a type's method resolution order"},
993 {0}
994};
995
996static char type_doc[] =
997"type(object) -> the object's type\n"
998"type(name, bases, dict) -> a new type";
999
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001000PyTypeObject PyType_Type = {
1001 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002 0, /* ob_size */
1003 "type", /* tp_name */
1004 sizeof(etype), /* tp_basicsize */
1005 sizeof(struct memberlist), /* tp_itemsize */
1006 (destructor)type_dealloc, /* tp_dealloc */
1007 0, /* tp_print */
1008 0, /* tp_getattr */
1009 0, /* tp_setattr */
1010 type_compare, /* tp_compare */
1011 (reprfunc)type_repr, /* tp_repr */
1012 0, /* tp_as_number */
1013 0, /* tp_as_sequence */
1014 0, /* tp_as_mapping */
1015 (hashfunc)_Py_HashPointer, /* tp_hash */
1016 (ternaryfunc)type_call, /* tp_call */
1017 0, /* tp_str */
1018 (getattrofunc)type_getattro, /* tp_getattro */
1019 (setattrofunc)type_setattro, /* tp_setattro */
1020 0, /* tp_as_buffer */
1021 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1022 type_doc, /* tp_doc */
1023 0, /* tp_traverse */
1024 0, /* tp_clear */
1025 0, /* tp_richcompare */
1026 0, /* tp_weaklistoffset */
1027 0, /* tp_iter */
1028 0, /* tp_iternext */
1029 type_methods, /* tp_methods */
1030 type_members, /* tp_members */
1031 type_getsets, /* tp_getset */
1032 0, /* tp_base */
1033 0, /* tp_dict */
1034 0, /* tp_descr_get */
1035 0, /* tp_descr_set */
1036 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1037 0, /* tp_init */
1038 0, /* tp_alloc */
1039 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001040};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041
1042
1043/* The base type of all types (eventually)... except itself. */
1044
1045static int
1046object_init(PyObject *self, PyObject *args, PyObject *kwds)
1047{
1048 return 0;
1049}
1050
1051static void
1052object_dealloc(PyObject *self)
1053{
1054 self->ob_type->tp_free(self);
1055}
1056
Guido van Rossum8e248182001-08-12 05:17:56 +00001057static PyObject *
1058object_repr(PyObject *self)
1059{
Guido van Rossum76e69632001-08-16 18:52:43 +00001060 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001061 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001062
Guido van Rossum76e69632001-08-16 18:52:43 +00001063 type = self->ob_type;
1064 mod = type_module(type, NULL);
1065 if (mod == NULL)
1066 PyErr_Clear();
1067 else if (!PyString_Check(mod)) {
1068 Py_DECREF(mod);
1069 mod = NULL;
1070 }
1071 name = type_name(type, NULL);
1072 if (name == NULL)
1073 return NULL;
1074 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Barry Warsaw7ce36942001-08-24 18:34:26 +00001075 rtn = PyString_FromFormat("<%s.%s instance at %p>",
1076 PyString_AS_STRING(mod),
1077 PyString_AS_STRING(name),
1078 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001079 else
Barry Warsaw7ce36942001-08-24 18:34:26 +00001080 rtn = PyString_FromFormat("<%s instance at %p>",
1081 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001082 Py_XDECREF(mod);
1083 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001084 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001085}
1086
Guido van Rossumb8f63662001-08-15 23:57:02 +00001087static PyObject *
1088object_str(PyObject *self)
1089{
1090 unaryfunc f;
1091
1092 f = self->ob_type->tp_repr;
1093 if (f == NULL)
1094 f = object_repr;
1095 return f(self);
1096}
1097
Guido van Rossum8e248182001-08-12 05:17:56 +00001098static long
1099object_hash(PyObject *self)
1100{
1101 return _Py_HashPointer(self);
1102}
Guido van Rossum8e248182001-08-12 05:17:56 +00001103
Tim Peters6d6c1a32001-08-02 04:15:00 +00001104static void
1105object_free(PyObject *self)
1106{
1107 PyObject_Del(self);
1108}
1109
1110static struct memberlist object_members[] = {
1111 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
1112 {0}
1113};
1114
1115PyTypeObject PyBaseObject_Type = {
1116 PyObject_HEAD_INIT(&PyType_Type)
1117 0, /* ob_size */
1118 "object", /* tp_name */
1119 sizeof(PyObject), /* tp_basicsize */
1120 0, /* tp_itemsize */
1121 (destructor)object_dealloc, /* tp_dealloc */
1122 0, /* tp_print */
1123 0, /* tp_getattr */
1124 0, /* tp_setattr */
1125 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001126 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001127 0, /* tp_as_number */
1128 0, /* tp_as_sequence */
1129 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001130 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001132 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001134 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 0, /* tp_as_buffer */
1136 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1137 "The most base type", /* tp_doc */
1138 0, /* tp_traverse */
1139 0, /* tp_clear */
1140 0, /* tp_richcompare */
1141 0, /* tp_weaklistoffset */
1142 0, /* tp_iter */
1143 0, /* tp_iternext */
1144 0, /* tp_methods */
1145 object_members, /* tp_members */
1146 0, /* tp_getset */
1147 0, /* tp_base */
1148 0, /* tp_dict */
1149 0, /* tp_descr_get */
1150 0, /* tp_descr_set */
1151 0, /* tp_dictoffset */
1152 object_init, /* tp_init */
1153 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001154 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 object_free, /* tp_free */
1156};
1157
1158
1159/* Initialize the __dict__ in a type object */
1160
1161static int
1162add_methods(PyTypeObject *type, PyMethodDef *meth)
1163{
1164 PyObject *dict = type->tp_defined;
1165
1166 for (; meth->ml_name != NULL; meth++) {
1167 PyObject *descr;
1168 if (PyDict_GetItemString(dict, meth->ml_name))
1169 continue;
1170 descr = PyDescr_NewMethod(type, meth);
1171 if (descr == NULL)
1172 return -1;
1173 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1174 return -1;
1175 Py_DECREF(descr);
1176 }
1177 return 0;
1178}
1179
1180static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001181add_members(PyTypeObject *type, struct memberlist *memb)
1182{
1183 PyObject *dict = type->tp_defined;
1184
1185 for (; memb->name != NULL; memb++) {
1186 PyObject *descr;
1187 if (PyDict_GetItemString(dict, memb->name))
1188 continue;
1189 descr = PyDescr_NewMember(type, memb);
1190 if (descr == NULL)
1191 return -1;
1192 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1193 return -1;
1194 Py_DECREF(descr);
1195 }
1196 return 0;
1197}
1198
1199static int
1200add_getset(PyTypeObject *type, struct getsetlist *gsp)
1201{
1202 PyObject *dict = type->tp_defined;
1203
1204 for (; gsp->name != NULL; gsp++) {
1205 PyObject *descr;
1206 if (PyDict_GetItemString(dict, gsp->name))
1207 continue;
1208 descr = PyDescr_NewGetSet(type, gsp);
1209
1210 if (descr == NULL)
1211 return -1;
1212 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1213 return -1;
1214 Py_DECREF(descr);
1215 }
1216 return 0;
1217}
1218
Guido van Rossum13d52f02001-08-10 21:24:08 +00001219static void
1220inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221{
1222 int oldsize, newsize;
1223
Guido van Rossum13d52f02001-08-10 21:24:08 +00001224 /* Special flag magic */
1225 if (!type->tp_as_buffer && base->tp_as_buffer) {
1226 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1227 type->tp_flags |=
1228 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1229 }
1230 if (!type->tp_as_sequence && base->tp_as_sequence) {
1231 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1232 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1233 }
1234 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1235 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1236 if ((!type->tp_as_number && base->tp_as_number) ||
1237 (!type->tp_as_sequence && base->tp_as_sequence)) {
1238 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1239 if (!type->tp_as_number && !type->tp_as_sequence) {
1240 type->tp_flags |= base->tp_flags &
1241 Py_TPFLAGS_HAVE_INPLACEOPS;
1242 }
1243 }
1244 /* Wow */
1245 }
1246 if (!type->tp_as_number && base->tp_as_number) {
1247 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1248 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1249 }
1250
1251 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001252 oldsize = base->tp_basicsize;
1253 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1254 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1255 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001256 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1257 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001258 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001259 if (type->tp_traverse == NULL)
1260 type->tp_traverse = base->tp_traverse;
1261 if (type->tp_clear == NULL)
1262 type->tp_clear = base->tp_clear;
1263 }
1264 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1265 if (base != &PyBaseObject_Type ||
1266 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1267 if (type->tp_new == NULL)
1268 type->tp_new = base->tp_new;
1269 }
1270 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001271 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001272
1273 /* Copy other non-function slots */
1274
1275#undef COPYVAL
1276#define COPYVAL(SLOT) \
1277 if (type->SLOT == 0) type->SLOT = base->SLOT
1278
1279 COPYVAL(tp_itemsize);
1280 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1281 COPYVAL(tp_weaklistoffset);
1282 }
1283 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1284 COPYVAL(tp_dictoffset);
1285 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001286}
1287
1288static void
1289inherit_slots(PyTypeObject *type, PyTypeObject *base)
1290{
1291 PyTypeObject *basebase;
1292
1293#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294#undef COPYSLOT
1295#undef COPYNUM
1296#undef COPYSEQ
1297#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001298
1299#define SLOTDEFINED(SLOT) \
1300 (base->SLOT != 0 && \
1301 (basebase == NULL || base->SLOT != basebase->SLOT))
1302
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001304 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305
1306#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1307#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1308#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1309
Guido van Rossum13d52f02001-08-10 21:24:08 +00001310 /* This won't inherit indirect slots (from tp_as_number etc.)
1311 if type doesn't provide the space. */
1312
1313 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1314 basebase = base->tp_base;
1315 if (basebase->tp_as_number == NULL)
1316 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317 COPYNUM(nb_add);
1318 COPYNUM(nb_subtract);
1319 COPYNUM(nb_multiply);
1320 COPYNUM(nb_divide);
1321 COPYNUM(nb_remainder);
1322 COPYNUM(nb_divmod);
1323 COPYNUM(nb_power);
1324 COPYNUM(nb_negative);
1325 COPYNUM(nb_positive);
1326 COPYNUM(nb_absolute);
1327 COPYNUM(nb_nonzero);
1328 COPYNUM(nb_invert);
1329 COPYNUM(nb_lshift);
1330 COPYNUM(nb_rshift);
1331 COPYNUM(nb_and);
1332 COPYNUM(nb_xor);
1333 COPYNUM(nb_or);
1334 COPYNUM(nb_coerce);
1335 COPYNUM(nb_int);
1336 COPYNUM(nb_long);
1337 COPYNUM(nb_float);
1338 COPYNUM(nb_oct);
1339 COPYNUM(nb_hex);
1340 COPYNUM(nb_inplace_add);
1341 COPYNUM(nb_inplace_subtract);
1342 COPYNUM(nb_inplace_multiply);
1343 COPYNUM(nb_inplace_divide);
1344 COPYNUM(nb_inplace_remainder);
1345 COPYNUM(nb_inplace_power);
1346 COPYNUM(nb_inplace_lshift);
1347 COPYNUM(nb_inplace_rshift);
1348 COPYNUM(nb_inplace_and);
1349 COPYNUM(nb_inplace_xor);
1350 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001351 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1352 COPYNUM(nb_true_divide);
1353 COPYNUM(nb_floor_divide);
1354 COPYNUM(nb_inplace_true_divide);
1355 COPYNUM(nb_inplace_floor_divide);
1356 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357 }
1358
Guido van Rossum13d52f02001-08-10 21:24:08 +00001359 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1360 basebase = base->tp_base;
1361 if (basebase->tp_as_sequence == NULL)
1362 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001363 COPYSEQ(sq_length);
1364 COPYSEQ(sq_concat);
1365 COPYSEQ(sq_repeat);
1366 COPYSEQ(sq_item);
1367 COPYSEQ(sq_slice);
1368 COPYSEQ(sq_ass_item);
1369 COPYSEQ(sq_ass_slice);
1370 COPYSEQ(sq_contains);
1371 COPYSEQ(sq_inplace_concat);
1372 COPYSEQ(sq_inplace_repeat);
1373 }
1374
Guido van Rossum13d52f02001-08-10 21:24:08 +00001375 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1376 basebase = base->tp_base;
1377 if (basebase->tp_as_mapping == NULL)
1378 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001379 COPYMAP(mp_length);
1380 COPYMAP(mp_subscript);
1381 COPYMAP(mp_ass_subscript);
1382 }
1383
Guido van Rossum13d52f02001-08-10 21:24:08 +00001384 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386 COPYSLOT(tp_dealloc);
1387 COPYSLOT(tp_print);
1388 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1389 type->tp_getattr = base->tp_getattr;
1390 type->tp_getattro = base->tp_getattro;
1391 }
1392 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1393 type->tp_setattr = base->tp_setattr;
1394 type->tp_setattro = base->tp_setattro;
1395 }
1396 /* tp_compare see tp_richcompare */
1397 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001398 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001399 COPYSLOT(tp_call);
1400 COPYSLOT(tp_str);
1401 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001403 if (type->tp_compare == NULL &&
1404 type->tp_richcompare == NULL &&
1405 type->tp_hash == NULL)
1406 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 type->tp_compare = base->tp_compare;
1408 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001409 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410 }
1411 }
1412 else {
1413 COPYSLOT(tp_compare);
1414 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1416 COPYSLOT(tp_iter);
1417 COPYSLOT(tp_iternext);
1418 }
1419 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1420 COPYSLOT(tp_descr_get);
1421 COPYSLOT(tp_descr_set);
1422 COPYSLOT(tp_dictoffset);
1423 COPYSLOT(tp_init);
1424 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 COPYSLOT(tp_free);
1426 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001427}
1428
Guido van Rossum13d52f02001-08-10 21:24:08 +00001429staticforward int add_operators(PyTypeObject *);
1430
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001432PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433{
1434 PyObject *dict, *bases, *x;
1435 PyTypeObject *base;
1436 int i, n;
1437
Guido van Rossumd614f972001-08-10 17:39:49 +00001438 if (type->tp_flags & Py_TPFLAGS_READY) {
1439 assert(type->tp_dict != NULL);
1440 return 0;
1441 }
1442 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1443 assert(type->tp_dict == NULL);
1444
1445 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446
1447 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1448 base = type->tp_base;
1449 if (base == NULL && type != &PyBaseObject_Type)
1450 base = type->tp_base = &PyBaseObject_Type;
1451
1452 /* Initialize tp_bases */
1453 bases = type->tp_bases;
1454 if (bases == NULL) {
1455 if (base == NULL)
1456 bases = PyTuple_New(0);
1457 else
1458 bases = Py_BuildValue("(O)", base);
1459 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001460 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001461 type->tp_bases = bases;
1462 }
1463
1464 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001465 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001466 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001467 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468 }
1469
1470 /* Initialize tp_defined */
1471 dict = type->tp_defined;
1472 if (dict == NULL) {
1473 dict = PyDict_New();
1474 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001475 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 type->tp_defined = dict;
1477 }
1478
1479 /* Add type-specific descriptors to tp_defined */
1480 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001481 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482 if (type->tp_methods != NULL) {
1483 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001484 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001485 }
1486 if (type->tp_members != NULL) {
1487 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001488 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489 }
1490 if (type->tp_getset != NULL) {
1491 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001492 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001493 }
1494
1495 /* Temporarily make tp_dict the same object as tp_defined.
1496 (This is needed to call mro(), and can stay this way for
1497 dynamic types). */
1498 Py_INCREF(type->tp_defined);
1499 type->tp_dict = type->tp_defined;
1500
1501 /* Calculate method resolution order */
1502 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001503 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504 }
1505
Guido van Rossum13d52f02001-08-10 21:24:08 +00001506 /* Inherit special flags from dominant base */
1507 if (type->tp_base != NULL)
1508 inherit_special(type, type->tp_base);
1509
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001511 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001512 /* For a dynamic type, all slots are overridden */
1513 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001514 }
1515 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001517 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001519 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001521 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001522 bases = type->tp_mro;
1523 assert(bases != NULL);
1524 assert(PyTuple_Check(bases));
1525 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001526 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1528 assert(PyType_Check(base));
1529 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001530 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001531 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001532 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533 }
1534 }
1535
Guido van Rossum13d52f02001-08-10 21:24:08 +00001536 /* Some more special stuff */
1537 base = type->tp_base;
1538 if (base != NULL) {
1539 if (type->tp_as_number == NULL)
1540 type->tp_as_number = base->tp_as_number;
1541 if (type->tp_as_sequence == NULL)
1542 type->tp_as_sequence = base->tp_as_sequence;
1543 if (type->tp_as_mapping == NULL)
1544 type->tp_as_mapping = base->tp_as_mapping;
1545 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546
Guido van Rossum13d52f02001-08-10 21:24:08 +00001547 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001548 assert(type->tp_dict != NULL);
1549 type->tp_flags =
1550 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001552
1553 error:
1554 type->tp_flags &= ~Py_TPFLAGS_READYING;
1555 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556}
1557
1558
1559/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1560
1561/* There's a wrapper *function* for each distinct function typedef used
1562 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1563 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1564 Most tables have only one entry; the tables for binary operators have two
1565 entries, one regular and one with reversed arguments. */
1566
1567static PyObject *
1568wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1569{
1570 inquiry func = (inquiry)wrapped;
1571 int res;
1572
1573 if (!PyArg_ParseTuple(args, ""))
1574 return NULL;
1575 res = (*func)(self);
1576 if (res == -1 && PyErr_Occurred())
1577 return NULL;
1578 return PyInt_FromLong((long)res);
1579}
1580
1581static struct wrapperbase tab_len[] = {
1582 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1583 {0}
1584};
1585
1586static PyObject *
1587wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1588{
1589 binaryfunc func = (binaryfunc)wrapped;
1590 PyObject *other;
1591
1592 if (!PyArg_ParseTuple(args, "O", &other))
1593 return NULL;
1594 return (*func)(self, other);
1595}
1596
1597static PyObject *
1598wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1599{
1600 binaryfunc func = (binaryfunc)wrapped;
1601 PyObject *other;
1602
1603 if (!PyArg_ParseTuple(args, "O", &other))
1604 return NULL;
1605 return (*func)(other, self);
1606}
1607
1608#undef BINARY
1609#define BINARY(NAME, OP) \
1610static struct wrapperbase tab_##NAME[] = { \
1611 {"__" #NAME "__", \
1612 (wrapperfunc)wrap_binaryfunc, \
1613 "x.__" #NAME "__(y) <==> " #OP}, \
1614 {"__r" #NAME "__", \
1615 (wrapperfunc)wrap_binaryfunc_r, \
1616 "y.__r" #NAME "__(x) <==> " #OP}, \
1617 {0} \
1618}
1619
1620BINARY(add, "x+y");
1621BINARY(sub, "x-y");
1622BINARY(mul, "x*y");
1623BINARY(div, "x/y");
1624BINARY(mod, "x%y");
1625BINARY(divmod, "divmod(x,y)");
1626BINARY(lshift, "x<<y");
1627BINARY(rshift, "x>>y");
1628BINARY(and, "x&y");
1629BINARY(xor, "x^y");
1630BINARY(or, "x|y");
1631
1632static PyObject *
1633wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1634{
1635 ternaryfunc func = (ternaryfunc)wrapped;
1636 PyObject *other;
1637 PyObject *third = Py_None;
1638
1639 /* Note: This wrapper only works for __pow__() */
1640
1641 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1642 return NULL;
1643 return (*func)(self, other, third);
1644}
1645
1646#undef TERNARY
1647#define TERNARY(NAME, OP) \
1648static struct wrapperbase tab_##NAME[] = { \
1649 {"__" #NAME "__", \
1650 (wrapperfunc)wrap_ternaryfunc, \
1651 "x.__" #NAME "__(y, z) <==> " #OP}, \
1652 {"__r" #NAME "__", \
1653 (wrapperfunc)wrap_ternaryfunc, \
1654 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1655 {0} \
1656}
1657
1658TERNARY(pow, "(x**y) % z");
1659
1660#undef UNARY
1661#define UNARY(NAME, OP) \
1662static struct wrapperbase tab_##NAME[] = { \
1663 {"__" #NAME "__", \
1664 (wrapperfunc)wrap_unaryfunc, \
1665 "x.__" #NAME "__() <==> " #OP}, \
1666 {0} \
1667}
1668
1669static PyObject *
1670wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1671{
1672 unaryfunc func = (unaryfunc)wrapped;
1673
1674 if (!PyArg_ParseTuple(args, ""))
1675 return NULL;
1676 return (*func)(self);
1677}
1678
1679UNARY(neg, "-x");
1680UNARY(pos, "+x");
1681UNARY(abs, "abs(x)");
1682UNARY(nonzero, "x != 0");
1683UNARY(invert, "~x");
1684UNARY(int, "int(x)");
1685UNARY(long, "long(x)");
1686UNARY(float, "float(x)");
1687UNARY(oct, "oct(x)");
1688UNARY(hex, "hex(x)");
1689
1690#undef IBINARY
1691#define IBINARY(NAME, OP) \
1692static struct wrapperbase tab_##NAME[] = { \
1693 {"__" #NAME "__", \
1694 (wrapperfunc)wrap_binaryfunc, \
1695 "x.__" #NAME "__(y) <==> " #OP}, \
1696 {0} \
1697}
1698
1699IBINARY(iadd, "x+=y");
1700IBINARY(isub, "x-=y");
1701IBINARY(imul, "x*=y");
1702IBINARY(idiv, "x/=y");
1703IBINARY(imod, "x%=y");
1704IBINARY(ilshift, "x<<=y");
1705IBINARY(irshift, "x>>=y");
1706IBINARY(iand, "x&=y");
1707IBINARY(ixor, "x^=y");
1708IBINARY(ior, "x|=y");
1709
1710#undef ITERNARY
1711#define ITERNARY(NAME, OP) \
1712static struct wrapperbase tab_##NAME[] = { \
1713 {"__" #NAME "__", \
1714 (wrapperfunc)wrap_ternaryfunc, \
1715 "x.__" #NAME "__(y) <==> " #OP}, \
1716 {0} \
1717}
1718
1719ITERNARY(ipow, "x = (x**y) % z");
1720
1721static struct wrapperbase tab_getitem[] = {
1722 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1723 "x.__getitem__(y) <==> x[y]"},
1724 {0}
1725};
1726
1727static PyObject *
1728wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1729{
1730 intargfunc func = (intargfunc)wrapped;
1731 int i;
1732
1733 if (!PyArg_ParseTuple(args, "i", &i))
1734 return NULL;
1735 return (*func)(self, i);
1736}
1737
1738static struct wrapperbase tab_mul_int[] = {
1739 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1740 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1741 {0}
1742};
1743
1744static struct wrapperbase tab_concat[] = {
1745 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1746 {0}
1747};
1748
1749static struct wrapperbase tab_imul_int[] = {
1750 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1751 {0}
1752};
1753
Guido van Rossum5d815f32001-08-17 21:57:47 +00001754static int
1755getindex(PyObject *self, PyObject *arg)
1756{
1757 int i;
1758
1759 i = PyInt_AsLong(arg);
1760 if (i == -1 && PyErr_Occurred())
1761 return -1;
1762 if (i < 0) {
1763 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1764 if (sq && sq->sq_length) {
1765 int n = (*sq->sq_length)(self);
1766 if (n < 0)
1767 return -1;
1768 i += n;
1769 }
1770 }
1771 return i;
1772}
1773
1774static PyObject *
1775wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1776{
1777 intargfunc func = (intargfunc)wrapped;
1778 PyObject *arg;
1779 int i;
1780
1781 if (!PyArg_ParseTuple(args, "O", &arg))
1782 return NULL;
1783 i = getindex(self, arg);
1784 if (i == -1 && PyErr_Occurred())
1785 return NULL;
1786 return (*func)(self, i);
1787}
1788
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001790 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791 "x.__getitem__(i) <==> x[i]"},
1792 {0}
1793};
1794
1795static PyObject *
1796wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1797{
1798 intintargfunc func = (intintargfunc)wrapped;
1799 int i, j;
1800
1801 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1802 return NULL;
1803 return (*func)(self, i, j);
1804}
1805
1806static struct wrapperbase tab_getslice[] = {
1807 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1808 "x.__getslice__(i, j) <==> x[i:j]"},
1809 {0}
1810};
1811
1812static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001813wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001814{
1815 intobjargproc func = (intobjargproc)wrapped;
1816 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001817 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001818
Guido van Rossum5d815f32001-08-17 21:57:47 +00001819 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1820 return NULL;
1821 i = getindex(self, arg);
1822 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 return NULL;
1824 res = (*func)(self, i, value);
1825 if (res == -1 && PyErr_Occurred())
1826 return NULL;
1827 Py_INCREF(Py_None);
1828 return Py_None;
1829}
1830
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001831static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001832wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001833{
1834 intobjargproc func = (intobjargproc)wrapped;
1835 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001836 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001837
Guido van Rossum5d815f32001-08-17 21:57:47 +00001838 if (!PyArg_ParseTuple(args, "O", &arg))
1839 return NULL;
1840 i = getindex(self, arg);
1841 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001842 return NULL;
1843 res = (*func)(self, i, NULL);
1844 if (res == -1 && PyErr_Occurred())
1845 return NULL;
1846 Py_INCREF(Py_None);
1847 return Py_None;
1848}
1849
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001851 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00001853 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001854 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 {0}
1856};
1857
1858static PyObject *
1859wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1860{
1861 intintobjargproc func = (intintobjargproc)wrapped;
1862 int i, j, res;
1863 PyObject *value;
1864
1865 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1866 return NULL;
1867 res = (*func)(self, i, j, value);
1868 if (res == -1 && PyErr_Occurred())
1869 return NULL;
1870 Py_INCREF(Py_None);
1871 return Py_None;
1872}
1873
1874static struct wrapperbase tab_setslice[] = {
1875 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1876 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1877 {0}
1878};
1879
1880/* XXX objobjproc is a misnomer; should be objargpred */
1881static PyObject *
1882wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1883{
1884 objobjproc func = (objobjproc)wrapped;
1885 int res;
1886 PyObject *value;
1887
1888 if (!PyArg_ParseTuple(args, "O", &value))
1889 return NULL;
1890 res = (*func)(self, value);
1891 if (res == -1 && PyErr_Occurred())
1892 return NULL;
1893 return PyInt_FromLong((long)res);
1894}
1895
1896static struct wrapperbase tab_contains[] = {
1897 {"__contains__", (wrapperfunc)wrap_objobjproc,
1898 "x.__contains__(y) <==> y in x"},
1899 {0}
1900};
1901
1902static PyObject *
1903wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1904{
1905 objobjargproc func = (objobjargproc)wrapped;
1906 int res;
1907 PyObject *key, *value;
1908
1909 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1910 return NULL;
1911 res = (*func)(self, key, value);
1912 if (res == -1 && PyErr_Occurred())
1913 return NULL;
1914 Py_INCREF(Py_None);
1915 return Py_None;
1916}
1917
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001918static PyObject *
1919wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1920{
1921 objobjargproc func = (objobjargproc)wrapped;
1922 int res;
1923 PyObject *key;
1924
1925 if (!PyArg_ParseTuple(args, "O", &key))
1926 return NULL;
1927 res = (*func)(self, key, NULL);
1928 if (res == -1 && PyErr_Occurred())
1929 return NULL;
1930 Py_INCREF(Py_None);
1931 return Py_None;
1932}
1933
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934static struct wrapperbase tab_setitem[] = {
1935 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1936 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001937 {"__delitem__", (wrapperfunc)wrap_delitem,
1938 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001939 {0}
1940};
1941
1942static PyObject *
1943wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1944{
1945 cmpfunc func = (cmpfunc)wrapped;
1946 int res;
1947 PyObject *other;
1948
1949 if (!PyArg_ParseTuple(args, "O", &other))
1950 return NULL;
1951 res = (*func)(self, other);
1952 if (PyErr_Occurred())
1953 return NULL;
1954 return PyInt_FromLong((long)res);
1955}
1956
1957static struct wrapperbase tab_cmp[] = {
1958 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1959 "x.__cmp__(y) <==> cmp(x,y)"},
1960 {0}
1961};
1962
1963static struct wrapperbase tab_repr[] = {
1964 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1965 "x.__repr__() <==> repr(x)"},
1966 {0}
1967};
1968
1969static struct wrapperbase tab_getattr[] = {
1970 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1971 "x.__getattr__('name') <==> x.name"},
1972 {0}
1973};
1974
1975static PyObject *
1976wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1977{
1978 setattrofunc func = (setattrofunc)wrapped;
1979 int res;
1980 PyObject *name, *value;
1981
1982 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1983 return NULL;
1984 res = (*func)(self, name, value);
1985 if (res < 0)
1986 return NULL;
1987 Py_INCREF(Py_None);
1988 return Py_None;
1989}
1990
1991static PyObject *
1992wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1993{
1994 setattrofunc func = (setattrofunc)wrapped;
1995 int res;
1996 PyObject *name;
1997
1998 if (!PyArg_ParseTuple(args, "O", &name))
1999 return NULL;
2000 res = (*func)(self, name, NULL);
2001 if (res < 0)
2002 return NULL;
2003 Py_INCREF(Py_None);
2004 return Py_None;
2005}
2006
2007static struct wrapperbase tab_setattr[] = {
2008 {"__setattr__", (wrapperfunc)wrap_setattr,
2009 "x.__setattr__('name', value) <==> x.name = value"},
2010 {"__delattr__", (wrapperfunc)wrap_delattr,
2011 "x.__delattr__('name') <==> del x.name"},
2012 {0}
2013};
2014
2015static PyObject *
2016wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2017{
2018 hashfunc func = (hashfunc)wrapped;
2019 long res;
2020
2021 if (!PyArg_ParseTuple(args, ""))
2022 return NULL;
2023 res = (*func)(self);
2024 if (res == -1 && PyErr_Occurred())
2025 return NULL;
2026 return PyInt_FromLong(res);
2027}
2028
2029static struct wrapperbase tab_hash[] = {
2030 {"__hash__", (wrapperfunc)wrap_hashfunc,
2031 "x.__hash__() <==> hash(x)"},
2032 {0}
2033};
2034
2035static PyObject *
2036wrap_call(PyObject *self, PyObject *args, void *wrapped)
2037{
2038 ternaryfunc func = (ternaryfunc)wrapped;
2039
2040 /* XXX What about keyword arguments? */
2041 return (*func)(self, args, NULL);
2042}
2043
2044static struct wrapperbase tab_call[] = {
2045 {"__call__", (wrapperfunc)wrap_call,
2046 "x.__call__(...) <==> x(...)"},
2047 {0}
2048};
2049
2050static struct wrapperbase tab_str[] = {
2051 {"__str__", (wrapperfunc)wrap_unaryfunc,
2052 "x.__str__() <==> str(x)"},
2053 {0}
2054};
2055
2056static PyObject *
2057wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2058{
2059 richcmpfunc func = (richcmpfunc)wrapped;
2060 PyObject *other;
2061
2062 if (!PyArg_ParseTuple(args, "O", &other))
2063 return NULL;
2064 return (*func)(self, other, op);
2065}
2066
2067#undef RICHCMP_WRAPPER
2068#define RICHCMP_WRAPPER(NAME, OP) \
2069static PyObject * \
2070richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2071{ \
2072 return wrap_richcmpfunc(self, args, wrapped, OP); \
2073}
2074
Jack Jansen8e938b42001-08-08 15:29:49 +00002075RICHCMP_WRAPPER(lt, Py_LT)
2076RICHCMP_WRAPPER(le, Py_LE)
2077RICHCMP_WRAPPER(eq, Py_EQ)
2078RICHCMP_WRAPPER(ne, Py_NE)
2079RICHCMP_WRAPPER(gt, Py_GT)
2080RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002081
2082#undef RICHCMP_ENTRY
2083#define RICHCMP_ENTRY(NAME, EXPR) \
2084 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2085 "x.__" #NAME "__(y) <==> " EXPR}
2086
2087static struct wrapperbase tab_richcmp[] = {
2088 RICHCMP_ENTRY(lt, "x<y"),
2089 RICHCMP_ENTRY(le, "x<=y"),
2090 RICHCMP_ENTRY(eq, "x==y"),
2091 RICHCMP_ENTRY(ne, "x!=y"),
2092 RICHCMP_ENTRY(gt, "x>y"),
2093 RICHCMP_ENTRY(ge, "x>=y"),
2094 {0}
2095};
2096
2097static struct wrapperbase tab_iter[] = {
2098 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2099 {0}
2100};
2101
2102static PyObject *
2103wrap_next(PyObject *self, PyObject *args, void *wrapped)
2104{
2105 unaryfunc func = (unaryfunc)wrapped;
2106 PyObject *res;
2107
2108 if (!PyArg_ParseTuple(args, ""))
2109 return NULL;
2110 res = (*func)(self);
2111 if (res == NULL && !PyErr_Occurred())
2112 PyErr_SetNone(PyExc_StopIteration);
2113 return res;
2114}
2115
2116static struct wrapperbase tab_next[] = {
2117 {"next", (wrapperfunc)wrap_next,
2118 "x.next() -> the next value, or raise StopIteration"},
2119 {0}
2120};
2121
2122static PyObject *
2123wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2124{
2125 descrgetfunc func = (descrgetfunc)wrapped;
2126 PyObject *obj;
2127 PyObject *type = NULL;
2128
2129 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2130 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002131 return (*func)(self, obj, type);
2132}
2133
2134static struct wrapperbase tab_descr_get[] = {
2135 {"__get__", (wrapperfunc)wrap_descr_get,
2136 "descr.__get__(obj, type) -> value"},
2137 {0}
2138};
2139
2140static PyObject *
2141wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2142{
2143 descrsetfunc func = (descrsetfunc)wrapped;
2144 PyObject *obj, *value;
2145 int ret;
2146
2147 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2148 return NULL;
2149 ret = (*func)(self, obj, value);
2150 if (ret < 0)
2151 return NULL;
2152 Py_INCREF(Py_None);
2153 return Py_None;
2154}
2155
2156static struct wrapperbase tab_descr_set[] = {
2157 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2158 "descr.__set__(obj, value)"},
2159 {0}
2160};
2161
2162static PyObject *
2163wrap_init(PyObject *self, PyObject *args, void *wrapped)
2164{
2165 initproc func = (initproc)wrapped;
2166
2167 /* XXX What about keyword arguments? */
2168 if (func(self, args, NULL) < 0)
2169 return NULL;
2170 Py_INCREF(Py_None);
2171 return Py_None;
2172}
2173
2174static struct wrapperbase tab_init[] = {
2175 {"__init__", (wrapperfunc)wrap_init,
2176 "x.__init__(...) initializes x; "
2177 "see x.__type__.__doc__ for signature"},
2178 {0}
2179};
2180
2181static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002182tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183{
Barry Warsaw60f01882001-08-22 19:24:42 +00002184 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002185 PyObject *arg0, *res;
2186
2187 if (self == NULL || !PyType_Check(self))
2188 Py_FatalError("__new__() called with non-type 'self'");
2189 type = (PyTypeObject *)self;
2190 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002191 PyErr_Format(PyExc_TypeError,
2192 "%s.__new__(): not enough arguments",
2193 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002194 return NULL;
2195 }
2196 arg0 = PyTuple_GET_ITEM(args, 0);
2197 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002198 PyErr_Format(PyExc_TypeError,
2199 "%s.__new__(X): X is not a type object (%s)",
2200 type->tp_name,
2201 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002202 return NULL;
2203 }
2204 subtype = (PyTypeObject *)arg0;
2205 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002206 PyErr_Format(PyExc_TypeError,
2207 "%s.__new__(%s): %s is not a subtype of %s",
2208 type->tp_name,
2209 subtype->tp_name,
2210 subtype->tp_name,
2211 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002212 return NULL;
2213 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002214
2215 /* Check that the use doesn't do something silly and unsafe like
2216 object.__new__(dictionary). To do this, we check that the
2217 most derived base that's not a heap type is this type. */
2218 staticbase = subtype;
2219 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2220 staticbase = staticbase->tp_base;
2221 if (staticbase != type) {
2222 PyErr_Format(PyExc_TypeError,
2223 "%s.__new__(%s) is not safe, use %s.__new__()",
2224 type->tp_name,
2225 subtype->tp_name,
2226 staticbase == NULL ? "?" : staticbase->tp_name);
2227 return NULL;
2228 }
2229
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002230 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2231 if (args == NULL)
2232 return NULL;
2233 res = type->tp_new(subtype, args, kwds);
2234 Py_DECREF(args);
2235 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002236}
2237
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002238static struct PyMethodDef tp_new_methoddef[] = {
2239 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2240 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241 {0}
2242};
2243
2244static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002245add_tp_new_wrapper(PyTypeObject *type)
2246{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002247 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002248
Guido van Rossumf040ede2001-08-07 16:40:56 +00002249 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2250 return 0;
2251 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002252 if (func == NULL)
2253 return -1;
2254 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2255}
2256
Guido van Rossum13d52f02001-08-10 21:24:08 +00002257static int
2258add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2259{
2260 PyObject *dict = type->tp_defined;
2261
2262 for (; wraps->name != NULL; wraps++) {
2263 PyObject *descr;
2264 if (PyDict_GetItemString(dict, wraps->name))
2265 continue;
2266 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2267 if (descr == NULL)
2268 return -1;
2269 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2270 return -1;
2271 Py_DECREF(descr);
2272 }
2273 return 0;
2274}
2275
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002276/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002277 dictionary with method descriptors for function slots. For each
2278 function slot (like tp_repr) that's defined in the type, one or
2279 more corresponding descriptors are added in the type's tp_defined
2280 dictionary under the appropriate name (like __repr__). Some
2281 function slots cause more than one descriptor to be added (for
2282 example, the nb_add slot adds both __add__ and __radd__
2283 descriptors) and some function slots compete for the same
2284 descriptor (for example both sq_item and mp_subscript generate a
2285 __getitem__ descriptor). This only adds new descriptors and
2286 doesn't overwrite entries in tp_defined that were previously
2287 defined. The descriptors contain a reference to the C function
2288 they must call, so that it's safe if they are copied into a
2289 subtype's __dict__ and the subtype has a different C function in
2290 its slot -- calling the method defined by the descriptor will call
2291 the C function that was used to create it, rather than the C
2292 function present in the slot when it is called. (This is important
2293 because a subtype may have a C function in the slot that calls the
2294 method from the dictionary, and we want to avoid infinite recursion
2295 here.) */
2296
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002297static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298add_operators(PyTypeObject *type)
2299{
2300 PySequenceMethods *sq;
2301 PyMappingMethods *mp;
2302 PyNumberMethods *nb;
2303
2304#undef ADD
2305#define ADD(SLOT, TABLE) \
2306 if (SLOT) { \
2307 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2308 return -1; \
2309 }
2310
2311 if ((sq = type->tp_as_sequence) != NULL) {
2312 ADD(sq->sq_length, tab_len);
2313 ADD(sq->sq_concat, tab_concat);
2314 ADD(sq->sq_repeat, tab_mul_int);
2315 ADD(sq->sq_item, tab_getitem_int);
2316 ADD(sq->sq_slice, tab_getslice);
2317 ADD(sq->sq_ass_item, tab_setitem_int);
2318 ADD(sq->sq_ass_slice, tab_setslice);
2319 ADD(sq->sq_contains, tab_contains);
2320 ADD(sq->sq_inplace_concat, tab_iadd);
2321 ADD(sq->sq_inplace_repeat, tab_imul_int);
2322 }
2323
2324 if ((mp = type->tp_as_mapping) != NULL) {
2325 if (sq->sq_length == NULL)
2326 ADD(mp->mp_length, tab_len);
2327 ADD(mp->mp_subscript, tab_getitem);
2328 ADD(mp->mp_ass_subscript, tab_setitem);
2329 }
2330
2331 /* We don't support "old-style numbers" because their binary
2332 operators require that both arguments have the same type;
2333 the wrappers here only work for new-style numbers. */
2334 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2335 (nb = type->tp_as_number) != NULL) {
2336 ADD(nb->nb_add, tab_add);
2337 ADD(nb->nb_subtract, tab_sub);
2338 ADD(nb->nb_multiply, tab_mul);
2339 ADD(nb->nb_divide, tab_div);
2340 ADD(nb->nb_remainder, tab_mod);
2341 ADD(nb->nb_divmod, tab_divmod);
2342 ADD(nb->nb_power, tab_pow);
2343 ADD(nb->nb_negative, tab_neg);
2344 ADD(nb->nb_positive, tab_pos);
2345 ADD(nb->nb_absolute, tab_abs);
2346 ADD(nb->nb_nonzero, tab_nonzero);
2347 ADD(nb->nb_invert, tab_invert);
2348 ADD(nb->nb_lshift, tab_lshift);
2349 ADD(nb->nb_rshift, tab_rshift);
2350 ADD(nb->nb_and, tab_and);
2351 ADD(nb->nb_xor, tab_xor);
2352 ADD(nb->nb_or, tab_or);
2353 /* We don't support coerce() -- see above comment */
2354 ADD(nb->nb_int, tab_int);
2355 ADD(nb->nb_long, tab_long);
2356 ADD(nb->nb_float, tab_float);
2357 ADD(nb->nb_oct, tab_oct);
2358 ADD(nb->nb_hex, tab_hex);
2359 ADD(nb->nb_inplace_add, tab_iadd);
2360 ADD(nb->nb_inplace_subtract, tab_isub);
2361 ADD(nb->nb_inplace_multiply, tab_imul);
2362 ADD(nb->nb_inplace_divide, tab_idiv);
2363 ADD(nb->nb_inplace_remainder, tab_imod);
2364 ADD(nb->nb_inplace_power, tab_ipow);
2365 ADD(nb->nb_inplace_lshift, tab_ilshift);
2366 ADD(nb->nb_inplace_rshift, tab_irshift);
2367 ADD(nb->nb_inplace_and, tab_iand);
2368 ADD(nb->nb_inplace_xor, tab_ixor);
2369 ADD(nb->nb_inplace_or, tab_ior);
2370 }
2371
2372 ADD(type->tp_getattro, tab_getattr);
2373 ADD(type->tp_setattro, tab_setattr);
2374 ADD(type->tp_compare, tab_cmp);
2375 ADD(type->tp_repr, tab_repr);
2376 ADD(type->tp_hash, tab_hash);
2377 ADD(type->tp_call, tab_call);
2378 ADD(type->tp_str, tab_str);
2379 ADD(type->tp_richcompare, tab_richcmp);
2380 ADD(type->tp_iter, tab_iter);
2381 ADD(type->tp_iternext, tab_next);
2382 ADD(type->tp_descr_get, tab_descr_get);
2383 ADD(type->tp_descr_set, tab_descr_set);
2384 ADD(type->tp_init, tab_init);
2385
Guido van Rossumf040ede2001-08-07 16:40:56 +00002386 if (type->tp_new != NULL) {
2387 if (add_tp_new_wrapper(type) < 0)
2388 return -1;
2389 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390
2391 return 0;
2392}
2393
Guido van Rossumf040ede2001-08-07 16:40:56 +00002394/* Slot wrappers that call the corresponding __foo__ slot. See comments
2395 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002396
Guido van Rossumdc91b992001-08-08 22:26:22 +00002397#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002399FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002400{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002401 static PyObject *cache_str; \
Guido van Rossum2730b132001-08-28 18:22:14 +00002402 return call_method(self, OPSTR, &cache_str, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002403}
2404
Guido van Rossumdc91b992001-08-08 22:26:22 +00002405#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002406static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002407FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002409 static PyObject *cache_str; \
2410 return call_method(self, OPSTR, &cache_str, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411}
2412
Guido van Rossumdc91b992001-08-08 22:26:22 +00002413
2414#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002415static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002416FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002418 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002419 if (self->ob_type->tp_as_number != NULL && \
2420 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2421 PyObject *r; \
Guido van Rossum2730b132001-08-28 18:22:14 +00002422 r = call_method( \
2423 self, OPSTR, &cache_str, "O", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002424 if (r != Py_NotImplemented || \
2425 other->ob_type == self->ob_type) \
2426 return r; \
2427 Py_DECREF(r); \
2428 } \
2429 if (other->ob_type->tp_as_number != NULL && \
2430 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossum2730b132001-08-28 18:22:14 +00002431 return call_method( \
2432 other, ROPSTR, &rcache_str, "O", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002433 } \
2434 Py_INCREF(Py_NotImplemented); \
2435 return Py_NotImplemented; \
2436}
2437
2438#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2439 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2440
2441#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2442static PyObject * \
2443FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2444{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002445 static PyObject *cache_str; \
2446 return call_method(self, OPSTR, &cache_str, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002447}
2448
2449static int
2450slot_sq_length(PyObject *self)
2451{
Guido van Rossum2730b132001-08-28 18:22:14 +00002452 static PyObject *len_str;
2453 PyObject *res = call_method(self, "__len__", &len_str, "");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454
2455 if (res == NULL)
2456 return -1;
2457 return (int)PyInt_AsLong(res);
2458}
2459
Guido van Rossumdc91b992001-08-08 22:26:22 +00002460SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2461SLOT1(slot_sq_repeat, "__mul__", int, "i")
2462SLOT1(slot_sq_item, "__getitem__", int, "i")
2463SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002464
2465static int
2466slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2467{
2468 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002469 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002470
2471 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002472 res = call_method(self, "__delitem__", &delitem_str,
2473 "i", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002474 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002475 res = call_method(self, "__setitem__", &setitem_str,
2476 "iO", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477 if (res == NULL)
2478 return -1;
2479 Py_DECREF(res);
2480 return 0;
2481}
2482
2483static int
2484slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2485{
2486 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002487 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002488
2489 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002490 res = call_method(self, "__delslice__", &delslice_str,
2491 "ii", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002492 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002493 res = call_method(self, "__setslice__", &setslice_str,
2494 "iiO", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002495 if (res == NULL)
2496 return -1;
2497 Py_DECREF(res);
2498 return 0;
2499}
2500
2501static int
2502slot_sq_contains(PyObject *self, PyObject *value)
2503{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002504 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002505 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002506
Guido van Rossum60718732001-08-28 17:47:51 +00002507 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002508
2509 if (func != NULL) {
2510 args = Py_BuildValue("(O)", value);
2511 if (args == NULL)
2512 res = NULL;
2513 else {
2514 res = PyEval_CallObject(func, args);
2515 Py_DECREF(args);
2516 }
2517 Py_DECREF(func);
2518 if (res == NULL)
2519 return -1;
2520 return PyObject_IsTrue(res);
2521 }
2522 else {
2523 PyErr_Clear();
2524 return _PySequence_IterContains(self, value);
2525 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002526}
2527
Guido van Rossumdc91b992001-08-08 22:26:22 +00002528SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2529SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530
2531#define slot_mp_length slot_sq_length
2532
Guido van Rossumdc91b992001-08-08 22:26:22 +00002533SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002534
2535static int
2536slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2537{
2538 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002539 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002540
2541 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002542 res = call_method(self, "__delitem__", &delitem_str,
2543 "O", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002544 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002545 res = call_method(self, "__setitem__", &setitem_str,
2546 "OO", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002547 if (res == NULL)
2548 return -1;
2549 Py_DECREF(res);
2550 return 0;
2551}
2552
Guido van Rossumdc91b992001-08-08 22:26:22 +00002553SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2554SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2555SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2556SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2557SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2558SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2559
2560staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2561
2562SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2563 nb_power, "__pow__", "__rpow__")
2564
2565static PyObject *
2566slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2567{
Guido van Rossum2730b132001-08-28 18:22:14 +00002568 static PyObject *pow_str;
2569
Guido van Rossumdc91b992001-08-08 22:26:22 +00002570 if (modulus == Py_None)
2571 return slot_nb_power_binary(self, other);
2572 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002573 return call_method(self, "__pow__", &pow_str,
2574 "OO", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002575}
2576
2577SLOT0(slot_nb_negative, "__neg__")
2578SLOT0(slot_nb_positive, "__pos__")
2579SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580
2581static int
2582slot_nb_nonzero(PyObject *self)
2583{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002584 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002585 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586
Guido van Rossum60718732001-08-28 17:47:51 +00002587 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002588 if (func == NULL) {
2589 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002590 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002591 }
2592
2593 if (func != NULL) {
2594 res = PyEval_CallObject(func, NULL);
2595 Py_DECREF(func);
2596 if (res == NULL)
2597 return -1;
2598 return PyObject_IsTrue(res);
2599 }
2600 else {
2601 PyErr_Clear();
2602 return 1;
2603 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604}
2605
Guido van Rossumdc91b992001-08-08 22:26:22 +00002606SLOT0(slot_nb_invert, "__invert__")
2607SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2608SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2609SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2610SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2611SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002612/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002613SLOT0(slot_nb_int, "__int__")
2614SLOT0(slot_nb_long, "__long__")
2615SLOT0(slot_nb_float, "__float__")
2616SLOT0(slot_nb_oct, "__oct__")
2617SLOT0(slot_nb_hex, "__hex__")
2618SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2619SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2620SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2621SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2622SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2623SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2624SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2625SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2626SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2627SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2628SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2629SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2630 "__floordiv__", "__rfloordiv__")
2631SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2632SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2633SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002634
2635static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002636half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002637{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002638 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002639 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002640 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002641
Guido van Rossum60718732001-08-28 17:47:51 +00002642 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002643 if (func == NULL) {
2644 PyErr_Clear();
2645 }
2646 else {
2647 args = Py_BuildValue("(O)", other);
2648 if (args == NULL)
2649 res = NULL;
2650 else {
2651 res = PyObject_CallObject(func, args);
2652 Py_DECREF(args);
2653 }
2654 if (res != Py_NotImplemented) {
2655 if (res == NULL)
2656 return -2;
2657 c = PyInt_AsLong(res);
2658 Py_DECREF(res);
2659 if (c == -1 && PyErr_Occurred())
2660 return -2;
2661 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2662 }
2663 Py_DECREF(res);
2664 }
2665 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666}
2667
Guido van Rossumb8f63662001-08-15 23:57:02 +00002668static int
2669slot_tp_compare(PyObject *self, PyObject *other)
2670{
2671 int c;
2672
2673 if (self->ob_type->tp_compare == slot_tp_compare) {
2674 c = half_compare(self, other);
2675 if (c <= 1)
2676 return c;
2677 }
2678 if (other->ob_type->tp_compare == slot_tp_compare) {
2679 c = half_compare(other, self);
2680 if (c < -1)
2681 return -2;
2682 if (c <= 1)
2683 return -c;
2684 }
2685 return (void *)self < (void *)other ? -1 :
2686 (void *)self > (void *)other ? 1 : 0;
2687}
2688
2689static PyObject *
2690slot_tp_repr(PyObject *self)
2691{
2692 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002693 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002694
Guido van Rossum60718732001-08-28 17:47:51 +00002695 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002696 if (func != NULL) {
2697 res = PyEval_CallObject(func, NULL);
2698 Py_DECREF(func);
2699 return res;
2700 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002701 PyErr_Clear();
2702 return PyString_FromFormat("<%s object at %p>",
2703 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002704}
2705
2706static PyObject *
2707slot_tp_str(PyObject *self)
2708{
2709 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002710 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002711
Guido van Rossum60718732001-08-28 17:47:51 +00002712 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002713 if (func != NULL) {
2714 res = PyEval_CallObject(func, NULL);
2715 Py_DECREF(func);
2716 return res;
2717 }
2718 else {
2719 PyErr_Clear();
2720 return slot_tp_repr(self);
2721 }
2722}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723
2724static long
2725slot_tp_hash(PyObject *self)
2726{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002727 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002728 static PyObject *hash_str, *eq_str, *cmp_str;
2729
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730 long h;
2731
Guido van Rossum60718732001-08-28 17:47:51 +00002732 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002733
2734 if (func != NULL) {
2735 res = PyEval_CallObject(func, NULL);
2736 Py_DECREF(func);
2737 if (res == NULL)
2738 return -1;
2739 h = PyInt_AsLong(res);
2740 }
2741 else {
2742 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002743 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002744 if (func == NULL) {
2745 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002746 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002747 }
2748 if (func != NULL) {
2749 Py_DECREF(func);
2750 PyErr_SetString(PyExc_TypeError, "unhashable type");
2751 return -1;
2752 }
2753 PyErr_Clear();
2754 h = _Py_HashPointer((void *)self);
2755 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756 if (h == -1 && !PyErr_Occurred())
2757 h = -2;
2758 return h;
2759}
2760
2761static PyObject *
2762slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2763{
Guido van Rossum60718732001-08-28 17:47:51 +00002764 static PyObject *call_str;
2765 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766 PyObject *res;
2767
2768 if (meth == NULL)
2769 return NULL;
2770 res = PyObject_Call(meth, args, kwds);
2771 Py_DECREF(meth);
2772 return res;
2773}
2774
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775static PyObject *
2776slot_tp_getattro(PyObject *self, PyObject *name)
2777{
2778 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002780 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002781
Guido van Rossum8e248182001-08-12 05:17:56 +00002782 if (getattr_str == NULL) {
2783 getattr_str = PyString_InternFromString("__getattr__");
2784 if (getattr_str == NULL)
2785 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002787 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002788 if (getattr == NULL) {
2789 /* Avoid further slowdowns */
2790 if (tp->tp_getattro == slot_tp_getattro)
2791 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002792 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002793 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 return PyObject_CallFunction(getattr, "OO", self, name);
2795}
2796
2797static int
2798slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2799{
2800 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002801 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002802
2803 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002804 res = call_method(self, "__delattr__", &delattr_str,
2805 "O", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002806 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002807 res = call_method(self, "__setattr__", &setattr_str,
2808 "OO", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002809 if (res == NULL)
2810 return -1;
2811 Py_DECREF(res);
2812 return 0;
2813}
2814
2815/* Map rich comparison operators to their __xx__ namesakes */
2816static char *name_op[] = {
2817 "__lt__",
2818 "__le__",
2819 "__eq__",
2820 "__ne__",
2821 "__gt__",
2822 "__ge__",
2823};
2824
2825static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002826half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002827{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002828 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002829 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830
Guido van Rossum60718732001-08-28 17:47:51 +00002831 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002832 if (func == NULL) {
2833 PyErr_Clear();
2834 Py_INCREF(Py_NotImplemented);
2835 return Py_NotImplemented;
2836 }
2837 args = Py_BuildValue("(O)", other);
2838 if (args == NULL)
2839 res = NULL;
2840 else {
2841 res = PyObject_CallObject(func, args);
2842 Py_DECREF(args);
2843 }
2844 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002845 return res;
2846}
2847
Guido van Rossumb8f63662001-08-15 23:57:02 +00002848/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2849static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2850
2851static PyObject *
2852slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2853{
2854 PyObject *res;
2855
2856 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2857 res = half_richcompare(self, other, op);
2858 if (res != Py_NotImplemented)
2859 return res;
2860 Py_DECREF(res);
2861 }
2862 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2863 res = half_richcompare(other, self, swapped_op[op]);
2864 if (res != Py_NotImplemented) {
2865 return res;
2866 }
2867 Py_DECREF(res);
2868 }
2869 Py_INCREF(Py_NotImplemented);
2870 return Py_NotImplemented;
2871}
2872
2873static PyObject *
2874slot_tp_iter(PyObject *self)
2875{
2876 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002877 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002878
Guido van Rossum60718732001-08-28 17:47:51 +00002879 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002880 if (func != NULL) {
2881 res = PyObject_CallObject(func, NULL);
2882 Py_DECREF(func);
2883 return res;
2884 }
2885 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002886 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002887 if (func == NULL) {
2888 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2889 return NULL;
2890 }
2891 Py_DECREF(func);
2892 return PySeqIter_New(self);
2893}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894
2895static PyObject *
2896slot_tp_iternext(PyObject *self)
2897{
Guido van Rossum2730b132001-08-28 18:22:14 +00002898 static PyObject *next_str;
2899 return call_method(self, "next", &next_str, "");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900}
2901
Guido van Rossum1a493502001-08-17 16:47:50 +00002902static PyObject *
2903slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
2904{
2905 PyTypeObject *tp = self->ob_type;
2906 PyObject *get;
2907 static PyObject *get_str = NULL;
2908
2909 if (get_str == NULL) {
2910 get_str = PyString_InternFromString("__get__");
2911 if (get_str == NULL)
2912 return NULL;
2913 }
2914 get = _PyType_Lookup(tp, get_str);
2915 if (get == NULL) {
2916 /* Avoid further slowdowns */
2917 if (tp->tp_descr_get == slot_tp_descr_get)
2918 tp->tp_descr_get = NULL;
2919 Py_INCREF(self);
2920 return self;
2921 }
Guido van Rossum2c252392001-08-24 10:13:31 +00002922 if (obj == NULL)
2923 obj = Py_None;
2924 if (type == NULL)
2925 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00002926 return PyObject_CallFunction(get, "OOO", self, obj, type);
2927}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002928
2929static int
2930slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2931{
Guido van Rossum2c252392001-08-24 10:13:31 +00002932 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002933 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00002934
2935 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002936 res = call_method(self, "__del__", &del_str,
2937 "O", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00002938 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002939 res = call_method(self, "__set__", &set_str,
2940 "OO", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941 if (res == NULL)
2942 return -1;
2943 Py_DECREF(res);
2944 return 0;
2945}
2946
2947static int
2948slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2949{
Guido van Rossum60718732001-08-28 17:47:51 +00002950 static PyObject *init_str;
2951 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002952 PyObject *res;
2953
2954 if (meth == NULL)
2955 return -1;
2956 res = PyObject_Call(meth, args, kwds);
2957 Py_DECREF(meth);
2958 if (res == NULL)
2959 return -1;
2960 Py_DECREF(res);
2961 return 0;
2962}
2963
2964static PyObject *
2965slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2966{
2967 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2968 PyObject *newargs, *x;
2969 int i, n;
2970
2971 if (func == NULL)
2972 return NULL;
2973 assert(PyTuple_Check(args));
2974 n = PyTuple_GET_SIZE(args);
2975 newargs = PyTuple_New(n+1);
2976 if (newargs == NULL)
2977 return NULL;
2978 Py_INCREF(type);
2979 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2980 for (i = 0; i < n; i++) {
2981 x = PyTuple_GET_ITEM(args, i);
2982 Py_INCREF(x);
2983 PyTuple_SET_ITEM(newargs, i+1, x);
2984 }
2985 x = PyObject_Call(func, newargs, kwds);
2986 Py_DECREF(func);
2987 return x;
2988}
2989
Guido van Rossumf040ede2001-08-07 16:40:56 +00002990/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002991 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002992 The dict argument is the dictionary argument passed to type_new(),
2993 which is the local namespace of the class statement, in other
2994 words, it contains the methods. For each special method (like
2995 __repr__) defined in the dictionary, the corresponding function
2996 slot in the type object (like tp_repr) is set to a special function
2997 whose name is 'slot_' followed by the slot name and whose signature
2998 is whatever is required for that slot. These slot functions look
2999 up the corresponding method in the type's dictionary and call it.
3000 The slot functions have to take care of the various peculiarities
3001 of the mapping between slots and special methods, such as mapping
3002 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3003 etc.) or mapping multiple slots to a single method (sq_item,
3004 mp_subscript <--> __getitem__). */
3005
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006static void
3007override_slots(PyTypeObject *type, PyObject *dict)
3008{
3009 PySequenceMethods *sq = type->tp_as_sequence;
3010 PyMappingMethods *mp = type->tp_as_mapping;
3011 PyNumberMethods *nb = type->tp_as_number;
3012
Guido van Rossumdc91b992001-08-08 22:26:22 +00003013#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003014 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003015 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016 }
3017
Guido van Rossumdc91b992001-08-08 22:26:22 +00003018#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003019 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003020 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021 }
3022
Guido van Rossumdc91b992001-08-08 22:26:22 +00003023#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003024 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003025 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026 }
3027
Guido van Rossumdc91b992001-08-08 22:26:22 +00003028#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003029 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003030 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031 }
3032
Guido van Rossumdc91b992001-08-08 22:26:22 +00003033 SQSLOT("__len__", sq_length, slot_sq_length);
3034 SQSLOT("__add__", sq_concat, slot_sq_concat);
3035 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3036 SQSLOT("__getitem__", sq_item, slot_sq_item);
3037 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3038 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3039 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3040 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3041 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3042 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3043 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3044 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045
Guido van Rossumdc91b992001-08-08 22:26:22 +00003046 MPSLOT("__len__", mp_length, slot_mp_length);
3047 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3048 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3049 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050
Guido van Rossumdc91b992001-08-08 22:26:22 +00003051 NBSLOT("__add__", nb_add, slot_nb_add);
3052 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3053 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3054 NBSLOT("__div__", nb_divide, slot_nb_divide);
3055 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3056 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3057 NBSLOT("__pow__", nb_power, slot_nb_power);
3058 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3059 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3060 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3061 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3062 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3063 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3064 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3065 NBSLOT("__and__", nb_and, slot_nb_and);
3066 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3067 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003069 NBSLOT("__int__", nb_int, slot_nb_int);
3070 NBSLOT("__long__", nb_long, slot_nb_long);
3071 NBSLOT("__float__", nb_float, slot_nb_float);
3072 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3073 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3074 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3075 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3076 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3077 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3078 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3079 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3080 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3081 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3082 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3083 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3084 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3085 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3086 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3087 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3088 slot_nb_inplace_floor_divide);
3089 NBSLOT("__itruediv__", nb_inplace_true_divide,
3090 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003091
Guido van Rossum8e248182001-08-12 05:17:56 +00003092 if (dict == NULL ||
3093 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094 PyDict_GetItemString(dict, "__repr__"))
3095 type->tp_print = NULL;
3096
Guido van Rossumdc91b992001-08-08 22:26:22 +00003097 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
3098 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3099 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3100 TPSLOT("__call__", tp_call, slot_tp_call);
3101 TPSLOT("__str__", tp_str, slot_tp_str);
3102 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
3103 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3104 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3105 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3106 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3107 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3108 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3109 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3110 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3111 TPSLOT("next", tp_iternext, slot_tp_iternext);
3112 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3113 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3114 TPSLOT("__init__", tp_init, slot_tp_init);
3115 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003117
3118
3119/* Cooperative 'super' */
3120
3121typedef struct {
3122 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003123 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003124 PyObject *obj;
3125} superobject;
3126
3127static void
3128super_dealloc(PyObject *self)
3129{
3130 superobject *su = (superobject *)self;
3131
3132 Py_XDECREF(su->obj);
3133 Py_XDECREF(su->type);
3134 self->ob_type->tp_free(self);
3135}
3136
3137static PyObject *
3138super_getattro(PyObject *self, PyObject *name)
3139{
3140 superobject *su = (superobject *)self;
3141
3142 if (su->obj != NULL) {
3143 PyObject *mro, *res, *tmp;
3144 descrgetfunc f;
3145 int i, n;
3146
Guido van Rossume705ef12001-08-29 15:47:06 +00003147 mro = su->obj->ob_type->tp_mro;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003148 assert(mro != NULL && PyTuple_Check(mro));
3149 n = PyTuple_GET_SIZE(mro);
3150 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003151 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003152 break;
3153 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003154 if (i >= n && PyType_Check(su->obj)) {
3155 mro = ((PyTypeObject *)(su->obj))->tp_mro;
3156 assert(mro != NULL && PyTuple_Check(mro));
3157 n = PyTuple_GET_SIZE(mro);
3158 for (i = 0; i < n; i++) {
3159 if ((PyObject *)(su->type) ==
3160 PyTuple_GET_ITEM(mro, i))
3161 break;
3162 }
3163 if (i >= n) {
3164 PyErr_SetString(PyExc_TypeError,
3165 "bogus super object");
3166 return NULL;
3167 }
3168 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003169 i++;
3170 res = NULL;
3171 for (; i < n; i++) {
3172 tmp = PyTuple_GET_ITEM(mro, i);
3173 assert(PyType_Check(tmp));
3174 res = PyDict_GetItem(
3175 ((PyTypeObject *)tmp)->tp_defined, name);
3176 if (res != NULL) {
3177 Py_INCREF(res);
3178 f = res->ob_type->tp_descr_get;
3179 if (f != NULL) {
3180 tmp = f(res, su->obj, res);
3181 Py_DECREF(res);
3182 res = tmp;
3183 }
3184 return res;
3185 }
3186 }
3187 }
3188 return PyObject_GenericGetAttr(self, name);
3189}
3190
3191static PyObject *
3192super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3193{
3194 superobject *su = (superobject *)self;
3195 superobject *new;
3196
3197 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3198 /* Not binding to an object, or already bound */
3199 Py_INCREF(self);
3200 return self;
3201 }
3202 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3203 if (new == NULL)
3204 return NULL;
3205 Py_INCREF(su->type);
3206 Py_INCREF(obj);
3207 new->type = su->type;
3208 new->obj = obj;
3209 return (PyObject *)new;
3210}
3211
3212static int
3213super_init(PyObject *self, PyObject *args, PyObject *kwds)
3214{
3215 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003216 PyTypeObject *type;
3217 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003218
3219 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3220 return -1;
3221 if (obj == Py_None)
3222 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003223 if (obj != NULL &&
3224 !PyType_IsSubtype(obj->ob_type, type) &&
3225 !(PyType_Check(obj) &&
3226 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003227 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003228 "super(type, obj): "
3229 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003230 return -1;
3231 }
3232 Py_INCREF(type);
3233 Py_XINCREF(obj);
3234 su->type = type;
3235 su->obj = obj;
3236 return 0;
3237}
3238
3239static char super_doc[] =
3240"super(type) -> unbound super object\n"
3241"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003242"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003243"Typical use to call a cooperative superclass method:\n"
3244"class C(B):\n"
3245" def meth(self, arg):\n"
3246" super(C, self).meth(arg)";
3247
3248PyTypeObject PySuper_Type = {
3249 PyObject_HEAD_INIT(&PyType_Type)
3250 0, /* ob_size */
3251 "super", /* tp_name */
3252 sizeof(superobject), /* tp_basicsize */
3253 0, /* tp_itemsize */
3254 /* methods */
3255 super_dealloc, /* tp_dealloc */
3256 0, /* tp_print */
3257 0, /* tp_getattr */
3258 0, /* tp_setattr */
3259 0, /* tp_compare */
3260 0, /* tp_repr */
3261 0, /* tp_as_number */
3262 0, /* tp_as_sequence */
3263 0, /* tp_as_mapping */
3264 0, /* tp_hash */
3265 0, /* tp_call */
3266 0, /* tp_str */
3267 super_getattro, /* tp_getattro */
3268 0, /* tp_setattro */
3269 0, /* tp_as_buffer */
Guido van Rossum31bcff82001-08-30 04:37:15 +00003270 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003271 super_doc, /* tp_doc */
3272 0, /* tp_traverse */
3273 0, /* tp_clear */
3274 0, /* tp_richcompare */
3275 0, /* tp_weaklistoffset */
3276 0, /* tp_iter */
3277 0, /* tp_iternext */
3278 0, /* tp_methods */
3279 0, /* tp_members */
3280 0, /* tp_getset */
3281 0, /* tp_base */
3282 0, /* tp_dict */
3283 super_descr_get, /* tp_descr_get */
3284 0, /* tp_descr_set */
3285 0, /* tp_dictoffset */
3286 super_init, /* tp_init */
3287 PyType_GenericAlloc, /* tp_alloc */
3288 PyType_GenericNew, /* tp_new */
3289 _PyObject_Del, /* tp_free */
3290};