blob: 9b7243b1e672854ed3fe7c019df31fd3ff3df698 [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 +00007staticforward int add_members(PyTypeObject *, struct memberlist *);
8
9static struct memberlist type_members[] = {
10 {"__name__", T_STRING, offsetof(PyTypeObject, tp_name), READONLY},
11 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
12 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
13 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
14 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
15 {"__weaklistoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
17 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
18 {"__dictoffset__", T_LONG,
19 offsetof(PyTypeObject, tp_dictoffset), READONLY},
20 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
21 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
22 {0}
23};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000024
Guido van Rossumc0b618a1997-05-02 03:12:38 +000025static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000026type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000027{
Tim Peters6d6c1a32001-08-02 04:15:00 +000028 return PyString_FromString("__builtin__");
29}
30
31static PyObject *
32type_dict(PyTypeObject *type, void *context)
33{
34 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000035 Py_INCREF(Py_None);
36 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000038 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
39 Py_INCREF(type->tp_dict);
40 return type->tp_dict;
41 }
42 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000043}
44
Tim Peters6d6c1a32001-08-02 04:15:00 +000045static PyObject *
46type_defined(PyTypeObject *type, void *context)
47{
48 if (type->tp_defined == NULL) {
49 Py_INCREF(Py_None);
50 return Py_None;
51 }
52 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
53 Py_INCREF(type->tp_defined);
54 return type->tp_defined;
55 }
56 return PyDictProxy_New(type->tp_defined);
57}
58
59static PyObject *
60type_dynamic(PyTypeObject *type, void *context)
61{
62 PyObject *res;
63
64 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
65 Py_INCREF(res);
66 return res;
67}
68
69struct getsetlist type_getsets[] = {
70 {"__module__", (getter)type_module, NULL, NULL},
71 {"__dict__", (getter)type_dict, NULL, NULL},
72 {"__defined__", (getter)type_defined, NULL, NULL},
73 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
74 {0}
75};
76
Martin v. Löwis0163d6d2001-06-09 07:34:05 +000077static int
78type_compare(PyObject *v, PyObject *w)
79{
80 /* This is called with type objects only. So we
81 can just compare the addresses. */
82 Py_uintptr_t vv = (Py_uintptr_t)v;
83 Py_uintptr_t ww = (Py_uintptr_t)w;
84 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
85}
86
Guido van Rossumc0b618a1997-05-02 03:12:38 +000087static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000088type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000089{
90 char buf[100];
Tim Peters6d6c1a32001-08-02 04:15:00 +000091 sprintf(buf, "<type '%.80s'>", type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000092 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093}
94
Tim Peters6d6c1a32001-08-02 04:15:00 +000095static PyObject *
96type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
97{
98 PyObject *obj;
99
100 if (type->tp_new == NULL) {
101 PyErr_Format(PyExc_TypeError,
102 "cannot create '%.100s' instances",
103 type->tp_name);
104 return NULL;
105 }
106
107 obj = type->tp_new(type, args, NULL);
108 if (obj != NULL) {
109 type = obj->ob_type;
110 if (type->tp_init != NULL &&
111 type->tp_init(obj, args, kwds) < 0) {
112 Py_DECREF(obj);
113 obj = NULL;
114 }
115 }
116 return obj;
117}
118
119PyObject *
120PyType_GenericAlloc(PyTypeObject *type, int nitems)
121{
122 int size;
123 void *mem;
124 PyObject *obj;
125
126 /* Inline PyObject_New() so we can zero the memory */
127 size = _PyObject_VAR_SIZE(type, nitems);
128 mem = PyObject_MALLOC(size);
129 if (mem == NULL)
130 return PyErr_NoMemory();
131 memset(mem, '\0', size);
132 if (PyType_IS_GC(type))
133 obj = PyObject_FROM_GC(mem);
134 else
135 obj = (PyObject *)mem;
136 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
137 Py_INCREF(type);
138 if (type->tp_itemsize == 0)
139 PyObject_INIT(obj, type);
140 else
141 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
142 if (PyType_IS_GC(type))
143 PyObject_GC_Init(obj);
144 return obj;
145}
146
147PyObject *
148PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
149{
150 return type->tp_alloc(type, 0);
151}
152
153/* Helper for subtyping */
154
155static void
156subtype_dealloc(PyObject *self)
157{
158 int dictoffset = self->ob_type->tp_dictoffset;
159 PyTypeObject *type, *base;
160 destructor f;
161
162 /* This exists so we can DECREF self->ob_type */
163
164 /* Find the nearest base with a different tp_dealloc */
165 type = self->ob_type;
166 base = type->tp_base;
167 while ((f = base->tp_dealloc) == subtype_dealloc) {
168 base = base->tp_base;
169 assert(base);
170 }
171
172 /* If we added a dict, DECREF it */
173 if (dictoffset && !base->tp_dictoffset) {
174 PyObject **dictptr = (PyObject **) ((char *)self + dictoffset);
175 PyObject *dict = *dictptr;
176 if (dict != NULL) {
177 Py_DECREF(dict);
178 *dictptr = NULL;
179 }
180 }
181
182 /* Finalize GC if the base doesn't do GC and we do */
183 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
184 PyObject_GC_Fini(self);
185
186 /* Call the base tp_dealloc() */
187 assert(f);
188 f(self);
189
190 /* Can't reference self beyond this point */
191 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
192 Py_DECREF(type);
193 }
194}
195
196staticforward void override_slots(PyTypeObject *type, PyObject *dict);
197staticforward PyTypeObject *solid_base(PyTypeObject *type);
198
199typedef struct {
200 PyTypeObject type;
201 PyNumberMethods as_number;
202 PySequenceMethods as_sequence;
203 PyMappingMethods as_mapping;
204 PyBufferProcs as_buffer;
205 PyObject *name, *slots;
206 struct memberlist members[1];
207} etype;
208
209/* type test with subclassing support */
210
211int
212PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
213{
214 PyObject *mro;
215
216 mro = a->tp_mro;
217 if (mro != NULL) {
218 /* Deal with multiple inheritance without recursion
219 by walking the MRO tuple */
220 int i, n;
221 assert(PyTuple_Check(mro));
222 n = PyTuple_GET_SIZE(mro);
223 for (i = 0; i < n; i++) {
224 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
225 return 1;
226 }
227 return 0;
228 }
229 else {
230 /* a is not completely initilized yet; follow tp_base */
231 do {
232 if (a == b)
233 return 1;
234 a = a->tp_base;
235 } while (a != NULL);
236 return b == &PyBaseObject_Type;
237 }
238}
239
240/* Method resolution order algorithm from "Putting Metaclasses to Work"
241 by Forman and Danforth (Addison-Wesley 1999). */
242
243static int
244conservative_merge(PyObject *left, PyObject *right)
245{
246 int left_size;
247 int right_size;
248 int i, j, r, ok;
249 PyObject *temp, *rr;
250
251 assert(PyList_Check(left));
252 assert(PyList_Check(right));
253
254 again:
255 left_size = PyList_GET_SIZE(left);
256 right_size = PyList_GET_SIZE(right);
257 for (i = 0; i < left_size; i++) {
258 for (j = 0; j < right_size; j++) {
259 if (PyList_GET_ITEM(left, i) ==
260 PyList_GET_ITEM(right, j)) {
261 /* found a merge point */
262 temp = PyList_New(0);
263 if (temp == NULL)
264 return -1;
265 for (r = 0; r < j; r++) {
266 rr = PyList_GET_ITEM(right, r);
267 ok = PySequence_Contains(left, rr);
268 if (ok < 0) {
269 Py_DECREF(temp);
270 return -1;
271 }
272 if (!ok) {
273 ok = PyList_Append(temp, rr);
274 if (ok < 0) {
275 Py_DECREF(temp);
276 return -1;
277 }
278 }
279 }
280 ok = PyList_SetSlice(left, i, i, temp);
281 Py_DECREF(temp);
282 if (ok < 0)
283 return -1;
284 ok = PyList_SetSlice(right, 0, j+1, NULL);
285 if (ok < 0)
286 return -1;
287 goto again;
288 }
289 }
290 }
291 return PyList_SetSlice(left, left_size, left_size, right);
292}
293
294static int
295serious_order_disagreements(PyObject *left, PyObject *right)
296{
297 return 0; /* XXX later -- for now, we cheat: "don't do that" */
298}
299
300static PyObject *
301mro_implementation(PyTypeObject *type)
302{
303 int i, n, ok;
304 PyObject *bases, *result;
305
306 bases = type->tp_bases;
307 n = PyTuple_GET_SIZE(bases);
308 result = Py_BuildValue("[O]", (PyObject *)type);
309 if (result == NULL)
310 return NULL;
311 for (i = 0; i < n; i++) {
312 PyTypeObject *base =
313 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
314 PyObject *parentMRO = PySequence_List(base->tp_mro);
315 if (parentMRO == NULL) {
316 Py_DECREF(result);
317 return NULL;
318 }
319 if (serious_order_disagreements(result, parentMRO)) {
320 Py_DECREF(result);
321 return NULL;
322 }
323 ok = conservative_merge(result, parentMRO);
324 Py_DECREF(parentMRO);
325 if (ok < 0) {
326 Py_DECREF(result);
327 return NULL;
328 }
329 }
330 return result;
331}
332
333static PyObject *
334mro_external(PyObject *self, PyObject *args)
335{
336 PyTypeObject *type = (PyTypeObject *)self;
337
338 if (!PyArg_ParseTuple(args, ""))
339 return NULL;
340 return mro_implementation(type);
341}
342
343static int
344mro_internal(PyTypeObject *type)
345{
346 PyObject *mro, *result, *tuple;
347
348 if (type->ob_type == &PyType_Type) {
349 result = mro_implementation(type);
350 }
351 else {
352 mro = PyObject_GetAttrString((PyObject *)type, "mro");
353 if (mro == NULL)
354 return -1;
355 result = PyObject_CallObject(mro, NULL);
356 Py_DECREF(mro);
357 }
358 if (result == NULL)
359 return -1;
360 tuple = PySequence_Tuple(result);
361 Py_DECREF(result);
362 type->tp_mro = tuple;
363 return 0;
364}
365
366
367/* Calculate the best base amongst multiple base classes.
368 This is the first one that's on the path to the "solid base". */
369
370static PyTypeObject *
371best_base(PyObject *bases)
372{
373 int i, n;
374 PyTypeObject *base, *winner, *candidate, *base_i;
375
376 assert(PyTuple_Check(bases));
377 n = PyTuple_GET_SIZE(bases);
378 assert(n > 0);
379 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
380 winner = &PyBaseObject_Type;
381 for (i = 0; i < n; i++) {
382 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
383 if (!PyType_Check((PyObject *)base_i)) {
384 PyErr_SetString(
385 PyExc_TypeError,
386 "bases must be types");
387 return NULL;
388 }
389 if (base_i->tp_dict == NULL) {
390 if (PyType_InitDict(base_i) < 0)
391 return NULL;
392 }
393 candidate = solid_base(base_i);
394 if (PyType_IsSubtype(winner, candidate))
395 ;
396 else if (PyType_IsSubtype(candidate, winner)) {
397 winner = candidate;
398 base = base_i;
399 }
400 else {
401 PyErr_SetString(
402 PyExc_TypeError,
403 "multiple bases have "
404 "instance lay-out conflict");
405 return NULL;
406 }
407 }
408 assert(base != NULL);
409 return base;
410}
411
412static int
413extra_ivars(PyTypeObject *type, PyTypeObject *base)
414{
415 int t_size = PyType_BASICSIZE(type);
416 int b_size = PyType_BASICSIZE(base);
417
418 assert(t_size >= b_size); /* type smaller than base! */
419 if (type->tp_itemsize || base->tp_itemsize) {
420 /* If itemsize is involved, stricter rules */
421 return t_size != b_size ||
422 type->tp_itemsize != base->tp_itemsize;
423 }
424 if (t_size == b_size)
425 return 0;
426 if (type->tp_dictoffset != 0 && base->tp_dictoffset == 0 &&
427 type->tp_dictoffset == b_size &&
428 (size_t)t_size == b_size + sizeof(PyObject *))
429 return 0; /* "Forgive" adding a __dict__ only */
430 return 1;
431}
432
433static PyTypeObject *
434solid_base(PyTypeObject *type)
435{
436 PyTypeObject *base;
437
438 if (type->tp_base)
439 base = solid_base(type->tp_base);
440 else
441 base = &PyBaseObject_Type;
442 if (extra_ivars(type, base))
443 return type;
444 else
445 return base;
446}
447
448staticforward void object_dealloc(PyObject *);
449staticforward int object_init(PyObject *, PyObject *, PyObject *);
450
451static PyObject *
452type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
453{
454 PyObject *name, *bases, *dict;
455 static char *kwlist[] = {"name", "bases", "dict", 0};
456 PyObject *slots, *tmp;
457 PyTypeObject *type, *base, *tmptype;
458 etype *et;
459 struct memberlist *mp;
460 int i, nbases, nslots, slotoffset, dynamic;
461
462 if (metatype == &PyType_Type &&
463 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
464 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
465 /* type(x) -> x.__class__ */
466 PyObject *x = PyTuple_GET_ITEM(args, 0);
467 Py_INCREF(x->ob_type);
468 return (PyObject *) x->ob_type;
469 }
470
471 /* Check arguments */
472 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
473 &name,
474 &PyTuple_Type, &bases,
475 &PyDict_Type, &dict))
476 return NULL;
477
478 /* Determine the proper metatype to deal with this,
479 and check for metatype conflicts while we're at it.
480 Note that if some other metatype wins to contract,
481 it's possible that its instances are not types. */
482 nbases = PyTuple_GET_SIZE(bases);
483 for (i = 0; i < nbases; i++) {
484 tmp = PyTuple_GET_ITEM(bases, i);
485 tmptype = tmp->ob_type;
486 if (PyType_IsSubtype(metatype, tmptype))
487 continue;
488 if (PyType_IsSubtype(tmptype, metatype)) {
489 metatype = tmptype;
490 continue;
491 }
492 PyErr_SetString(PyExc_TypeError,
493 "metatype conflict among bases");
494 return NULL;
495 }
496 if (metatype->tp_new != type_new) /* Pass it to the winner */
497 return metatype->tp_new(metatype, args, kwds);
498
499 /* Adjust for empty tuple bases */
500 if (nbases == 0) {
501 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
502 if (bases == NULL)
503 return NULL;
504 nbases = 1;
505 }
506 else
507 Py_INCREF(bases);
508
509 /* XXX From here until type is allocated, "return NULL" leaks bases! */
510
511 /* Calculate best base, and check that all bases are type objects */
512 base = best_base(bases);
513 if (base == NULL)
514 return NULL;
515 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
516 PyErr_Format(PyExc_TypeError,
517 "type '%.100s' is not an acceptable base type",
518 base->tp_name);
519 return NULL;
520 }
521
522 /* Should this be a dynamic class (i.e. modifiable __dict__)? */
523 tmp = PyDict_GetItemString(dict, "__dynamic__");
524 if (tmp != NULL) {
525 /* The class author has a preference */
526 dynamic = PyObject_IsTrue(tmp);
527 Py_DECREF(tmp);
528 if (dynamic < 0)
529 return NULL;
530 }
531 else {
532 /* Make a new class dynamic if any of its bases is dynamic.
533 This is not always the same as inheriting the __dynamic__
534 class attribute! */
535 dynamic = 0;
536 for (i = 0; i < nbases; i++) {
537 tmptype = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
538 if (tmptype->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
539 dynamic = 1;
540 break;
541 }
542 }
543 }
544
545 /* Check for a __slots__ sequence variable in dict, and count it */
546 slots = PyDict_GetItemString(dict, "__slots__");
547 nslots = 0;
548 if (slots != NULL) {
549 /* Make it into a tuple */
550 if (PyString_Check(slots))
551 slots = Py_BuildValue("(O)", slots);
552 else
553 slots = PySequence_Tuple(slots);
554 if (slots == NULL)
555 return NULL;
556 nslots = PyTuple_GET_SIZE(slots);
557 for (i = 0; i < nslots; i++) {
558 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
559 PyErr_SetString(PyExc_TypeError,
560 "__slots__ must be a sequence of strings");
561 Py_DECREF(slots);
562 return NULL;
563 }
564 }
565 }
566 if (slots == NULL && base->tp_dictoffset == 0 &&
567 (base->tp_setattro == PyObject_GenericSetAttr ||
568 base->tp_setattro == NULL))
569 nslots = 1;
570
571 /* XXX From here until type is safely allocated,
572 "return NULL" may leak slots! */
573
574 /* Allocate the type object */
575 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
576 if (type == NULL)
577 return NULL;
578
579 /* Keep name and slots alive in the extended type object */
580 et = (etype *)type;
581 Py_INCREF(name);
582 et->name = name;
583 et->slots = slots;
584
585 /* Initialize essential fields */
586 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
587 Py_TPFLAGS_BASETYPE;
588 if (dynamic)
589 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
590 type->tp_as_number = &et->as_number;
591 type->tp_as_sequence = &et->as_sequence;
592 type->tp_as_mapping = &et->as_mapping;
593 type->tp_as_buffer = &et->as_buffer;
594 type->tp_name = PyString_AS_STRING(name);
595
596 /* Set tp_base and tp_bases */
597 type->tp_bases = bases;
598 Py_INCREF(base);
599 type->tp_base = base;
600
601 /* Initialize tp_defined from passed-in dict */
602 type->tp_defined = dict = PyDict_Copy(dict);
603 if (dict == NULL) {
604 Py_DECREF(type);
605 return NULL;
606 }
607
608 /* Special-case __new__: if it's a plain function,
609 make it a static function */
610 tmp = PyDict_GetItemString(dict, "__new__");
611 if (tmp != NULL && PyFunction_Check(tmp)) {
612 tmp = PyStaticMethod_New(tmp);
613 if (tmp == NULL) {
614 Py_DECREF(type);
615 return NULL;
616 }
617 PyDict_SetItemString(dict, "__new__", tmp);
618 Py_DECREF(tmp);
619 }
620
621 /* Add descriptors for custom slots from __slots__, or for __dict__ */
622 mp = et->members;
623 slotoffset = PyType_BASICSIZE(base);
624 if (slots != NULL) {
625 for (i = 0; i < nslots; i++, mp++) {
626 mp->name = PyString_AS_STRING(
627 PyTuple_GET_ITEM(slots, i));
628 mp->type = T_OBJECT;
629 mp->offset = slotoffset;
630 slotoffset += sizeof(PyObject *);
631 }
632 }
633 else if (nslots) {
634 type->tp_dictoffset = slotoffset;
635 mp->name = "__dict__";
636 mp->type = T_OBJECT;
637 mp->offset = slotoffset;
638 mp->readonly = 1;
639 slotoffset += sizeof(PyObject *);
640 }
641 type->tp_basicsize = slotoffset;
642 add_members(type, et->members);
643
644 /* Special case some slots */
645 if (type->tp_dictoffset != 0 || nslots > 0) {
646 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
647 type->tp_getattro = PyObject_GenericGetAttr;
648 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
649 type->tp_setattro = PyObject_GenericSetAttr;
650 }
651 type->tp_dealloc = subtype_dealloc;
652
653 /* Always override allocation strategy to use regular heap */
654 type->tp_alloc = PyType_GenericAlloc;
655 type->tp_free = _PyObject_Del;
656
657 /* Initialize the rest */
658 if (PyType_InitDict(type) < 0) {
659 Py_DECREF(type);
660 return NULL;
661 }
662
663 /* Override slots that deserve it */
664 override_slots(type, type->tp_defined);
665 return (PyObject *)type;
666}
667
668/* Internal API to look for a name through the MRO.
669 This returns a borrowed reference, and doesn't set an exception! */
670PyObject *
671_PyType_Lookup(PyTypeObject *type, PyObject *name)
672{
673 int i, n;
674 PyObject *mro, *res, *dict;
675
676 /* For static types, look in tp_dict */
677 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
678 dict = type->tp_dict;
679 assert(dict && PyDict_Check(dict));
680 return PyDict_GetItem(dict, name);
681 }
682
683 /* For dynamic types, look in tp_defined of types in MRO */
684 mro = type->tp_mro;
685 assert(PyTuple_Check(mro));
686 n = PyTuple_GET_SIZE(mro);
687 for (i = 0; i < n; i++) {
688 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
689 assert(PyType_Check(type));
690 dict = type->tp_defined;
691 assert(dict && PyDict_Check(dict));
692 res = PyDict_GetItem(dict, name);
693 if (res != NULL)
694 return res;
695 }
696 return NULL;
697}
698
699/* This is similar to PyObject_GenericGetAttr(),
700 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
701static PyObject *
702type_getattro(PyTypeObject *type, PyObject *name)
703{
704 PyTypeObject *metatype = type->ob_type;
705 PyObject *descr, *res;
706 descrgetfunc f;
707
708 /* Initialize this type (we'll assume the metatype is initialized) */
709 if (type->tp_dict == NULL) {
710 if (PyType_InitDict(type) < 0)
711 return NULL;
712 }
713
714 /* Get a descriptor from the metatype */
715 descr = _PyType_Lookup(metatype, name);
716 f = NULL;
717 if (descr != NULL) {
718 f = descr->ob_type->tp_descr_get;
719 if (f != NULL && PyDescr_IsData(descr))
720 return f(descr,
721 (PyObject *)type, (PyObject *)metatype);
722 }
723
724 /* Look in tp_defined of this type and its bases */
725 res = _PyType_Lookup(type, name);
726 if (res != NULL) {
727 f = res->ob_type->tp_descr_get;
728 if (f != NULL)
729 return f(res, (PyObject *)NULL, (PyObject *)type);
730 Py_INCREF(res);
731 return res;
732 }
733
734 /* Use the descriptor from the metatype */
735 if (f != NULL) {
736 res = f(descr, (PyObject *)type, (PyObject *)metatype);
737 return res;
738 }
739 if (descr != NULL) {
740 Py_INCREF(descr);
741 return descr;
742 }
743
744 /* Give up */
745 PyErr_Format(PyExc_AttributeError,
746 "type object '%.50s' has no attribute '%.400s'",
747 type->tp_name, PyString_AS_STRING(name));
748 return NULL;
749}
750
751static int
752type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
753{
754 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
755 return PyObject_GenericSetAttr((PyObject *)type, name, value);
756 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
757 return -1;
758}
759
760static void
761type_dealloc(PyTypeObject *type)
762{
763 etype *et;
764
765 /* Assert this is a heap-allocated type object */
766 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
767 et = (etype *)type;
768 Py_XDECREF(type->tp_base);
769 Py_XDECREF(type->tp_dict);
770 Py_XDECREF(type->tp_bases);
771 Py_XDECREF(type->tp_mro);
772 Py_XDECREF(type->tp_defined);
773 /* XXX more? */
774 Py_XDECREF(et->name);
775 Py_XDECREF(et->slots);
776 type->ob_type->tp_free((PyObject *)type);
777}
778
779static PyMethodDef type_methods[] = {
780 {"mro", mro_external, METH_VARARGS,
781 "mro() -> list\nreturn a type's method resolution order"},
782 {0}
783};
784
785static char type_doc[] =
786"type(object) -> the object's type\n"
787"type(name, bases, dict) -> a new type";
788
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789PyTypeObject PyType_Type = {
790 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791 0, /* ob_size */
792 "type", /* tp_name */
793 sizeof(etype), /* tp_basicsize */
794 sizeof(struct memberlist), /* tp_itemsize */
795 (destructor)type_dealloc, /* tp_dealloc */
796 0, /* tp_print */
797 0, /* tp_getattr */
798 0, /* tp_setattr */
799 type_compare, /* tp_compare */
800 (reprfunc)type_repr, /* tp_repr */
801 0, /* tp_as_number */
802 0, /* tp_as_sequence */
803 0, /* tp_as_mapping */
804 (hashfunc)_Py_HashPointer, /* tp_hash */
805 (ternaryfunc)type_call, /* tp_call */
806 0, /* tp_str */
807 (getattrofunc)type_getattro, /* tp_getattro */
808 (setattrofunc)type_setattro, /* tp_setattro */
809 0, /* tp_as_buffer */
810 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
811 type_doc, /* tp_doc */
812 0, /* tp_traverse */
813 0, /* tp_clear */
814 0, /* tp_richcompare */
815 0, /* tp_weaklistoffset */
816 0, /* tp_iter */
817 0, /* tp_iternext */
818 type_methods, /* tp_methods */
819 type_members, /* tp_members */
820 type_getsets, /* tp_getset */
821 0, /* tp_base */
822 0, /* tp_dict */
823 0, /* tp_descr_get */
824 0, /* tp_descr_set */
825 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
826 0, /* tp_init */
827 0, /* tp_alloc */
828 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000829};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830
831
832/* The base type of all types (eventually)... except itself. */
833
834static int
835object_init(PyObject *self, PyObject *args, PyObject *kwds)
836{
837 return 0;
838}
839
840static void
841object_dealloc(PyObject *self)
842{
843 self->ob_type->tp_free(self);
844}
845
846static void
847object_free(PyObject *self)
848{
849 PyObject_Del(self);
850}
851
852static struct memberlist object_members[] = {
853 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
854 {0}
855};
856
857PyTypeObject PyBaseObject_Type = {
858 PyObject_HEAD_INIT(&PyType_Type)
859 0, /* ob_size */
860 "object", /* tp_name */
861 sizeof(PyObject), /* tp_basicsize */
862 0, /* tp_itemsize */
863 (destructor)object_dealloc, /* tp_dealloc */
864 0, /* tp_print */
865 0, /* tp_getattr */
866 0, /* tp_setattr */
867 0, /* tp_compare */
868 0, /* tp_repr */
869 0, /* tp_as_number */
870 0, /* tp_as_sequence */
871 0, /* tp_as_mapping */
872 0, /* tp_hash */
873 0, /* tp_call */
874 0, /* tp_str */
875 PyObject_GenericGetAttr, /* tp_getattro */
876 0, /* tp_setattro */
877 0, /* tp_as_buffer */
878 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
879 "The most base type", /* tp_doc */
880 0, /* tp_traverse */
881 0, /* tp_clear */
882 0, /* tp_richcompare */
883 0, /* tp_weaklistoffset */
884 0, /* tp_iter */
885 0, /* tp_iternext */
886 0, /* tp_methods */
887 object_members, /* tp_members */
888 0, /* tp_getset */
889 0, /* tp_base */
890 0, /* tp_dict */
891 0, /* tp_descr_get */
892 0, /* tp_descr_set */
893 0, /* tp_dictoffset */
894 object_init, /* tp_init */
895 PyType_GenericAlloc, /* tp_alloc */
896 PyType_GenericNew, /* tp_new */
897 object_free, /* tp_free */
898};
899
900
901/* Initialize the __dict__ in a type object */
902
903static int
904add_methods(PyTypeObject *type, PyMethodDef *meth)
905{
906 PyObject *dict = type->tp_defined;
907
908 for (; meth->ml_name != NULL; meth++) {
909 PyObject *descr;
910 if (PyDict_GetItemString(dict, meth->ml_name))
911 continue;
912 descr = PyDescr_NewMethod(type, meth);
913 if (descr == NULL)
914 return -1;
915 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
916 return -1;
917 Py_DECREF(descr);
918 }
919 return 0;
920}
921
922static int
923add_wrappers(PyTypeObject *type, struct wrapperbase *base, void *wrapped)
924{
925 PyObject *dict = type->tp_defined;
926
927 for (; base->name != NULL; base++) {
928 PyObject *descr;
929 if (PyDict_GetItemString(dict, base->name))
930 continue;
931 descr = PyDescr_NewWrapper(type, base, wrapped);
932 if (descr == NULL)
933 return -1;
934 if (PyDict_SetItemString(dict, base->name, descr) < 0)
935 return -1;
936 Py_DECREF(descr);
937 }
938 return 0;
939}
940
941static int
942add_staticmethodwrappers(PyTypeObject *type, struct wrapperbase *base,
943 void *wrapped)
944{
945 PyObject *dict = type->tp_defined;
946 PyObject *sm;
947
948 for (; base->name != NULL; base++) {
949 PyObject *descr;
950 if (PyDict_GetItemString(dict, base->name))
951 continue;
952 descr = PyDescr_NewWrapper(type->ob_type, base, wrapped);
953 if (descr == NULL)
954 return -1;
955 sm = PyStaticMethod_New(descr);
956 Py_DECREF(descr);
957 if (sm == NULL)
958 return -1;
959 if (PyDict_SetItemString(dict, base->name, sm) < 0)
960 return -1;
961 Py_DECREF(sm);
962 }
963 return 0;
964}
965
966static int
967add_members(PyTypeObject *type, struct memberlist *memb)
968{
969 PyObject *dict = type->tp_defined;
970
971 for (; memb->name != NULL; memb++) {
972 PyObject *descr;
973 if (PyDict_GetItemString(dict, memb->name))
974 continue;
975 descr = PyDescr_NewMember(type, memb);
976 if (descr == NULL)
977 return -1;
978 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
979 return -1;
980 Py_DECREF(descr);
981 }
982 return 0;
983}
984
985static int
986add_getset(PyTypeObject *type, struct getsetlist *gsp)
987{
988 PyObject *dict = type->tp_defined;
989
990 for (; gsp->name != NULL; gsp++) {
991 PyObject *descr;
992 if (PyDict_GetItemString(dict, gsp->name))
993 continue;
994 descr = PyDescr_NewGetSet(type, gsp);
995
996 if (descr == NULL)
997 return -1;
998 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
999 return -1;
1000 Py_DECREF(descr);
1001 }
1002 return 0;
1003}
1004
1005staticforward int add_operators(PyTypeObject *);
1006
1007static int
1008inherit_slots(PyTypeObject *type, PyTypeObject *base)
1009{
1010 int oldsize, newsize;
1011
1012#undef COPYSLOT
1013#undef COPYNUM
1014#undef COPYSEQ
1015#undef COPYMAP
1016#define COPYSLOT(SLOT) \
1017 if (!type->SLOT) type->SLOT = base->SLOT
1018
1019#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1020#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1021#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1022
1023 if (type->tp_as_number == NULL)
1024 type->tp_as_number = base->tp_as_number;
1025 else if (base->tp_as_number) {
1026 COPYNUM(nb_add);
1027 COPYNUM(nb_subtract);
1028 COPYNUM(nb_multiply);
1029 COPYNUM(nb_divide);
1030 COPYNUM(nb_remainder);
1031 COPYNUM(nb_divmod);
1032 COPYNUM(nb_power);
1033 COPYNUM(nb_negative);
1034 COPYNUM(nb_positive);
1035 COPYNUM(nb_absolute);
1036 COPYNUM(nb_nonzero);
1037 COPYNUM(nb_invert);
1038 COPYNUM(nb_lshift);
1039 COPYNUM(nb_rshift);
1040 COPYNUM(nb_and);
1041 COPYNUM(nb_xor);
1042 COPYNUM(nb_or);
1043 COPYNUM(nb_coerce);
1044 COPYNUM(nb_int);
1045 COPYNUM(nb_long);
1046 COPYNUM(nb_float);
1047 COPYNUM(nb_oct);
1048 COPYNUM(nb_hex);
1049 COPYNUM(nb_inplace_add);
1050 COPYNUM(nb_inplace_subtract);
1051 COPYNUM(nb_inplace_multiply);
1052 COPYNUM(nb_inplace_divide);
1053 COPYNUM(nb_inplace_remainder);
1054 COPYNUM(nb_inplace_power);
1055 COPYNUM(nb_inplace_lshift);
1056 COPYNUM(nb_inplace_rshift);
1057 COPYNUM(nb_inplace_and);
1058 COPYNUM(nb_inplace_xor);
1059 COPYNUM(nb_inplace_or);
1060 }
1061
1062 if (type->tp_as_sequence == NULL)
1063 type->tp_as_sequence = base->tp_as_sequence;
1064 else if (base->tp_as_sequence) {
1065 COPYSEQ(sq_length);
1066 COPYSEQ(sq_concat);
1067 COPYSEQ(sq_repeat);
1068 COPYSEQ(sq_item);
1069 COPYSEQ(sq_slice);
1070 COPYSEQ(sq_ass_item);
1071 COPYSEQ(sq_ass_slice);
1072 COPYSEQ(sq_contains);
1073 COPYSEQ(sq_inplace_concat);
1074 COPYSEQ(sq_inplace_repeat);
1075 }
1076
1077 if (type->tp_as_mapping == NULL)
1078 type->tp_as_mapping = base->tp_as_mapping;
1079 else if (base->tp_as_mapping) {
1080 COPYMAP(mp_length);
1081 COPYMAP(mp_subscript);
1082 COPYMAP(mp_ass_subscript);
1083 }
1084
1085 /* Special flag magic */
1086 if (!type->tp_as_buffer && base->tp_as_buffer) {
1087 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1088 type->tp_flags |=
1089 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1090 }
1091 if (!type->tp_as_sequence && base->tp_as_sequence) {
1092 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1093 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1094 }
1095 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1096 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1097 if ((!type->tp_as_number && base->tp_as_number) ||
1098 (!type->tp_as_sequence && base->tp_as_sequence)) {
1099 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1100 if (!type->tp_as_number && !type->tp_as_sequence) {
1101 type->tp_flags |= base->tp_flags &
1102 Py_TPFLAGS_HAVE_INPLACEOPS;
1103 }
1104 }
1105 /* Wow */
1106 }
1107 if (!type->tp_as_number && base->tp_as_number) {
1108 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1109 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1110 }
1111
1112 /* Copying basicsize is connected to the GC flags */
1113 oldsize = PyType_BASICSIZE(base);
1114 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1115 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1116 (base->tp_flags & Py_TPFLAGS_GC) &&
1117 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1118 (!type->tp_traverse && !type->tp_clear)) {
1119 type->tp_flags |= Py_TPFLAGS_GC;
1120 COPYSLOT(tp_traverse);
1121 COPYSLOT(tp_clear);
1122 }
1123 PyType_SET_BASICSIZE(type, newsize);
1124
1125 COPYSLOT(tp_itemsize);
1126 COPYSLOT(tp_dealloc);
1127 COPYSLOT(tp_print);
1128 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1129 type->tp_getattr = base->tp_getattr;
1130 type->tp_getattro = base->tp_getattro;
1131 }
1132 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1133 type->tp_setattr = base->tp_setattr;
1134 type->tp_setattro = base->tp_setattro;
1135 }
1136 /* tp_compare see tp_richcompare */
1137 COPYSLOT(tp_repr);
1138 COPYSLOT(tp_hash);
1139 COPYSLOT(tp_call);
1140 COPYSLOT(tp_str);
1141 COPYSLOT(tp_as_buffer);
1142 COPYSLOT(tp_flags);
1143 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
1144 if (type->tp_compare == NULL && type->tp_richcompare == NULL) {
1145 type->tp_compare = base->tp_compare;
1146 type->tp_richcompare = base->tp_richcompare;
1147 }
1148 }
1149 else {
1150 COPYSLOT(tp_compare);
1151 }
1152 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1153 COPYSLOT(tp_weaklistoffset);
1154 }
1155 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1156 COPYSLOT(tp_iter);
1157 COPYSLOT(tp_iternext);
1158 }
1159 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1160 COPYSLOT(tp_descr_get);
1161 COPYSLOT(tp_descr_set);
1162 COPYSLOT(tp_dictoffset);
1163 COPYSLOT(tp_init);
1164 COPYSLOT(tp_alloc);
1165 COPYSLOT(tp_new);
1166 COPYSLOT(tp_free);
1167 }
1168
1169 return 0;
1170}
1171
1172int
1173PyType_InitDict(PyTypeObject *type)
1174{
1175 PyObject *dict, *bases, *x;
1176 PyTypeObject *base;
1177 int i, n;
1178
1179 if (type->tp_dict != NULL)
1180 return 0; /* Already initialized */
1181
1182 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1183 base = type->tp_base;
1184 if (base == NULL && type != &PyBaseObject_Type)
1185 base = type->tp_base = &PyBaseObject_Type;
1186
1187 /* Initialize tp_bases */
1188 bases = type->tp_bases;
1189 if (bases == NULL) {
1190 if (base == NULL)
1191 bases = PyTuple_New(0);
1192 else
1193 bases = Py_BuildValue("(O)", base);
1194 if (bases == NULL)
1195 return -1;
1196 type->tp_bases = bases;
1197 }
1198
1199 /* Initialize the base class */
1200 if (base) {
1201 if (PyType_InitDict(base) < 0)
1202 return -1;
1203 }
1204
1205 /* Initialize tp_defined */
1206 dict = type->tp_defined;
1207 if (dict == NULL) {
1208 dict = PyDict_New();
1209 if (dict == NULL)
1210 return -1;
1211 type->tp_defined = dict;
1212 }
1213
1214 /* Add type-specific descriptors to tp_defined */
1215 if (add_operators(type) < 0)
1216 return -1;
1217 if (type->tp_methods != NULL) {
1218 if (add_methods(type, type->tp_methods) < 0)
1219 return -1;
1220 }
1221 if (type->tp_members != NULL) {
1222 if (add_members(type, type->tp_members) < 0)
1223 return -1;
1224 }
1225 if (type->tp_getset != NULL) {
1226 if (add_getset(type, type->tp_getset) < 0)
1227 return -1;
1228 }
1229
1230 /* Temporarily make tp_dict the same object as tp_defined.
1231 (This is needed to call mro(), and can stay this way for
1232 dynamic types). */
1233 Py_INCREF(type->tp_defined);
1234 type->tp_dict = type->tp_defined;
1235
1236 /* Calculate method resolution order */
1237 if (mro_internal(type) < 0) {
1238 return -1;
1239 }
1240
1241 /* Initialize tp_dict properly */
1242 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
1243 /* For a static type, tp_dict is the consolidation
1244 of the tp_defined of its bases in MRO. Earlier
1245 bases override later bases; since d.update() works
1246 the other way, we walk the MRO sequence backwards. */
1247 Py_DECREF(type->tp_dict);
1248 type->tp_dict = PyDict_New();
1249 if (type->tp_dict == NULL)
1250 return -1;
1251 bases = type->tp_mro;
1252 assert(bases != NULL);
1253 assert(PyTuple_Check(bases));
1254 n = PyTuple_GET_SIZE(bases);
1255 for (i = n; --i >= 0; ) {
1256 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1257 assert(PyType_Check(base));
1258 x = base->tp_defined;
1259 if (x != NULL && PyDict_Update(type->tp_dict, x) < 0)
1260 return -1;
1261 }
1262 }
1263
1264 /* Inherit slots from direct base */
1265 if (type->tp_base != NULL)
1266 if (inherit_slots(type, type->tp_base) < 0)
1267 return -1;
1268
1269 return 0;
1270}
1271
1272
1273/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1274
1275/* There's a wrapper *function* for each distinct function typedef used
1276 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1277 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1278 Most tables have only one entry; the tables for binary operators have two
1279 entries, one regular and one with reversed arguments. */
1280
1281static PyObject *
1282wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1283{
1284 inquiry func = (inquiry)wrapped;
1285 int res;
1286
1287 if (!PyArg_ParseTuple(args, ""))
1288 return NULL;
1289 res = (*func)(self);
1290 if (res == -1 && PyErr_Occurred())
1291 return NULL;
1292 return PyInt_FromLong((long)res);
1293}
1294
1295static struct wrapperbase tab_len[] = {
1296 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1297 {0}
1298};
1299
1300static PyObject *
1301wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1302{
1303 binaryfunc func = (binaryfunc)wrapped;
1304 PyObject *other;
1305
1306 if (!PyArg_ParseTuple(args, "O", &other))
1307 return NULL;
1308 return (*func)(self, other);
1309}
1310
1311static PyObject *
1312wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1313{
1314 binaryfunc func = (binaryfunc)wrapped;
1315 PyObject *other;
1316
1317 if (!PyArg_ParseTuple(args, "O", &other))
1318 return NULL;
1319 return (*func)(other, self);
1320}
1321
1322#undef BINARY
1323#define BINARY(NAME, OP) \
1324static struct wrapperbase tab_##NAME[] = { \
1325 {"__" #NAME "__", \
1326 (wrapperfunc)wrap_binaryfunc, \
1327 "x.__" #NAME "__(y) <==> " #OP}, \
1328 {"__r" #NAME "__", \
1329 (wrapperfunc)wrap_binaryfunc_r, \
1330 "y.__r" #NAME "__(x) <==> " #OP}, \
1331 {0} \
1332}
1333
1334BINARY(add, "x+y");
1335BINARY(sub, "x-y");
1336BINARY(mul, "x*y");
1337BINARY(div, "x/y");
1338BINARY(mod, "x%y");
1339BINARY(divmod, "divmod(x,y)");
1340BINARY(lshift, "x<<y");
1341BINARY(rshift, "x>>y");
1342BINARY(and, "x&y");
1343BINARY(xor, "x^y");
1344BINARY(or, "x|y");
1345
1346static PyObject *
1347wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1348{
1349 ternaryfunc func = (ternaryfunc)wrapped;
1350 PyObject *other;
1351 PyObject *third = Py_None;
1352
1353 /* Note: This wrapper only works for __pow__() */
1354
1355 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1356 return NULL;
1357 return (*func)(self, other, third);
1358}
1359
1360#undef TERNARY
1361#define TERNARY(NAME, OP) \
1362static struct wrapperbase tab_##NAME[] = { \
1363 {"__" #NAME "__", \
1364 (wrapperfunc)wrap_ternaryfunc, \
1365 "x.__" #NAME "__(y, z) <==> " #OP}, \
1366 {"__r" #NAME "__", \
1367 (wrapperfunc)wrap_ternaryfunc, \
1368 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1369 {0} \
1370}
1371
1372TERNARY(pow, "(x**y) % z");
1373
1374#undef UNARY
1375#define UNARY(NAME, OP) \
1376static struct wrapperbase tab_##NAME[] = { \
1377 {"__" #NAME "__", \
1378 (wrapperfunc)wrap_unaryfunc, \
1379 "x.__" #NAME "__() <==> " #OP}, \
1380 {0} \
1381}
1382
1383static PyObject *
1384wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1385{
1386 unaryfunc func = (unaryfunc)wrapped;
1387
1388 if (!PyArg_ParseTuple(args, ""))
1389 return NULL;
1390 return (*func)(self);
1391}
1392
1393UNARY(neg, "-x");
1394UNARY(pos, "+x");
1395UNARY(abs, "abs(x)");
1396UNARY(nonzero, "x != 0");
1397UNARY(invert, "~x");
1398UNARY(int, "int(x)");
1399UNARY(long, "long(x)");
1400UNARY(float, "float(x)");
1401UNARY(oct, "oct(x)");
1402UNARY(hex, "hex(x)");
1403
1404#undef IBINARY
1405#define IBINARY(NAME, OP) \
1406static struct wrapperbase tab_##NAME[] = { \
1407 {"__" #NAME "__", \
1408 (wrapperfunc)wrap_binaryfunc, \
1409 "x.__" #NAME "__(y) <==> " #OP}, \
1410 {0} \
1411}
1412
1413IBINARY(iadd, "x+=y");
1414IBINARY(isub, "x-=y");
1415IBINARY(imul, "x*=y");
1416IBINARY(idiv, "x/=y");
1417IBINARY(imod, "x%=y");
1418IBINARY(ilshift, "x<<=y");
1419IBINARY(irshift, "x>>=y");
1420IBINARY(iand, "x&=y");
1421IBINARY(ixor, "x^=y");
1422IBINARY(ior, "x|=y");
1423
1424#undef ITERNARY
1425#define ITERNARY(NAME, OP) \
1426static struct wrapperbase tab_##NAME[] = { \
1427 {"__" #NAME "__", \
1428 (wrapperfunc)wrap_ternaryfunc, \
1429 "x.__" #NAME "__(y) <==> " #OP}, \
1430 {0} \
1431}
1432
1433ITERNARY(ipow, "x = (x**y) % z");
1434
1435static struct wrapperbase tab_getitem[] = {
1436 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1437 "x.__getitem__(y) <==> x[y]"},
1438 {0}
1439};
1440
1441static PyObject *
1442wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1443{
1444 intargfunc func = (intargfunc)wrapped;
1445 int i;
1446
1447 if (!PyArg_ParseTuple(args, "i", &i))
1448 return NULL;
1449 return (*func)(self, i);
1450}
1451
1452static struct wrapperbase tab_mul_int[] = {
1453 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1454 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1455 {0}
1456};
1457
1458static struct wrapperbase tab_concat[] = {
1459 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1460 {0}
1461};
1462
1463static struct wrapperbase tab_imul_int[] = {
1464 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1465 {0}
1466};
1467
1468static struct wrapperbase tab_getitem_int[] = {
1469 {"__getitem__", (wrapperfunc)wrap_intargfunc,
1470 "x.__getitem__(i) <==> x[i]"},
1471 {0}
1472};
1473
1474static PyObject *
1475wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1476{
1477 intintargfunc func = (intintargfunc)wrapped;
1478 int i, j;
1479
1480 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1481 return NULL;
1482 return (*func)(self, i, j);
1483}
1484
1485static struct wrapperbase tab_getslice[] = {
1486 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1487 "x.__getslice__(i, j) <==> x[i:j]"},
1488 {0}
1489};
1490
1491static PyObject *
1492wrap_intobjargproc(PyObject *self, PyObject *args, void *wrapped)
1493{
1494 intobjargproc func = (intobjargproc)wrapped;
1495 int i, res;
1496 PyObject *value;
1497
1498 if (!PyArg_ParseTuple(args, "iO", &i, &value))
1499 return NULL;
1500 res = (*func)(self, i, value);
1501 if (res == -1 && PyErr_Occurred())
1502 return NULL;
1503 Py_INCREF(Py_None);
1504 return Py_None;
1505}
1506
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001507static PyObject *
1508wrap_delitem_int(PyObject *self, PyObject *args, void *wrapped)
1509{
1510 intobjargproc func = (intobjargproc)wrapped;
1511 int i, res;
1512
1513 if (!PyArg_ParseTuple(args, "i", &i))
1514 return NULL;
1515 res = (*func)(self, i, NULL);
1516 if (res == -1 && PyErr_Occurred())
1517 return NULL;
1518 Py_INCREF(Py_None);
1519 return Py_None;
1520}
1521
Tim Peters6d6c1a32001-08-02 04:15:00 +00001522static struct wrapperbase tab_setitem_int[] = {
1523 {"__setitem__", (wrapperfunc)wrap_intobjargproc,
1524 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001525 {"__delitem__", (wrapperfunc)wrap_delitem_int,
1526 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 {0}
1528};
1529
1530static PyObject *
1531wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1532{
1533 intintobjargproc func = (intintobjargproc)wrapped;
1534 int i, j, res;
1535 PyObject *value;
1536
1537 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1538 return NULL;
1539 res = (*func)(self, i, j, value);
1540 if (res == -1 && PyErr_Occurred())
1541 return NULL;
1542 Py_INCREF(Py_None);
1543 return Py_None;
1544}
1545
1546static struct wrapperbase tab_setslice[] = {
1547 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1548 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1549 {0}
1550};
1551
1552/* XXX objobjproc is a misnomer; should be objargpred */
1553static PyObject *
1554wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1555{
1556 objobjproc func = (objobjproc)wrapped;
1557 int res;
1558 PyObject *value;
1559
1560 if (!PyArg_ParseTuple(args, "O", &value))
1561 return NULL;
1562 res = (*func)(self, value);
1563 if (res == -1 && PyErr_Occurred())
1564 return NULL;
1565 return PyInt_FromLong((long)res);
1566}
1567
1568static struct wrapperbase tab_contains[] = {
1569 {"__contains__", (wrapperfunc)wrap_objobjproc,
1570 "x.__contains__(y) <==> y in x"},
1571 {0}
1572};
1573
1574static PyObject *
1575wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1576{
1577 objobjargproc func = (objobjargproc)wrapped;
1578 int res;
1579 PyObject *key, *value;
1580
1581 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1582 return NULL;
1583 res = (*func)(self, key, value);
1584 if (res == -1 && PyErr_Occurred())
1585 return NULL;
1586 Py_INCREF(Py_None);
1587 return Py_None;
1588}
1589
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001590static PyObject *
1591wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1592{
1593 objobjargproc func = (objobjargproc)wrapped;
1594 int res;
1595 PyObject *key;
1596
1597 if (!PyArg_ParseTuple(args, "O", &key))
1598 return NULL;
1599 res = (*func)(self, key, NULL);
1600 if (res == -1 && PyErr_Occurred())
1601 return NULL;
1602 Py_INCREF(Py_None);
1603 return Py_None;
1604}
1605
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606static struct wrapperbase tab_setitem[] = {
1607 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1608 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001609 {"__delitem__", (wrapperfunc)wrap_delitem,
1610 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611 {0}
1612};
1613
1614static PyObject *
1615wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1616{
1617 cmpfunc func = (cmpfunc)wrapped;
1618 int res;
1619 PyObject *other;
1620
1621 if (!PyArg_ParseTuple(args, "O", &other))
1622 return NULL;
1623 res = (*func)(self, other);
1624 if (PyErr_Occurred())
1625 return NULL;
1626 return PyInt_FromLong((long)res);
1627}
1628
1629static struct wrapperbase tab_cmp[] = {
1630 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1631 "x.__cmp__(y) <==> cmp(x,y)"},
1632 {0}
1633};
1634
1635static struct wrapperbase tab_repr[] = {
1636 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1637 "x.__repr__() <==> repr(x)"},
1638 {0}
1639};
1640
1641static struct wrapperbase tab_getattr[] = {
1642 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1643 "x.__getattr__('name') <==> x.name"},
1644 {0}
1645};
1646
1647static PyObject *
1648wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1649{
1650 setattrofunc func = (setattrofunc)wrapped;
1651 int res;
1652 PyObject *name, *value;
1653
1654 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1655 return NULL;
1656 res = (*func)(self, name, value);
1657 if (res < 0)
1658 return NULL;
1659 Py_INCREF(Py_None);
1660 return Py_None;
1661}
1662
1663static PyObject *
1664wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1665{
1666 setattrofunc func = (setattrofunc)wrapped;
1667 int res;
1668 PyObject *name;
1669
1670 if (!PyArg_ParseTuple(args, "O", &name))
1671 return NULL;
1672 res = (*func)(self, name, NULL);
1673 if (res < 0)
1674 return NULL;
1675 Py_INCREF(Py_None);
1676 return Py_None;
1677}
1678
1679static struct wrapperbase tab_setattr[] = {
1680 {"__setattr__", (wrapperfunc)wrap_setattr,
1681 "x.__setattr__('name', value) <==> x.name = value"},
1682 {"__delattr__", (wrapperfunc)wrap_delattr,
1683 "x.__delattr__('name') <==> del x.name"},
1684 {0}
1685};
1686
1687static PyObject *
1688wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1689{
1690 hashfunc func = (hashfunc)wrapped;
1691 long res;
1692
1693 if (!PyArg_ParseTuple(args, ""))
1694 return NULL;
1695 res = (*func)(self);
1696 if (res == -1 && PyErr_Occurred())
1697 return NULL;
1698 return PyInt_FromLong(res);
1699}
1700
1701static struct wrapperbase tab_hash[] = {
1702 {"__hash__", (wrapperfunc)wrap_hashfunc,
1703 "x.__hash__() <==> hash(x)"},
1704 {0}
1705};
1706
1707static PyObject *
1708wrap_call(PyObject *self, PyObject *args, void *wrapped)
1709{
1710 ternaryfunc func = (ternaryfunc)wrapped;
1711
1712 /* XXX What about keyword arguments? */
1713 return (*func)(self, args, NULL);
1714}
1715
1716static struct wrapperbase tab_call[] = {
1717 {"__call__", (wrapperfunc)wrap_call,
1718 "x.__call__(...) <==> x(...)"},
1719 {0}
1720};
1721
1722static struct wrapperbase tab_str[] = {
1723 {"__str__", (wrapperfunc)wrap_unaryfunc,
1724 "x.__str__() <==> str(x)"},
1725 {0}
1726};
1727
1728static PyObject *
1729wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1730{
1731 richcmpfunc func = (richcmpfunc)wrapped;
1732 PyObject *other;
1733
1734 if (!PyArg_ParseTuple(args, "O", &other))
1735 return NULL;
1736 return (*func)(self, other, op);
1737}
1738
1739#undef RICHCMP_WRAPPER
1740#define RICHCMP_WRAPPER(NAME, OP) \
1741static PyObject * \
1742richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1743{ \
1744 return wrap_richcmpfunc(self, args, wrapped, OP); \
1745}
1746
1747RICHCMP_WRAPPER(lt, Py_LT);
1748RICHCMP_WRAPPER(le, Py_LE);
1749RICHCMP_WRAPPER(eq, Py_EQ);
1750RICHCMP_WRAPPER(ne, Py_NE);
1751RICHCMP_WRAPPER(gt, Py_GT);
1752RICHCMP_WRAPPER(ge, Py_GE);
1753
1754#undef RICHCMP_ENTRY
1755#define RICHCMP_ENTRY(NAME, EXPR) \
1756 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1757 "x.__" #NAME "__(y) <==> " EXPR}
1758
1759static struct wrapperbase tab_richcmp[] = {
1760 RICHCMP_ENTRY(lt, "x<y"),
1761 RICHCMP_ENTRY(le, "x<=y"),
1762 RICHCMP_ENTRY(eq, "x==y"),
1763 RICHCMP_ENTRY(ne, "x!=y"),
1764 RICHCMP_ENTRY(gt, "x>y"),
1765 RICHCMP_ENTRY(ge, "x>=y"),
1766 {0}
1767};
1768
1769static struct wrapperbase tab_iter[] = {
1770 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
1771 {0}
1772};
1773
1774static PyObject *
1775wrap_next(PyObject *self, PyObject *args, void *wrapped)
1776{
1777 unaryfunc func = (unaryfunc)wrapped;
1778 PyObject *res;
1779
1780 if (!PyArg_ParseTuple(args, ""))
1781 return NULL;
1782 res = (*func)(self);
1783 if (res == NULL && !PyErr_Occurred())
1784 PyErr_SetNone(PyExc_StopIteration);
1785 return res;
1786}
1787
1788static struct wrapperbase tab_next[] = {
1789 {"next", (wrapperfunc)wrap_next,
1790 "x.next() -> the next value, or raise StopIteration"},
1791 {0}
1792};
1793
1794static PyObject *
1795wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
1796{
1797 descrgetfunc func = (descrgetfunc)wrapped;
1798 PyObject *obj;
1799 PyObject *type = NULL;
1800
1801 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
1802 return NULL;
1803 if (type == NULL)
1804 type = (PyObject *)obj->ob_type;
1805 return (*func)(self, obj, type);
1806}
1807
1808static struct wrapperbase tab_descr_get[] = {
1809 {"__get__", (wrapperfunc)wrap_descr_get,
1810 "descr.__get__(obj, type) -> value"},
1811 {0}
1812};
1813
1814static PyObject *
1815wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
1816{
1817 descrsetfunc func = (descrsetfunc)wrapped;
1818 PyObject *obj, *value;
1819 int ret;
1820
1821 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
1822 return NULL;
1823 ret = (*func)(self, obj, value);
1824 if (ret < 0)
1825 return NULL;
1826 Py_INCREF(Py_None);
1827 return Py_None;
1828}
1829
1830static struct wrapperbase tab_descr_set[] = {
1831 {"__set__", (wrapperfunc)wrap_descrsetfunc,
1832 "descr.__set__(obj, value)"},
1833 {0}
1834};
1835
1836static PyObject *
1837wrap_init(PyObject *self, PyObject *args, void *wrapped)
1838{
1839 initproc func = (initproc)wrapped;
1840
1841 /* XXX What about keyword arguments? */
1842 if (func(self, args, NULL) < 0)
1843 return NULL;
1844 Py_INCREF(Py_None);
1845 return Py_None;
1846}
1847
1848static struct wrapperbase tab_init[] = {
1849 {"__init__", (wrapperfunc)wrap_init,
1850 "x.__init__(...) initializes x; "
1851 "see x.__type__.__doc__ for signature"},
1852 {0}
1853};
1854
1855static PyObject *
1856wrap_new(PyObject *type, PyObject *args, void *wrapped)
1857{
1858 newfunc new = (newfunc)wrapped;
1859 return new((PyTypeObject *)type, args, NULL);
1860}
1861
1862static struct wrapperbase tab_new[] = {
1863 {"__new__", (wrapperfunc)wrap_new,
1864 "T.__new__() -> an object with type T"},
1865 {0}
1866};
1867
1868static int
1869add_operators(PyTypeObject *type)
1870{
1871 PySequenceMethods *sq;
1872 PyMappingMethods *mp;
1873 PyNumberMethods *nb;
1874
1875#undef ADD
1876#define ADD(SLOT, TABLE) \
1877 if (SLOT) { \
1878 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
1879 return -1; \
1880 }
1881
1882 if ((sq = type->tp_as_sequence) != NULL) {
1883 ADD(sq->sq_length, tab_len);
1884 ADD(sq->sq_concat, tab_concat);
1885 ADD(sq->sq_repeat, tab_mul_int);
1886 ADD(sq->sq_item, tab_getitem_int);
1887 ADD(sq->sq_slice, tab_getslice);
1888 ADD(sq->sq_ass_item, tab_setitem_int);
1889 ADD(sq->sq_ass_slice, tab_setslice);
1890 ADD(sq->sq_contains, tab_contains);
1891 ADD(sq->sq_inplace_concat, tab_iadd);
1892 ADD(sq->sq_inplace_repeat, tab_imul_int);
1893 }
1894
1895 if ((mp = type->tp_as_mapping) != NULL) {
1896 if (sq->sq_length == NULL)
1897 ADD(mp->mp_length, tab_len);
1898 ADD(mp->mp_subscript, tab_getitem);
1899 ADD(mp->mp_ass_subscript, tab_setitem);
1900 }
1901
1902 /* We don't support "old-style numbers" because their binary
1903 operators require that both arguments have the same type;
1904 the wrappers here only work for new-style numbers. */
1905 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
1906 (nb = type->tp_as_number) != NULL) {
1907 ADD(nb->nb_add, tab_add);
1908 ADD(nb->nb_subtract, tab_sub);
1909 ADD(nb->nb_multiply, tab_mul);
1910 ADD(nb->nb_divide, tab_div);
1911 ADD(nb->nb_remainder, tab_mod);
1912 ADD(nb->nb_divmod, tab_divmod);
1913 ADD(nb->nb_power, tab_pow);
1914 ADD(nb->nb_negative, tab_neg);
1915 ADD(nb->nb_positive, tab_pos);
1916 ADD(nb->nb_absolute, tab_abs);
1917 ADD(nb->nb_nonzero, tab_nonzero);
1918 ADD(nb->nb_invert, tab_invert);
1919 ADD(nb->nb_lshift, tab_lshift);
1920 ADD(nb->nb_rshift, tab_rshift);
1921 ADD(nb->nb_and, tab_and);
1922 ADD(nb->nb_xor, tab_xor);
1923 ADD(nb->nb_or, tab_or);
1924 /* We don't support coerce() -- see above comment */
1925 ADD(nb->nb_int, tab_int);
1926 ADD(nb->nb_long, tab_long);
1927 ADD(nb->nb_float, tab_float);
1928 ADD(nb->nb_oct, tab_oct);
1929 ADD(nb->nb_hex, tab_hex);
1930 ADD(nb->nb_inplace_add, tab_iadd);
1931 ADD(nb->nb_inplace_subtract, tab_isub);
1932 ADD(nb->nb_inplace_multiply, tab_imul);
1933 ADD(nb->nb_inplace_divide, tab_idiv);
1934 ADD(nb->nb_inplace_remainder, tab_imod);
1935 ADD(nb->nb_inplace_power, tab_ipow);
1936 ADD(nb->nb_inplace_lshift, tab_ilshift);
1937 ADD(nb->nb_inplace_rshift, tab_irshift);
1938 ADD(nb->nb_inplace_and, tab_iand);
1939 ADD(nb->nb_inplace_xor, tab_ixor);
1940 ADD(nb->nb_inplace_or, tab_ior);
1941 }
1942
1943 ADD(type->tp_getattro, tab_getattr);
1944 ADD(type->tp_setattro, tab_setattr);
1945 ADD(type->tp_compare, tab_cmp);
1946 ADD(type->tp_repr, tab_repr);
1947 ADD(type->tp_hash, tab_hash);
1948 ADD(type->tp_call, tab_call);
1949 ADD(type->tp_str, tab_str);
1950 ADD(type->tp_richcompare, tab_richcmp);
1951 ADD(type->tp_iter, tab_iter);
1952 ADD(type->tp_iternext, tab_next);
1953 ADD(type->tp_descr_get, tab_descr_get);
1954 ADD(type->tp_descr_set, tab_descr_set);
1955 ADD(type->tp_init, tab_init);
1956
1957 if (type->tp_new != NULL)
1958 add_staticmethodwrappers(type, tab_new,
1959 (void *)(type->tp_new));
1960
1961 return 0;
1962}
1963
1964/* Slot wrappers that call the corresponding __foo__ slot */
1965
1966#define SLOT0(SLOTNAME, OPNAME) \
1967static PyObject * \
1968slot_##SLOTNAME(PyObject *self) \
1969{ \
1970 return PyObject_CallMethod(self, "__" #OPNAME "__", ""); \
1971}
1972
1973#define SLOT1(SLOTNAME, OPNAME, ARG1TYPE, ARGCODES) \
1974static PyObject * \
1975slot_##SLOTNAME(PyObject *self, ARG1TYPE arg1) \
1976{ \
1977 return PyObject_CallMethod(self, "__" #OPNAME "__", #ARGCODES, arg1); \
1978}
1979
1980#define SLOT2(SLOTNAME, OPNAME, ARG1TYPE, ARG2TYPE, ARGCODES) \
1981static PyObject * \
1982slot_##SLOTNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
1983{ \
1984 return PyObject_CallMethod(self, "__" #OPNAME "__", \
1985 #ARGCODES, arg1, arg2); \
1986}
1987
1988static int
1989slot_sq_length(PyObject *self)
1990{
1991 PyObject *res = PyObject_CallMethod(self, "__len__", "");
1992
1993 if (res == NULL)
1994 return -1;
1995 return (int)PyInt_AsLong(res);
1996}
1997
1998SLOT1(sq_concat, add, PyObject *, O);
1999SLOT1(sq_repeat, mul, int, i);
2000SLOT1(sq_item, getitem, int, i);
2001SLOT2(sq_slice, getslice, int, int, ii);
2002
2003static int
2004slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2005{
2006 PyObject *res;
2007
2008 if (value == NULL)
2009 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2010 else
2011 res = PyObject_CallMethod(self, "__setitem__",
2012 "iO", index, value);
2013 if (res == NULL)
2014 return -1;
2015 Py_DECREF(res);
2016 return 0;
2017}
2018
2019static int
2020slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2021{
2022 PyObject *res;
2023
2024 if (value == NULL)
2025 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2026 else
2027 res = PyObject_CallMethod(self, "__setslice__",
2028 "iiO", i, j, value);
2029 if (res == NULL)
2030 return -1;
2031 Py_DECREF(res);
2032 return 0;
2033}
2034
2035static int
2036slot_sq_contains(PyObject *self, PyObject *value)
2037{
2038 PyObject *res = PyObject_CallMethod(self, "__contains__", "O", value);
2039 int r;
2040
2041 if (res == NULL)
2042 return -1;
2043 r = PyInt_AsLong(res);
2044 Py_DECREF(res);
2045 return r;
2046}
2047
2048SLOT1(sq_inplace_concat, iadd, PyObject *, O);
2049SLOT1(sq_inplace_repeat, imul, int, i);
2050
2051#define slot_mp_length slot_sq_length
2052
2053SLOT1(mp_subscript, getitem, PyObject *, O);
2054
2055static int
2056slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2057{
2058 PyObject *res;
2059
2060 if (value == NULL)
2061 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2062 else
2063 res = PyObject_CallMethod(self, "__setitem__",
2064 "OO", key, value);
2065 if (res == NULL)
2066 return -1;
2067 Py_DECREF(res);
2068 return 0;
2069}
2070
2071/* XXX the numerical slots should call the reverse operators too;
2072 but how do they know their type? */
2073SLOT1(nb_add, add, PyObject *, O);
2074SLOT1(nb_subtract, sub, PyObject *, O);
2075SLOT1(nb_multiply, mul, PyObject *, O);
2076SLOT1(nb_divide, div, PyObject *, O);
2077SLOT1(nb_remainder, mod, PyObject *, O);
2078SLOT1(nb_divmod, divmod, PyObject *, O);
2079SLOT2(nb_power, pow, PyObject *, PyObject *, OO);
2080SLOT0(nb_negative, neg);
2081SLOT0(nb_positive, pos);
2082SLOT0(nb_absolute, abs);
2083
2084static int
2085slot_nb_nonzero(PyObject *self)
2086{
2087 PyObject *res = PyObject_CallMethod(self, "__nonzero__", "");
2088
2089 if (res == NULL)
2090 return -1;
2091 return (int)PyInt_AsLong(res);
2092}
2093
2094SLOT0(nb_invert, invert);
2095SLOT1(nb_lshift, lshift, PyObject *, O);
2096SLOT1(nb_rshift, rshift, PyObject *, O);
2097SLOT1(nb_and, and, PyObject *, O);
2098SLOT1(nb_xor, xor, PyObject *, O);
2099SLOT1(nb_or, or, PyObject *, O);
2100/* Not coerce() */
2101SLOT0(nb_int, int);
2102SLOT0(nb_long, long);
2103SLOT0(nb_float, float);
2104SLOT0(nb_oct, oct);
2105SLOT0(nb_hex, hex);
2106SLOT1(nb_inplace_add, iadd, PyObject *, O);
2107SLOT1(nb_inplace_subtract, isub, PyObject *, O);
2108SLOT1(nb_inplace_multiply, imul, PyObject *, O);
2109SLOT1(nb_inplace_divide, idiv, PyObject *, O);
2110SLOT1(nb_inplace_remainder, imod, PyObject *, O);
2111SLOT2(nb_inplace_power, ipow, PyObject *, PyObject *, OO);
2112SLOT1(nb_inplace_lshift, ilshift, PyObject *, O);
2113SLOT1(nb_inplace_rshift, irshift, PyObject *, O);
2114SLOT1(nb_inplace_and, iand, PyObject *, O);
2115SLOT1(nb_inplace_xor, ixor, PyObject *, O);
2116SLOT1(nb_inplace_or, ior, PyObject *, O);
2117
2118static int
2119slot_tp_compare(PyObject *self, PyObject *other)
2120{
2121 PyObject *res = PyObject_CallMethod(self, "__cmp__", "O", other);
2122 long r;
2123
2124 if (res == NULL)
2125 return -1;
2126 r = PyInt_AsLong(res);
2127 Py_DECREF(res);
2128 return (int)r;
2129}
2130
2131SLOT0(tp_repr, repr);
2132
2133static long
2134slot_tp_hash(PyObject *self)
2135{
2136 PyObject *res = PyObject_CallMethod(self, "__hash__", "");
2137 long h;
2138
2139 if (res == NULL)
2140 return -1;
2141 h = PyInt_AsLong(res);
2142 if (h == -1 && !PyErr_Occurred())
2143 h = -2;
2144 return h;
2145}
2146
2147static PyObject *
2148slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2149{
2150 PyObject *meth = PyObject_GetAttrString(self, "__call__");
2151 PyObject *res;
2152
2153 if (meth == NULL)
2154 return NULL;
2155 res = PyObject_Call(meth, args, kwds);
2156 Py_DECREF(meth);
2157 return res;
2158}
2159
2160SLOT0(tp_str, str);
2161
2162static PyObject *
2163slot_tp_getattro(PyObject *self, PyObject *name)
2164{
2165 PyTypeObject *tp = self->ob_type;
2166 PyObject *dict = NULL;
2167 PyObject *getattr;
2168
2169 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE)
2170 dict = tp->tp_dict;
2171 if (dict == NULL) {
2172 PyErr_Format(PyExc_SystemError,
2173 "'%.100s' type object has no __dict__???",
2174 tp->tp_name);
2175 return NULL;
2176 }
2177 getattr = PyDict_GetItemString(dict, "__getattr__");
2178 if (getattr == NULL) {
2179 PyErr_SetString(PyExc_AttributeError, "__getattr__");
2180 return NULL;
2181 }
2182 return PyObject_CallFunction(getattr, "OO", self, name);
2183}
2184
2185static int
2186slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2187{
2188 PyObject *res;
2189
2190 if (value == NULL)
2191 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2192 else
2193 res = PyObject_CallMethod(self, "__setattr__",
2194 "OO", name, value);
2195 if (res == NULL)
2196 return -1;
2197 Py_DECREF(res);
2198 return 0;
2199}
2200
2201/* Map rich comparison operators to their __xx__ namesakes */
2202static char *name_op[] = {
2203 "__lt__",
2204 "__le__",
2205 "__eq__",
2206 "__ne__",
2207 "__gt__",
2208 "__ge__",
2209};
2210
2211static PyObject *
2212slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2213{
2214 PyObject *meth = PyObject_GetAttrString(self, name_op[op]);
2215 PyObject *res;
2216
2217 if (meth == NULL)
2218 return NULL;
2219 res = PyObject_CallFunction(meth, "O", other);
2220 Py_DECREF(meth);
2221 return res;
2222}
2223
2224SLOT0(tp_iter, iter);
2225
2226static PyObject *
2227slot_tp_iternext(PyObject *self)
2228{
2229 return PyObject_CallMethod(self, "next", "");
2230}
2231
2232SLOT2(tp_descr_get, get, PyObject *, PyObject *, OO);
2233
2234static int
2235slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2236{
2237 PyObject *res = PyObject_CallMethod(self, "__set__",
2238 "OO", target, value);
2239 if (res == NULL)
2240 return -1;
2241 Py_DECREF(res);
2242 return 0;
2243}
2244
2245static int
2246slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2247{
2248 PyObject *meth = PyObject_GetAttrString(self, "__init__");
2249 PyObject *res;
2250
2251 if (meth == NULL)
2252 return -1;
2253 res = PyObject_Call(meth, args, kwds);
2254 Py_DECREF(meth);
2255 if (res == NULL)
2256 return -1;
2257 Py_DECREF(res);
2258 return 0;
2259}
2260
2261static PyObject *
2262slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2263{
2264 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2265 PyObject *newargs, *x;
2266 int i, n;
2267
2268 if (func == NULL)
2269 return NULL;
2270 assert(PyTuple_Check(args));
2271 n = PyTuple_GET_SIZE(args);
2272 newargs = PyTuple_New(n+1);
2273 if (newargs == NULL)
2274 return NULL;
2275 Py_INCREF(type);
2276 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2277 for (i = 0; i < n; i++) {
2278 x = PyTuple_GET_ITEM(args, i);
2279 Py_INCREF(x);
2280 PyTuple_SET_ITEM(newargs, i+1, x);
2281 }
2282 x = PyObject_Call(func, newargs, kwds);
2283 Py_DECREF(func);
2284 return x;
2285}
2286
2287static void
2288override_slots(PyTypeObject *type, PyObject *dict)
2289{
2290 PySequenceMethods *sq = type->tp_as_sequence;
2291 PyMappingMethods *mp = type->tp_as_mapping;
2292 PyNumberMethods *nb = type->tp_as_number;
2293
2294#define SQSLOT(OPNAME, SLOTNAME) \
2295 if (PyDict_GetItemString(dict, OPNAME)) { \
2296 sq->SLOTNAME = slot_##SLOTNAME; \
2297 }
2298
2299#define MPSLOT(OPNAME, SLOTNAME) \
2300 if (PyDict_GetItemString(dict, OPNAME)) { \
2301 mp->SLOTNAME = slot_##SLOTNAME; \
2302 }
2303
2304#define NBSLOT(OPNAME, SLOTNAME) \
2305 if (PyDict_GetItemString(dict, OPNAME)) { \
2306 nb->SLOTNAME = slot_##SLOTNAME; \
2307 }
2308
2309#define TPSLOT(OPNAME, SLOTNAME) \
2310 if (PyDict_GetItemString(dict, OPNAME)) { \
2311 type->SLOTNAME = slot_##SLOTNAME; \
2312 }
2313
2314 SQSLOT("__len__", sq_length);
2315 SQSLOT("__add__", sq_concat);
2316 SQSLOT("__mul__", sq_repeat);
2317 SQSLOT("__getitem__", sq_item);
2318 SQSLOT("__getslice__", sq_slice);
2319 SQSLOT("__setitem__", sq_ass_item);
2320 SQSLOT("__delitem__", sq_ass_item);
2321 SQSLOT("__setslice__", sq_ass_slice);
2322 SQSLOT("__delslice__", sq_ass_slice);
2323 SQSLOT("__contains__", sq_contains);
2324 SQSLOT("__iadd__", sq_inplace_concat);
2325 SQSLOT("__imul__", sq_inplace_repeat);
2326
2327 MPSLOT("__len__", mp_length);
2328 MPSLOT("__getitem__", mp_subscript);
2329 MPSLOT("__setitem__", mp_ass_subscript);
2330 MPSLOT("__delitem__", mp_ass_subscript);
2331
2332 NBSLOT("__add__", nb_add);
2333 NBSLOT("__sub__", nb_subtract);
2334 NBSLOT("__mul__", nb_multiply);
2335 NBSLOT("__div__", nb_divide);
2336 NBSLOT("__mod__", nb_remainder);
2337 NBSLOT("__divmod__", nb_divmod);
2338 NBSLOT("__pow__", nb_power);
2339 NBSLOT("__neg__", nb_negative);
2340 NBSLOT("__pos__", nb_positive);
2341 NBSLOT("__abs__", nb_absolute);
2342 NBSLOT("__nonzero__", nb_nonzero);
2343 NBSLOT("__invert__", nb_invert);
2344 NBSLOT("__lshift__", nb_lshift);
2345 NBSLOT("__rshift__", nb_rshift);
2346 NBSLOT("__and__", nb_and);
2347 NBSLOT("__xor__", nb_xor);
2348 NBSLOT("__or__", nb_or);
2349 /* Not coerce() */
2350 NBSLOT("__int__", nb_int);
2351 NBSLOT("__long__", nb_long);
2352 NBSLOT("__float__", nb_float);
2353 NBSLOT("__oct__", nb_oct);
2354 NBSLOT("__hex__", nb_hex);
2355 NBSLOT("__iadd__", nb_inplace_add);
2356 NBSLOT("__isub__", nb_inplace_subtract);
2357 NBSLOT("__imul__", nb_inplace_multiply);
2358 NBSLOT("__idiv__", nb_inplace_divide);
2359 NBSLOT("__imod__", nb_inplace_remainder);
2360 NBSLOT("__ipow__", nb_inplace_power);
2361 NBSLOT("__ilshift__", nb_inplace_lshift);
2362 NBSLOT("__irshift__", nb_inplace_rshift);
2363 NBSLOT("__iand__", nb_inplace_and);
2364 NBSLOT("__ixor__", nb_inplace_xor);
2365 NBSLOT("__ior__", nb_inplace_or);
2366
2367 if (PyDict_GetItemString(dict, "__str__") ||
2368 PyDict_GetItemString(dict, "__repr__"))
2369 type->tp_print = NULL;
2370
2371 TPSLOT("__cmp__", tp_compare);
2372 TPSLOT("__repr__", tp_repr);
2373 TPSLOT("__hash__", tp_hash);
2374 TPSLOT("__call__", tp_call);
2375 TPSLOT("__str__", tp_str);
2376 TPSLOT("__getattr__", tp_getattro);
2377 TPSLOT("__setattr__", tp_setattro);
2378 TPSLOT("__lt__", tp_richcompare);
2379 TPSLOT("__le__", tp_richcompare);
2380 TPSLOT("__eq__", tp_richcompare);
2381 TPSLOT("__ne__", tp_richcompare);
2382 TPSLOT("__gt__", tp_richcompare);
2383 TPSLOT("__ge__", tp_richcompare);
2384 TPSLOT("__iter__", tp_iter);
2385 TPSLOT("next", tp_iternext);
2386 TPSLOT("__get__", tp_descr_get);
2387 TPSLOT("__set__", tp_descr_set);
2388 TPSLOT("__init__", tp_init);
2389 TPSLOT("__new__", tp_new);
2390}