blob: 37afb47e186a64149b5ec326832845eeba66ba39 [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
Tim Peters6d6c1a32001-08-02 04:15:00 +0000942add_members(PyTypeObject *type, struct memberlist *memb)
943{
944 PyObject *dict = type->tp_defined;
945
946 for (; memb->name != NULL; memb++) {
947 PyObject *descr;
948 if (PyDict_GetItemString(dict, memb->name))
949 continue;
950 descr = PyDescr_NewMember(type, memb);
951 if (descr == NULL)
952 return -1;
953 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
954 return -1;
955 Py_DECREF(descr);
956 }
957 return 0;
958}
959
960static int
961add_getset(PyTypeObject *type, struct getsetlist *gsp)
962{
963 PyObject *dict = type->tp_defined;
964
965 for (; gsp->name != NULL; gsp++) {
966 PyObject *descr;
967 if (PyDict_GetItemString(dict, gsp->name))
968 continue;
969 descr = PyDescr_NewGetSet(type, gsp);
970
971 if (descr == NULL)
972 return -1;
973 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
974 return -1;
975 Py_DECREF(descr);
976 }
977 return 0;
978}
979
980staticforward int add_operators(PyTypeObject *);
981
982static int
983inherit_slots(PyTypeObject *type, PyTypeObject *base)
984{
985 int oldsize, newsize;
986
987#undef COPYSLOT
988#undef COPYNUM
989#undef COPYSEQ
990#undef COPYMAP
991#define COPYSLOT(SLOT) \
992 if (!type->SLOT) type->SLOT = base->SLOT
993
994#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
995#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
996#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
997
998 if (type->tp_as_number == NULL)
999 type->tp_as_number = base->tp_as_number;
1000 else if (base->tp_as_number) {
1001 COPYNUM(nb_add);
1002 COPYNUM(nb_subtract);
1003 COPYNUM(nb_multiply);
1004 COPYNUM(nb_divide);
1005 COPYNUM(nb_remainder);
1006 COPYNUM(nb_divmod);
1007 COPYNUM(nb_power);
1008 COPYNUM(nb_negative);
1009 COPYNUM(nb_positive);
1010 COPYNUM(nb_absolute);
1011 COPYNUM(nb_nonzero);
1012 COPYNUM(nb_invert);
1013 COPYNUM(nb_lshift);
1014 COPYNUM(nb_rshift);
1015 COPYNUM(nb_and);
1016 COPYNUM(nb_xor);
1017 COPYNUM(nb_or);
1018 COPYNUM(nb_coerce);
1019 COPYNUM(nb_int);
1020 COPYNUM(nb_long);
1021 COPYNUM(nb_float);
1022 COPYNUM(nb_oct);
1023 COPYNUM(nb_hex);
1024 COPYNUM(nb_inplace_add);
1025 COPYNUM(nb_inplace_subtract);
1026 COPYNUM(nb_inplace_multiply);
1027 COPYNUM(nb_inplace_divide);
1028 COPYNUM(nb_inplace_remainder);
1029 COPYNUM(nb_inplace_power);
1030 COPYNUM(nb_inplace_lshift);
1031 COPYNUM(nb_inplace_rshift);
1032 COPYNUM(nb_inplace_and);
1033 COPYNUM(nb_inplace_xor);
1034 COPYNUM(nb_inplace_or);
1035 }
1036
1037 if (type->tp_as_sequence == NULL)
1038 type->tp_as_sequence = base->tp_as_sequence;
1039 else if (base->tp_as_sequence) {
1040 COPYSEQ(sq_length);
1041 COPYSEQ(sq_concat);
1042 COPYSEQ(sq_repeat);
1043 COPYSEQ(sq_item);
1044 COPYSEQ(sq_slice);
1045 COPYSEQ(sq_ass_item);
1046 COPYSEQ(sq_ass_slice);
1047 COPYSEQ(sq_contains);
1048 COPYSEQ(sq_inplace_concat);
1049 COPYSEQ(sq_inplace_repeat);
1050 }
1051
1052 if (type->tp_as_mapping == NULL)
1053 type->tp_as_mapping = base->tp_as_mapping;
1054 else if (base->tp_as_mapping) {
1055 COPYMAP(mp_length);
1056 COPYMAP(mp_subscript);
1057 COPYMAP(mp_ass_subscript);
1058 }
1059
1060 /* Special flag magic */
1061 if (!type->tp_as_buffer && base->tp_as_buffer) {
1062 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1063 type->tp_flags |=
1064 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1065 }
1066 if (!type->tp_as_sequence && base->tp_as_sequence) {
1067 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1068 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1069 }
1070 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1071 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1072 if ((!type->tp_as_number && base->tp_as_number) ||
1073 (!type->tp_as_sequence && base->tp_as_sequence)) {
1074 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1075 if (!type->tp_as_number && !type->tp_as_sequence) {
1076 type->tp_flags |= base->tp_flags &
1077 Py_TPFLAGS_HAVE_INPLACEOPS;
1078 }
1079 }
1080 /* Wow */
1081 }
1082 if (!type->tp_as_number && base->tp_as_number) {
1083 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1084 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1085 }
1086
1087 /* Copying basicsize is connected to the GC flags */
1088 oldsize = PyType_BASICSIZE(base);
1089 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1090 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1091 (base->tp_flags & Py_TPFLAGS_GC) &&
1092 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1093 (!type->tp_traverse && !type->tp_clear)) {
1094 type->tp_flags |= Py_TPFLAGS_GC;
1095 COPYSLOT(tp_traverse);
1096 COPYSLOT(tp_clear);
1097 }
1098 PyType_SET_BASICSIZE(type, newsize);
1099
1100 COPYSLOT(tp_itemsize);
1101 COPYSLOT(tp_dealloc);
1102 COPYSLOT(tp_print);
1103 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1104 type->tp_getattr = base->tp_getattr;
1105 type->tp_getattro = base->tp_getattro;
1106 }
1107 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1108 type->tp_setattr = base->tp_setattr;
1109 type->tp_setattro = base->tp_setattro;
1110 }
1111 /* tp_compare see tp_richcompare */
1112 COPYSLOT(tp_repr);
1113 COPYSLOT(tp_hash);
1114 COPYSLOT(tp_call);
1115 COPYSLOT(tp_str);
1116 COPYSLOT(tp_as_buffer);
1117 COPYSLOT(tp_flags);
1118 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
1119 if (type->tp_compare == NULL && type->tp_richcompare == NULL) {
1120 type->tp_compare = base->tp_compare;
1121 type->tp_richcompare = base->tp_richcompare;
1122 }
1123 }
1124 else {
1125 COPYSLOT(tp_compare);
1126 }
1127 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1128 COPYSLOT(tp_weaklistoffset);
1129 }
1130 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1131 COPYSLOT(tp_iter);
1132 COPYSLOT(tp_iternext);
1133 }
1134 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1135 COPYSLOT(tp_descr_get);
1136 COPYSLOT(tp_descr_set);
1137 COPYSLOT(tp_dictoffset);
1138 COPYSLOT(tp_init);
1139 COPYSLOT(tp_alloc);
1140 COPYSLOT(tp_new);
1141 COPYSLOT(tp_free);
1142 }
1143
1144 return 0;
1145}
1146
1147int
1148PyType_InitDict(PyTypeObject *type)
1149{
1150 PyObject *dict, *bases, *x;
1151 PyTypeObject *base;
1152 int i, n;
1153
1154 if (type->tp_dict != NULL)
1155 return 0; /* Already initialized */
1156
1157 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1158 base = type->tp_base;
1159 if (base == NULL && type != &PyBaseObject_Type)
1160 base = type->tp_base = &PyBaseObject_Type;
1161
1162 /* Initialize tp_bases */
1163 bases = type->tp_bases;
1164 if (bases == NULL) {
1165 if (base == NULL)
1166 bases = PyTuple_New(0);
1167 else
1168 bases = Py_BuildValue("(O)", base);
1169 if (bases == NULL)
1170 return -1;
1171 type->tp_bases = bases;
1172 }
1173
1174 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001175 if (base && base->tp_dict == NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 if (PyType_InitDict(base) < 0)
1177 return -1;
1178 }
1179
1180 /* Initialize tp_defined */
1181 dict = type->tp_defined;
1182 if (dict == NULL) {
1183 dict = PyDict_New();
1184 if (dict == NULL)
1185 return -1;
1186 type->tp_defined = dict;
1187 }
1188
1189 /* Add type-specific descriptors to tp_defined */
1190 if (add_operators(type) < 0)
1191 return -1;
1192 if (type->tp_methods != NULL) {
1193 if (add_methods(type, type->tp_methods) < 0)
1194 return -1;
1195 }
1196 if (type->tp_members != NULL) {
1197 if (add_members(type, type->tp_members) < 0)
1198 return -1;
1199 }
1200 if (type->tp_getset != NULL) {
1201 if (add_getset(type, type->tp_getset) < 0)
1202 return -1;
1203 }
1204
1205 /* Temporarily make tp_dict the same object as tp_defined.
1206 (This is needed to call mro(), and can stay this way for
1207 dynamic types). */
1208 Py_INCREF(type->tp_defined);
1209 type->tp_dict = type->tp_defined;
1210
1211 /* Calculate method resolution order */
1212 if (mro_internal(type) < 0) {
1213 return -1;
1214 }
1215
1216 /* Initialize tp_dict properly */
1217 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
1218 /* For a static type, tp_dict is the consolidation
1219 of the tp_defined of its bases in MRO. Earlier
1220 bases override later bases; since d.update() works
1221 the other way, we walk the MRO sequence backwards. */
1222 Py_DECREF(type->tp_dict);
1223 type->tp_dict = PyDict_New();
1224 if (type->tp_dict == NULL)
1225 return -1;
1226 bases = type->tp_mro;
1227 assert(bases != NULL);
1228 assert(PyTuple_Check(bases));
1229 n = PyTuple_GET_SIZE(bases);
1230 for (i = n; --i >= 0; ) {
1231 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1232 assert(PyType_Check(base));
1233 x = base->tp_defined;
1234 if (x != NULL && PyDict_Update(type->tp_dict, x) < 0)
1235 return -1;
1236 }
1237 }
1238
1239 /* Inherit slots from direct base */
1240 if (type->tp_base != NULL)
1241 if (inherit_slots(type, type->tp_base) < 0)
1242 return -1;
1243
1244 return 0;
1245}
1246
1247
1248/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1249
1250/* There's a wrapper *function* for each distinct function typedef used
1251 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1252 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1253 Most tables have only one entry; the tables for binary operators have two
1254 entries, one regular and one with reversed arguments. */
1255
1256static PyObject *
1257wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1258{
1259 inquiry func = (inquiry)wrapped;
1260 int res;
1261
1262 if (!PyArg_ParseTuple(args, ""))
1263 return NULL;
1264 res = (*func)(self);
1265 if (res == -1 && PyErr_Occurred())
1266 return NULL;
1267 return PyInt_FromLong((long)res);
1268}
1269
1270static struct wrapperbase tab_len[] = {
1271 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1272 {0}
1273};
1274
1275static PyObject *
1276wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1277{
1278 binaryfunc func = (binaryfunc)wrapped;
1279 PyObject *other;
1280
1281 if (!PyArg_ParseTuple(args, "O", &other))
1282 return NULL;
1283 return (*func)(self, other);
1284}
1285
1286static PyObject *
1287wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1288{
1289 binaryfunc func = (binaryfunc)wrapped;
1290 PyObject *other;
1291
1292 if (!PyArg_ParseTuple(args, "O", &other))
1293 return NULL;
1294 return (*func)(other, self);
1295}
1296
1297#undef BINARY
1298#define BINARY(NAME, OP) \
1299static struct wrapperbase tab_##NAME[] = { \
1300 {"__" #NAME "__", \
1301 (wrapperfunc)wrap_binaryfunc, \
1302 "x.__" #NAME "__(y) <==> " #OP}, \
1303 {"__r" #NAME "__", \
1304 (wrapperfunc)wrap_binaryfunc_r, \
1305 "y.__r" #NAME "__(x) <==> " #OP}, \
1306 {0} \
1307}
1308
1309BINARY(add, "x+y");
1310BINARY(sub, "x-y");
1311BINARY(mul, "x*y");
1312BINARY(div, "x/y");
1313BINARY(mod, "x%y");
1314BINARY(divmod, "divmod(x,y)");
1315BINARY(lshift, "x<<y");
1316BINARY(rshift, "x>>y");
1317BINARY(and, "x&y");
1318BINARY(xor, "x^y");
1319BINARY(or, "x|y");
1320
1321static PyObject *
1322wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1323{
1324 ternaryfunc func = (ternaryfunc)wrapped;
1325 PyObject *other;
1326 PyObject *third = Py_None;
1327
1328 /* Note: This wrapper only works for __pow__() */
1329
1330 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1331 return NULL;
1332 return (*func)(self, other, third);
1333}
1334
1335#undef TERNARY
1336#define TERNARY(NAME, OP) \
1337static struct wrapperbase tab_##NAME[] = { \
1338 {"__" #NAME "__", \
1339 (wrapperfunc)wrap_ternaryfunc, \
1340 "x.__" #NAME "__(y, z) <==> " #OP}, \
1341 {"__r" #NAME "__", \
1342 (wrapperfunc)wrap_ternaryfunc, \
1343 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1344 {0} \
1345}
1346
1347TERNARY(pow, "(x**y) % z");
1348
1349#undef UNARY
1350#define UNARY(NAME, OP) \
1351static struct wrapperbase tab_##NAME[] = { \
1352 {"__" #NAME "__", \
1353 (wrapperfunc)wrap_unaryfunc, \
1354 "x.__" #NAME "__() <==> " #OP}, \
1355 {0} \
1356}
1357
1358static PyObject *
1359wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1360{
1361 unaryfunc func = (unaryfunc)wrapped;
1362
1363 if (!PyArg_ParseTuple(args, ""))
1364 return NULL;
1365 return (*func)(self);
1366}
1367
1368UNARY(neg, "-x");
1369UNARY(pos, "+x");
1370UNARY(abs, "abs(x)");
1371UNARY(nonzero, "x != 0");
1372UNARY(invert, "~x");
1373UNARY(int, "int(x)");
1374UNARY(long, "long(x)");
1375UNARY(float, "float(x)");
1376UNARY(oct, "oct(x)");
1377UNARY(hex, "hex(x)");
1378
1379#undef IBINARY
1380#define IBINARY(NAME, OP) \
1381static struct wrapperbase tab_##NAME[] = { \
1382 {"__" #NAME "__", \
1383 (wrapperfunc)wrap_binaryfunc, \
1384 "x.__" #NAME "__(y) <==> " #OP}, \
1385 {0} \
1386}
1387
1388IBINARY(iadd, "x+=y");
1389IBINARY(isub, "x-=y");
1390IBINARY(imul, "x*=y");
1391IBINARY(idiv, "x/=y");
1392IBINARY(imod, "x%=y");
1393IBINARY(ilshift, "x<<=y");
1394IBINARY(irshift, "x>>=y");
1395IBINARY(iand, "x&=y");
1396IBINARY(ixor, "x^=y");
1397IBINARY(ior, "x|=y");
1398
1399#undef ITERNARY
1400#define ITERNARY(NAME, OP) \
1401static struct wrapperbase tab_##NAME[] = { \
1402 {"__" #NAME "__", \
1403 (wrapperfunc)wrap_ternaryfunc, \
1404 "x.__" #NAME "__(y) <==> " #OP}, \
1405 {0} \
1406}
1407
1408ITERNARY(ipow, "x = (x**y) % z");
1409
1410static struct wrapperbase tab_getitem[] = {
1411 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1412 "x.__getitem__(y) <==> x[y]"},
1413 {0}
1414};
1415
1416static PyObject *
1417wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1418{
1419 intargfunc func = (intargfunc)wrapped;
1420 int i;
1421
1422 if (!PyArg_ParseTuple(args, "i", &i))
1423 return NULL;
1424 return (*func)(self, i);
1425}
1426
1427static struct wrapperbase tab_mul_int[] = {
1428 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1429 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1430 {0}
1431};
1432
1433static struct wrapperbase tab_concat[] = {
1434 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1435 {0}
1436};
1437
1438static struct wrapperbase tab_imul_int[] = {
1439 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1440 {0}
1441};
1442
1443static struct wrapperbase tab_getitem_int[] = {
1444 {"__getitem__", (wrapperfunc)wrap_intargfunc,
1445 "x.__getitem__(i) <==> x[i]"},
1446 {0}
1447};
1448
1449static PyObject *
1450wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1451{
1452 intintargfunc func = (intintargfunc)wrapped;
1453 int i, j;
1454
1455 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1456 return NULL;
1457 return (*func)(self, i, j);
1458}
1459
1460static struct wrapperbase tab_getslice[] = {
1461 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1462 "x.__getslice__(i, j) <==> x[i:j]"},
1463 {0}
1464};
1465
1466static PyObject *
1467wrap_intobjargproc(PyObject *self, PyObject *args, void *wrapped)
1468{
1469 intobjargproc func = (intobjargproc)wrapped;
1470 int i, res;
1471 PyObject *value;
1472
1473 if (!PyArg_ParseTuple(args, "iO", &i, &value))
1474 return NULL;
1475 res = (*func)(self, i, value);
1476 if (res == -1 && PyErr_Occurred())
1477 return NULL;
1478 Py_INCREF(Py_None);
1479 return Py_None;
1480}
1481
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001482static PyObject *
1483wrap_delitem_int(PyObject *self, PyObject *args, void *wrapped)
1484{
1485 intobjargproc func = (intobjargproc)wrapped;
1486 int i, res;
1487
1488 if (!PyArg_ParseTuple(args, "i", &i))
1489 return NULL;
1490 res = (*func)(self, i, NULL);
1491 if (res == -1 && PyErr_Occurred())
1492 return NULL;
1493 Py_INCREF(Py_None);
1494 return Py_None;
1495}
1496
Tim Peters6d6c1a32001-08-02 04:15:00 +00001497static struct wrapperbase tab_setitem_int[] = {
1498 {"__setitem__", (wrapperfunc)wrap_intobjargproc,
1499 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001500 {"__delitem__", (wrapperfunc)wrap_delitem_int,
1501 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502 {0}
1503};
1504
1505static PyObject *
1506wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1507{
1508 intintobjargproc func = (intintobjargproc)wrapped;
1509 int i, j, res;
1510 PyObject *value;
1511
1512 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1513 return NULL;
1514 res = (*func)(self, i, j, value);
1515 if (res == -1 && PyErr_Occurred())
1516 return NULL;
1517 Py_INCREF(Py_None);
1518 return Py_None;
1519}
1520
1521static struct wrapperbase tab_setslice[] = {
1522 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1523 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1524 {0}
1525};
1526
1527/* XXX objobjproc is a misnomer; should be objargpred */
1528static PyObject *
1529wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1530{
1531 objobjproc func = (objobjproc)wrapped;
1532 int res;
1533 PyObject *value;
1534
1535 if (!PyArg_ParseTuple(args, "O", &value))
1536 return NULL;
1537 res = (*func)(self, value);
1538 if (res == -1 && PyErr_Occurred())
1539 return NULL;
1540 return PyInt_FromLong((long)res);
1541}
1542
1543static struct wrapperbase tab_contains[] = {
1544 {"__contains__", (wrapperfunc)wrap_objobjproc,
1545 "x.__contains__(y) <==> y in x"},
1546 {0}
1547};
1548
1549static PyObject *
1550wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1551{
1552 objobjargproc func = (objobjargproc)wrapped;
1553 int res;
1554 PyObject *key, *value;
1555
1556 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1557 return NULL;
1558 res = (*func)(self, key, value);
1559 if (res == -1 && PyErr_Occurred())
1560 return NULL;
1561 Py_INCREF(Py_None);
1562 return Py_None;
1563}
1564
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001565static PyObject *
1566wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1567{
1568 objobjargproc func = (objobjargproc)wrapped;
1569 int res;
1570 PyObject *key;
1571
1572 if (!PyArg_ParseTuple(args, "O", &key))
1573 return NULL;
1574 res = (*func)(self, key, NULL);
1575 if (res == -1 && PyErr_Occurred())
1576 return NULL;
1577 Py_INCREF(Py_None);
1578 return Py_None;
1579}
1580
Tim Peters6d6c1a32001-08-02 04:15:00 +00001581static struct wrapperbase tab_setitem[] = {
1582 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1583 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001584 {"__delitem__", (wrapperfunc)wrap_delitem,
1585 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 {0}
1587};
1588
1589static PyObject *
1590wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1591{
1592 cmpfunc func = (cmpfunc)wrapped;
1593 int res;
1594 PyObject *other;
1595
1596 if (!PyArg_ParseTuple(args, "O", &other))
1597 return NULL;
1598 res = (*func)(self, other);
1599 if (PyErr_Occurred())
1600 return NULL;
1601 return PyInt_FromLong((long)res);
1602}
1603
1604static struct wrapperbase tab_cmp[] = {
1605 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1606 "x.__cmp__(y) <==> cmp(x,y)"},
1607 {0}
1608};
1609
1610static struct wrapperbase tab_repr[] = {
1611 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1612 "x.__repr__() <==> repr(x)"},
1613 {0}
1614};
1615
1616static struct wrapperbase tab_getattr[] = {
1617 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1618 "x.__getattr__('name') <==> x.name"},
1619 {0}
1620};
1621
1622static PyObject *
1623wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1624{
1625 setattrofunc func = (setattrofunc)wrapped;
1626 int res;
1627 PyObject *name, *value;
1628
1629 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1630 return NULL;
1631 res = (*func)(self, name, value);
1632 if (res < 0)
1633 return NULL;
1634 Py_INCREF(Py_None);
1635 return Py_None;
1636}
1637
1638static PyObject *
1639wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1640{
1641 setattrofunc func = (setattrofunc)wrapped;
1642 int res;
1643 PyObject *name;
1644
1645 if (!PyArg_ParseTuple(args, "O", &name))
1646 return NULL;
1647 res = (*func)(self, name, NULL);
1648 if (res < 0)
1649 return NULL;
1650 Py_INCREF(Py_None);
1651 return Py_None;
1652}
1653
1654static struct wrapperbase tab_setattr[] = {
1655 {"__setattr__", (wrapperfunc)wrap_setattr,
1656 "x.__setattr__('name', value) <==> x.name = value"},
1657 {"__delattr__", (wrapperfunc)wrap_delattr,
1658 "x.__delattr__('name') <==> del x.name"},
1659 {0}
1660};
1661
1662static PyObject *
1663wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1664{
1665 hashfunc func = (hashfunc)wrapped;
1666 long res;
1667
1668 if (!PyArg_ParseTuple(args, ""))
1669 return NULL;
1670 res = (*func)(self);
1671 if (res == -1 && PyErr_Occurred())
1672 return NULL;
1673 return PyInt_FromLong(res);
1674}
1675
1676static struct wrapperbase tab_hash[] = {
1677 {"__hash__", (wrapperfunc)wrap_hashfunc,
1678 "x.__hash__() <==> hash(x)"},
1679 {0}
1680};
1681
1682static PyObject *
1683wrap_call(PyObject *self, PyObject *args, void *wrapped)
1684{
1685 ternaryfunc func = (ternaryfunc)wrapped;
1686
1687 /* XXX What about keyword arguments? */
1688 return (*func)(self, args, NULL);
1689}
1690
1691static struct wrapperbase tab_call[] = {
1692 {"__call__", (wrapperfunc)wrap_call,
1693 "x.__call__(...) <==> x(...)"},
1694 {0}
1695};
1696
1697static struct wrapperbase tab_str[] = {
1698 {"__str__", (wrapperfunc)wrap_unaryfunc,
1699 "x.__str__() <==> str(x)"},
1700 {0}
1701};
1702
1703static PyObject *
1704wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1705{
1706 richcmpfunc func = (richcmpfunc)wrapped;
1707 PyObject *other;
1708
1709 if (!PyArg_ParseTuple(args, "O", &other))
1710 return NULL;
1711 return (*func)(self, other, op);
1712}
1713
1714#undef RICHCMP_WRAPPER
1715#define RICHCMP_WRAPPER(NAME, OP) \
1716static PyObject * \
1717richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1718{ \
1719 return wrap_richcmpfunc(self, args, wrapped, OP); \
1720}
1721
1722RICHCMP_WRAPPER(lt, Py_LT);
1723RICHCMP_WRAPPER(le, Py_LE);
1724RICHCMP_WRAPPER(eq, Py_EQ);
1725RICHCMP_WRAPPER(ne, Py_NE);
1726RICHCMP_WRAPPER(gt, Py_GT);
1727RICHCMP_WRAPPER(ge, Py_GE);
1728
1729#undef RICHCMP_ENTRY
1730#define RICHCMP_ENTRY(NAME, EXPR) \
1731 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1732 "x.__" #NAME "__(y) <==> " EXPR}
1733
1734static struct wrapperbase tab_richcmp[] = {
1735 RICHCMP_ENTRY(lt, "x<y"),
1736 RICHCMP_ENTRY(le, "x<=y"),
1737 RICHCMP_ENTRY(eq, "x==y"),
1738 RICHCMP_ENTRY(ne, "x!=y"),
1739 RICHCMP_ENTRY(gt, "x>y"),
1740 RICHCMP_ENTRY(ge, "x>=y"),
1741 {0}
1742};
1743
1744static struct wrapperbase tab_iter[] = {
1745 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
1746 {0}
1747};
1748
1749static PyObject *
1750wrap_next(PyObject *self, PyObject *args, void *wrapped)
1751{
1752 unaryfunc func = (unaryfunc)wrapped;
1753 PyObject *res;
1754
1755 if (!PyArg_ParseTuple(args, ""))
1756 return NULL;
1757 res = (*func)(self);
1758 if (res == NULL && !PyErr_Occurred())
1759 PyErr_SetNone(PyExc_StopIteration);
1760 return res;
1761}
1762
1763static struct wrapperbase tab_next[] = {
1764 {"next", (wrapperfunc)wrap_next,
1765 "x.next() -> the next value, or raise StopIteration"},
1766 {0}
1767};
1768
1769static PyObject *
1770wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
1771{
1772 descrgetfunc func = (descrgetfunc)wrapped;
1773 PyObject *obj;
1774 PyObject *type = NULL;
1775
1776 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
1777 return NULL;
1778 if (type == NULL)
1779 type = (PyObject *)obj->ob_type;
1780 return (*func)(self, obj, type);
1781}
1782
1783static struct wrapperbase tab_descr_get[] = {
1784 {"__get__", (wrapperfunc)wrap_descr_get,
1785 "descr.__get__(obj, type) -> value"},
1786 {0}
1787};
1788
1789static PyObject *
1790wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
1791{
1792 descrsetfunc func = (descrsetfunc)wrapped;
1793 PyObject *obj, *value;
1794 int ret;
1795
1796 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
1797 return NULL;
1798 ret = (*func)(self, obj, value);
1799 if (ret < 0)
1800 return NULL;
1801 Py_INCREF(Py_None);
1802 return Py_None;
1803}
1804
1805static struct wrapperbase tab_descr_set[] = {
1806 {"__set__", (wrapperfunc)wrap_descrsetfunc,
1807 "descr.__set__(obj, value)"},
1808 {0}
1809};
1810
1811static PyObject *
1812wrap_init(PyObject *self, PyObject *args, void *wrapped)
1813{
1814 initproc func = (initproc)wrapped;
1815
1816 /* XXX What about keyword arguments? */
1817 if (func(self, args, NULL) < 0)
1818 return NULL;
1819 Py_INCREF(Py_None);
1820 return Py_None;
1821}
1822
1823static struct wrapperbase tab_init[] = {
1824 {"__init__", (wrapperfunc)wrap_init,
1825 "x.__init__(...) initializes x; "
1826 "see x.__type__.__doc__ for signature"},
1827 {0}
1828};
1829
1830static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001831tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001832{
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001833 PyTypeObject *type, *subtype;
1834 PyObject *arg0, *res;
1835
1836 if (self == NULL || !PyType_Check(self))
1837 Py_FatalError("__new__() called with non-type 'self'");
1838 type = (PyTypeObject *)self;
1839 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
1840 PyErr_SetString(PyExc_TypeError,
1841 "T.__new__(): not enough arguments");
1842 return NULL;
1843 }
1844 arg0 = PyTuple_GET_ITEM(args, 0);
1845 if (!PyType_Check(arg0)) {
1846 PyErr_SetString(PyExc_TypeError,
1847 "T.__new__(S): S is not a type object");
1848 return NULL;
1849 }
1850 subtype = (PyTypeObject *)arg0;
1851 if (!PyType_IsSubtype(subtype, type)) {
1852 PyErr_SetString(PyExc_TypeError,
1853 "T.__new__(S): S is not a subtype of T");
1854 return NULL;
1855 }
1856 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
1857 if (args == NULL)
1858 return NULL;
1859 res = type->tp_new(subtype, args, kwds);
1860 Py_DECREF(args);
1861 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001862}
1863
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001864static struct PyMethodDef tp_new_methoddef[] = {
1865 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
1866 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 {0}
1868};
1869
1870static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001871add_tp_new_wrapper(PyTypeObject *type)
1872{
1873 PyObject *func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
1874
1875 if (func == NULL)
1876 return -1;
1877 return PyDict_SetItemString(type->tp_defined, "__new__", func);
1878}
1879
1880static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001881add_operators(PyTypeObject *type)
1882{
1883 PySequenceMethods *sq;
1884 PyMappingMethods *mp;
1885 PyNumberMethods *nb;
1886
1887#undef ADD
1888#define ADD(SLOT, TABLE) \
1889 if (SLOT) { \
1890 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
1891 return -1; \
1892 }
1893
1894 if ((sq = type->tp_as_sequence) != NULL) {
1895 ADD(sq->sq_length, tab_len);
1896 ADD(sq->sq_concat, tab_concat);
1897 ADD(sq->sq_repeat, tab_mul_int);
1898 ADD(sq->sq_item, tab_getitem_int);
1899 ADD(sq->sq_slice, tab_getslice);
1900 ADD(sq->sq_ass_item, tab_setitem_int);
1901 ADD(sq->sq_ass_slice, tab_setslice);
1902 ADD(sq->sq_contains, tab_contains);
1903 ADD(sq->sq_inplace_concat, tab_iadd);
1904 ADD(sq->sq_inplace_repeat, tab_imul_int);
1905 }
1906
1907 if ((mp = type->tp_as_mapping) != NULL) {
1908 if (sq->sq_length == NULL)
1909 ADD(mp->mp_length, tab_len);
1910 ADD(mp->mp_subscript, tab_getitem);
1911 ADD(mp->mp_ass_subscript, tab_setitem);
1912 }
1913
1914 /* We don't support "old-style numbers" because their binary
1915 operators require that both arguments have the same type;
1916 the wrappers here only work for new-style numbers. */
1917 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
1918 (nb = type->tp_as_number) != NULL) {
1919 ADD(nb->nb_add, tab_add);
1920 ADD(nb->nb_subtract, tab_sub);
1921 ADD(nb->nb_multiply, tab_mul);
1922 ADD(nb->nb_divide, tab_div);
1923 ADD(nb->nb_remainder, tab_mod);
1924 ADD(nb->nb_divmod, tab_divmod);
1925 ADD(nb->nb_power, tab_pow);
1926 ADD(nb->nb_negative, tab_neg);
1927 ADD(nb->nb_positive, tab_pos);
1928 ADD(nb->nb_absolute, tab_abs);
1929 ADD(nb->nb_nonzero, tab_nonzero);
1930 ADD(nb->nb_invert, tab_invert);
1931 ADD(nb->nb_lshift, tab_lshift);
1932 ADD(nb->nb_rshift, tab_rshift);
1933 ADD(nb->nb_and, tab_and);
1934 ADD(nb->nb_xor, tab_xor);
1935 ADD(nb->nb_or, tab_or);
1936 /* We don't support coerce() -- see above comment */
1937 ADD(nb->nb_int, tab_int);
1938 ADD(nb->nb_long, tab_long);
1939 ADD(nb->nb_float, tab_float);
1940 ADD(nb->nb_oct, tab_oct);
1941 ADD(nb->nb_hex, tab_hex);
1942 ADD(nb->nb_inplace_add, tab_iadd);
1943 ADD(nb->nb_inplace_subtract, tab_isub);
1944 ADD(nb->nb_inplace_multiply, tab_imul);
1945 ADD(nb->nb_inplace_divide, tab_idiv);
1946 ADD(nb->nb_inplace_remainder, tab_imod);
1947 ADD(nb->nb_inplace_power, tab_ipow);
1948 ADD(nb->nb_inplace_lshift, tab_ilshift);
1949 ADD(nb->nb_inplace_rshift, tab_irshift);
1950 ADD(nb->nb_inplace_and, tab_iand);
1951 ADD(nb->nb_inplace_xor, tab_ixor);
1952 ADD(nb->nb_inplace_or, tab_ior);
1953 }
1954
1955 ADD(type->tp_getattro, tab_getattr);
1956 ADD(type->tp_setattro, tab_setattr);
1957 ADD(type->tp_compare, tab_cmp);
1958 ADD(type->tp_repr, tab_repr);
1959 ADD(type->tp_hash, tab_hash);
1960 ADD(type->tp_call, tab_call);
1961 ADD(type->tp_str, tab_str);
1962 ADD(type->tp_richcompare, tab_richcmp);
1963 ADD(type->tp_iter, tab_iter);
1964 ADD(type->tp_iternext, tab_next);
1965 ADD(type->tp_descr_get, tab_descr_get);
1966 ADD(type->tp_descr_set, tab_descr_set);
1967 ADD(type->tp_init, tab_init);
1968
1969 if (type->tp_new != NULL)
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001970 add_tp_new_wrapper(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001971
1972 return 0;
1973}
1974
1975/* Slot wrappers that call the corresponding __foo__ slot */
1976
1977#define SLOT0(SLOTNAME, OPNAME) \
1978static PyObject * \
1979slot_##SLOTNAME(PyObject *self) \
1980{ \
1981 return PyObject_CallMethod(self, "__" #OPNAME "__", ""); \
1982}
1983
1984#define SLOT1(SLOTNAME, OPNAME, ARG1TYPE, ARGCODES) \
1985static PyObject * \
1986slot_##SLOTNAME(PyObject *self, ARG1TYPE arg1) \
1987{ \
1988 return PyObject_CallMethod(self, "__" #OPNAME "__", #ARGCODES, arg1); \
1989}
1990
1991#define SLOT2(SLOTNAME, OPNAME, ARG1TYPE, ARG2TYPE, ARGCODES) \
1992static PyObject * \
1993slot_##SLOTNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
1994{ \
1995 return PyObject_CallMethod(self, "__" #OPNAME "__", \
1996 #ARGCODES, arg1, arg2); \
1997}
1998
1999static int
2000slot_sq_length(PyObject *self)
2001{
2002 PyObject *res = PyObject_CallMethod(self, "__len__", "");
2003
2004 if (res == NULL)
2005 return -1;
2006 return (int)PyInt_AsLong(res);
2007}
2008
2009SLOT1(sq_concat, add, PyObject *, O);
2010SLOT1(sq_repeat, mul, int, i);
2011SLOT1(sq_item, getitem, int, i);
2012SLOT2(sq_slice, getslice, int, int, ii);
2013
2014static int
2015slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2016{
2017 PyObject *res;
2018
2019 if (value == NULL)
2020 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2021 else
2022 res = PyObject_CallMethod(self, "__setitem__",
2023 "iO", index, value);
2024 if (res == NULL)
2025 return -1;
2026 Py_DECREF(res);
2027 return 0;
2028}
2029
2030static int
2031slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2032{
2033 PyObject *res;
2034
2035 if (value == NULL)
2036 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2037 else
2038 res = PyObject_CallMethod(self, "__setslice__",
2039 "iiO", i, j, value);
2040 if (res == NULL)
2041 return -1;
2042 Py_DECREF(res);
2043 return 0;
2044}
2045
2046static int
2047slot_sq_contains(PyObject *self, PyObject *value)
2048{
2049 PyObject *res = PyObject_CallMethod(self, "__contains__", "O", value);
2050 int r;
2051
2052 if (res == NULL)
2053 return -1;
2054 r = PyInt_AsLong(res);
2055 Py_DECREF(res);
2056 return r;
2057}
2058
2059SLOT1(sq_inplace_concat, iadd, PyObject *, O);
2060SLOT1(sq_inplace_repeat, imul, int, i);
2061
2062#define slot_mp_length slot_sq_length
2063
2064SLOT1(mp_subscript, getitem, PyObject *, O);
2065
2066static int
2067slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2068{
2069 PyObject *res;
2070
2071 if (value == NULL)
2072 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2073 else
2074 res = PyObject_CallMethod(self, "__setitem__",
2075 "OO", key, value);
2076 if (res == NULL)
2077 return -1;
2078 Py_DECREF(res);
2079 return 0;
2080}
2081
2082/* XXX the numerical slots should call the reverse operators too;
2083 but how do they know their type? */
2084SLOT1(nb_add, add, PyObject *, O);
2085SLOT1(nb_subtract, sub, PyObject *, O);
2086SLOT1(nb_multiply, mul, PyObject *, O);
2087SLOT1(nb_divide, div, PyObject *, O);
2088SLOT1(nb_remainder, mod, PyObject *, O);
2089SLOT1(nb_divmod, divmod, PyObject *, O);
2090SLOT2(nb_power, pow, PyObject *, PyObject *, OO);
2091SLOT0(nb_negative, neg);
2092SLOT0(nb_positive, pos);
2093SLOT0(nb_absolute, abs);
2094
2095static int
2096slot_nb_nonzero(PyObject *self)
2097{
2098 PyObject *res = PyObject_CallMethod(self, "__nonzero__", "");
2099
2100 if (res == NULL)
2101 return -1;
2102 return (int)PyInt_AsLong(res);
2103}
2104
2105SLOT0(nb_invert, invert);
2106SLOT1(nb_lshift, lshift, PyObject *, O);
2107SLOT1(nb_rshift, rshift, PyObject *, O);
2108SLOT1(nb_and, and, PyObject *, O);
2109SLOT1(nb_xor, xor, PyObject *, O);
2110SLOT1(nb_or, or, PyObject *, O);
2111/* Not coerce() */
2112SLOT0(nb_int, int);
2113SLOT0(nb_long, long);
2114SLOT0(nb_float, float);
2115SLOT0(nb_oct, oct);
2116SLOT0(nb_hex, hex);
2117SLOT1(nb_inplace_add, iadd, PyObject *, O);
2118SLOT1(nb_inplace_subtract, isub, PyObject *, O);
2119SLOT1(nb_inplace_multiply, imul, PyObject *, O);
2120SLOT1(nb_inplace_divide, idiv, PyObject *, O);
2121SLOT1(nb_inplace_remainder, imod, PyObject *, O);
2122SLOT2(nb_inplace_power, ipow, PyObject *, PyObject *, OO);
2123SLOT1(nb_inplace_lshift, ilshift, PyObject *, O);
2124SLOT1(nb_inplace_rshift, irshift, PyObject *, O);
2125SLOT1(nb_inplace_and, iand, PyObject *, O);
2126SLOT1(nb_inplace_xor, ixor, PyObject *, O);
2127SLOT1(nb_inplace_or, ior, PyObject *, O);
2128
2129static int
2130slot_tp_compare(PyObject *self, PyObject *other)
2131{
2132 PyObject *res = PyObject_CallMethod(self, "__cmp__", "O", other);
2133 long r;
2134
2135 if (res == NULL)
2136 return -1;
2137 r = PyInt_AsLong(res);
2138 Py_DECREF(res);
2139 return (int)r;
2140}
2141
2142SLOT0(tp_repr, repr);
2143
2144static long
2145slot_tp_hash(PyObject *self)
2146{
2147 PyObject *res = PyObject_CallMethod(self, "__hash__", "");
2148 long h;
2149
2150 if (res == NULL)
2151 return -1;
2152 h = PyInt_AsLong(res);
2153 if (h == -1 && !PyErr_Occurred())
2154 h = -2;
2155 return h;
2156}
2157
2158static PyObject *
2159slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2160{
2161 PyObject *meth = PyObject_GetAttrString(self, "__call__");
2162 PyObject *res;
2163
2164 if (meth == NULL)
2165 return NULL;
2166 res = PyObject_Call(meth, args, kwds);
2167 Py_DECREF(meth);
2168 return res;
2169}
2170
2171SLOT0(tp_str, str);
2172
2173static PyObject *
2174slot_tp_getattro(PyObject *self, PyObject *name)
2175{
2176 PyTypeObject *tp = self->ob_type;
2177 PyObject *dict = NULL;
2178 PyObject *getattr;
2179
2180 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE)
2181 dict = tp->tp_dict;
2182 if (dict == NULL) {
2183 PyErr_Format(PyExc_SystemError,
2184 "'%.100s' type object has no __dict__???",
2185 tp->tp_name);
2186 return NULL;
2187 }
2188 getattr = PyDict_GetItemString(dict, "__getattr__");
2189 if (getattr == NULL) {
2190 PyErr_SetString(PyExc_AttributeError, "__getattr__");
2191 return NULL;
2192 }
2193 return PyObject_CallFunction(getattr, "OO", self, name);
2194}
2195
2196static int
2197slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2198{
2199 PyObject *res;
2200
2201 if (value == NULL)
2202 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2203 else
2204 res = PyObject_CallMethod(self, "__setattr__",
2205 "OO", name, value);
2206 if (res == NULL)
2207 return -1;
2208 Py_DECREF(res);
2209 return 0;
2210}
2211
2212/* Map rich comparison operators to their __xx__ namesakes */
2213static char *name_op[] = {
2214 "__lt__",
2215 "__le__",
2216 "__eq__",
2217 "__ne__",
2218 "__gt__",
2219 "__ge__",
2220};
2221
2222static PyObject *
2223slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2224{
2225 PyObject *meth = PyObject_GetAttrString(self, name_op[op]);
2226 PyObject *res;
2227
2228 if (meth == NULL)
2229 return NULL;
2230 res = PyObject_CallFunction(meth, "O", other);
2231 Py_DECREF(meth);
2232 return res;
2233}
2234
2235SLOT0(tp_iter, iter);
2236
2237static PyObject *
2238slot_tp_iternext(PyObject *self)
2239{
2240 return PyObject_CallMethod(self, "next", "");
2241}
2242
2243SLOT2(tp_descr_get, get, PyObject *, PyObject *, OO);
2244
2245static int
2246slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2247{
2248 PyObject *res = PyObject_CallMethod(self, "__set__",
2249 "OO", target, value);
2250 if (res == NULL)
2251 return -1;
2252 Py_DECREF(res);
2253 return 0;
2254}
2255
2256static int
2257slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2258{
2259 PyObject *meth = PyObject_GetAttrString(self, "__init__");
2260 PyObject *res;
2261
2262 if (meth == NULL)
2263 return -1;
2264 res = PyObject_Call(meth, args, kwds);
2265 Py_DECREF(meth);
2266 if (res == NULL)
2267 return -1;
2268 Py_DECREF(res);
2269 return 0;
2270}
2271
2272static PyObject *
2273slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2274{
2275 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2276 PyObject *newargs, *x;
2277 int i, n;
2278
2279 if (func == NULL)
2280 return NULL;
2281 assert(PyTuple_Check(args));
2282 n = PyTuple_GET_SIZE(args);
2283 newargs = PyTuple_New(n+1);
2284 if (newargs == NULL)
2285 return NULL;
2286 Py_INCREF(type);
2287 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2288 for (i = 0; i < n; i++) {
2289 x = PyTuple_GET_ITEM(args, i);
2290 Py_INCREF(x);
2291 PyTuple_SET_ITEM(newargs, i+1, x);
2292 }
2293 x = PyObject_Call(func, newargs, kwds);
2294 Py_DECREF(func);
2295 return x;
2296}
2297
2298static void
2299override_slots(PyTypeObject *type, PyObject *dict)
2300{
2301 PySequenceMethods *sq = type->tp_as_sequence;
2302 PyMappingMethods *mp = type->tp_as_mapping;
2303 PyNumberMethods *nb = type->tp_as_number;
2304
2305#define SQSLOT(OPNAME, SLOTNAME) \
2306 if (PyDict_GetItemString(dict, OPNAME)) { \
2307 sq->SLOTNAME = slot_##SLOTNAME; \
2308 }
2309
2310#define MPSLOT(OPNAME, SLOTNAME) \
2311 if (PyDict_GetItemString(dict, OPNAME)) { \
2312 mp->SLOTNAME = slot_##SLOTNAME; \
2313 }
2314
2315#define NBSLOT(OPNAME, SLOTNAME) \
2316 if (PyDict_GetItemString(dict, OPNAME)) { \
2317 nb->SLOTNAME = slot_##SLOTNAME; \
2318 }
2319
2320#define TPSLOT(OPNAME, SLOTNAME) \
2321 if (PyDict_GetItemString(dict, OPNAME)) { \
2322 type->SLOTNAME = slot_##SLOTNAME; \
2323 }
2324
2325 SQSLOT("__len__", sq_length);
2326 SQSLOT("__add__", sq_concat);
2327 SQSLOT("__mul__", sq_repeat);
2328 SQSLOT("__getitem__", sq_item);
2329 SQSLOT("__getslice__", sq_slice);
2330 SQSLOT("__setitem__", sq_ass_item);
2331 SQSLOT("__delitem__", sq_ass_item);
2332 SQSLOT("__setslice__", sq_ass_slice);
2333 SQSLOT("__delslice__", sq_ass_slice);
2334 SQSLOT("__contains__", sq_contains);
2335 SQSLOT("__iadd__", sq_inplace_concat);
2336 SQSLOT("__imul__", sq_inplace_repeat);
2337
2338 MPSLOT("__len__", mp_length);
2339 MPSLOT("__getitem__", mp_subscript);
2340 MPSLOT("__setitem__", mp_ass_subscript);
2341 MPSLOT("__delitem__", mp_ass_subscript);
2342
2343 NBSLOT("__add__", nb_add);
2344 NBSLOT("__sub__", nb_subtract);
2345 NBSLOT("__mul__", nb_multiply);
2346 NBSLOT("__div__", nb_divide);
2347 NBSLOT("__mod__", nb_remainder);
2348 NBSLOT("__divmod__", nb_divmod);
2349 NBSLOT("__pow__", nb_power);
2350 NBSLOT("__neg__", nb_negative);
2351 NBSLOT("__pos__", nb_positive);
2352 NBSLOT("__abs__", nb_absolute);
2353 NBSLOT("__nonzero__", nb_nonzero);
2354 NBSLOT("__invert__", nb_invert);
2355 NBSLOT("__lshift__", nb_lshift);
2356 NBSLOT("__rshift__", nb_rshift);
2357 NBSLOT("__and__", nb_and);
2358 NBSLOT("__xor__", nb_xor);
2359 NBSLOT("__or__", nb_or);
2360 /* Not coerce() */
2361 NBSLOT("__int__", nb_int);
2362 NBSLOT("__long__", nb_long);
2363 NBSLOT("__float__", nb_float);
2364 NBSLOT("__oct__", nb_oct);
2365 NBSLOT("__hex__", nb_hex);
2366 NBSLOT("__iadd__", nb_inplace_add);
2367 NBSLOT("__isub__", nb_inplace_subtract);
2368 NBSLOT("__imul__", nb_inplace_multiply);
2369 NBSLOT("__idiv__", nb_inplace_divide);
2370 NBSLOT("__imod__", nb_inplace_remainder);
2371 NBSLOT("__ipow__", nb_inplace_power);
2372 NBSLOT("__ilshift__", nb_inplace_lshift);
2373 NBSLOT("__irshift__", nb_inplace_rshift);
2374 NBSLOT("__iand__", nb_inplace_and);
2375 NBSLOT("__ixor__", nb_inplace_xor);
2376 NBSLOT("__ior__", nb_inplace_or);
2377
2378 if (PyDict_GetItemString(dict, "__str__") ||
2379 PyDict_GetItemString(dict, "__repr__"))
2380 type->tp_print = NULL;
2381
2382 TPSLOT("__cmp__", tp_compare);
2383 TPSLOT("__repr__", tp_repr);
2384 TPSLOT("__hash__", tp_hash);
2385 TPSLOT("__call__", tp_call);
2386 TPSLOT("__str__", tp_str);
2387 TPSLOT("__getattr__", tp_getattro);
2388 TPSLOT("__setattr__", tp_setattro);
2389 TPSLOT("__lt__", tp_richcompare);
2390 TPSLOT("__le__", tp_richcompare);
2391 TPSLOT("__eq__", tp_richcompare);
2392 TPSLOT("__ne__", tp_richcompare);
2393 TPSLOT("__gt__", tp_richcompare);
2394 TPSLOT("__ge__", tp_richcompare);
2395 TPSLOT("__iter__", tp_iter);
2396 TPSLOT("next", tp_iternext);
2397 TPSLOT("__get__", tp_descr_get);
2398 TPSLOT("__set__", tp_descr_set);
2399 TPSLOT("__init__", tp_init);
2400 TPSLOT("__new__", tp_new);
2401}