blob: 9f2857cb2dc3f04b1ffa7d4832f32729c35b114a [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) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000390 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000391 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 *);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000450staticforward int add_tp_new_wrapper(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451
452static PyObject *
453type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
454{
455 PyObject *name, *bases, *dict;
456 static char *kwlist[] = {"name", "bases", "dict", 0};
457 PyObject *slots, *tmp;
458 PyTypeObject *type, *base, *tmptype;
459 etype *et;
460 struct memberlist *mp;
461 int i, nbases, nslots, slotoffset, dynamic;
462
463 if (metatype == &PyType_Type &&
464 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
465 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
466 /* type(x) -> x.__class__ */
467 PyObject *x = PyTuple_GET_ITEM(args, 0);
468 Py_INCREF(x->ob_type);
469 return (PyObject *) x->ob_type;
470 }
471
472 /* Check arguments */
473 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
474 &name,
475 &PyTuple_Type, &bases,
476 &PyDict_Type, &dict))
477 return NULL;
478
479 /* Determine the proper metatype to deal with this,
480 and check for metatype conflicts while we're at it.
481 Note that if some other metatype wins to contract,
482 it's possible that its instances are not types. */
483 nbases = PyTuple_GET_SIZE(bases);
484 for (i = 0; i < nbases; i++) {
485 tmp = PyTuple_GET_ITEM(bases, i);
486 tmptype = tmp->ob_type;
487 if (PyType_IsSubtype(metatype, tmptype))
488 continue;
489 if (PyType_IsSubtype(tmptype, metatype)) {
490 metatype = tmptype;
491 continue;
492 }
493 PyErr_SetString(PyExc_TypeError,
494 "metatype conflict among bases");
495 return NULL;
496 }
497 if (metatype->tp_new != type_new) /* Pass it to the winner */
498 return metatype->tp_new(metatype, args, kwds);
499
500 /* Adjust for empty tuple bases */
501 if (nbases == 0) {
502 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
503 if (bases == NULL)
504 return NULL;
505 nbases = 1;
506 }
507 else
508 Py_INCREF(bases);
509
510 /* XXX From here until type is allocated, "return NULL" leaks bases! */
511
512 /* Calculate best base, and check that all bases are type objects */
513 base = best_base(bases);
514 if (base == NULL)
515 return NULL;
516 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
517 PyErr_Format(PyExc_TypeError,
518 "type '%.100s' is not an acceptable base type",
519 base->tp_name);
520 return NULL;
521 }
522
523 /* Should this be a dynamic class (i.e. modifiable __dict__)? */
524 tmp = PyDict_GetItemString(dict, "__dynamic__");
525 if (tmp != NULL) {
526 /* The class author has a preference */
527 dynamic = PyObject_IsTrue(tmp);
528 Py_DECREF(tmp);
529 if (dynamic < 0)
530 return NULL;
531 }
532 else {
533 /* Make a new class dynamic if any of its bases is dynamic.
534 This is not always the same as inheriting the __dynamic__
535 class attribute! */
536 dynamic = 0;
537 for (i = 0; i < nbases; i++) {
538 tmptype = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
539 if (tmptype->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
540 dynamic = 1;
541 break;
542 }
543 }
544 }
545
546 /* Check for a __slots__ sequence variable in dict, and count it */
547 slots = PyDict_GetItemString(dict, "__slots__");
548 nslots = 0;
549 if (slots != NULL) {
550 /* Make it into a tuple */
551 if (PyString_Check(slots))
552 slots = Py_BuildValue("(O)", slots);
553 else
554 slots = PySequence_Tuple(slots);
555 if (slots == NULL)
556 return NULL;
557 nslots = PyTuple_GET_SIZE(slots);
558 for (i = 0; i < nslots; i++) {
559 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
560 PyErr_SetString(PyExc_TypeError,
561 "__slots__ must be a sequence of strings");
562 Py_DECREF(slots);
563 return NULL;
564 }
565 }
566 }
567 if (slots == NULL && base->tp_dictoffset == 0 &&
568 (base->tp_setattro == PyObject_GenericSetAttr ||
569 base->tp_setattro == NULL))
570 nslots = 1;
571
572 /* XXX From here until type is safely allocated,
573 "return NULL" may leak slots! */
574
575 /* Allocate the type object */
576 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
577 if (type == NULL)
578 return NULL;
579
580 /* Keep name and slots alive in the extended type object */
581 et = (etype *)type;
582 Py_INCREF(name);
583 et->name = name;
584 et->slots = slots;
585
586 /* Initialize essential fields */
587 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
588 Py_TPFLAGS_BASETYPE;
589 if (dynamic)
590 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
591 type->tp_as_number = &et->as_number;
592 type->tp_as_sequence = &et->as_sequence;
593 type->tp_as_mapping = &et->as_mapping;
594 type->tp_as_buffer = &et->as_buffer;
595 type->tp_name = PyString_AS_STRING(name);
596
597 /* Set tp_base and tp_bases */
598 type->tp_bases = bases;
599 Py_INCREF(base);
600 type->tp_base = base;
601
602 /* Initialize tp_defined from passed-in dict */
603 type->tp_defined = dict = PyDict_Copy(dict);
604 if (dict == NULL) {
605 Py_DECREF(type);
606 return NULL;
607 }
608
609 /* Special-case __new__: if it's a plain function,
610 make it a static function */
611 tmp = PyDict_GetItemString(dict, "__new__");
612 if (tmp != NULL && PyFunction_Check(tmp)) {
613 tmp = PyStaticMethod_New(tmp);
614 if (tmp == NULL) {
615 Py_DECREF(type);
616 return NULL;
617 }
618 PyDict_SetItemString(dict, "__new__", tmp);
619 Py_DECREF(tmp);
620 }
621
622 /* Add descriptors for custom slots from __slots__, or for __dict__ */
623 mp = et->members;
624 slotoffset = PyType_BASICSIZE(base);
625 if (slots != NULL) {
626 for (i = 0; i < nslots; i++, mp++) {
627 mp->name = PyString_AS_STRING(
628 PyTuple_GET_ITEM(slots, i));
629 mp->type = T_OBJECT;
630 mp->offset = slotoffset;
631 slotoffset += sizeof(PyObject *);
632 }
633 }
634 else if (nslots) {
635 type->tp_dictoffset = slotoffset;
636 mp->name = "__dict__";
637 mp->type = T_OBJECT;
638 mp->offset = slotoffset;
639 mp->readonly = 1;
640 slotoffset += sizeof(PyObject *);
641 }
642 type->tp_basicsize = slotoffset;
643 add_members(type, et->members);
644
645 /* Special case some slots */
646 if (type->tp_dictoffset != 0 || nslots > 0) {
647 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
648 type->tp_getattro = PyObject_GenericGetAttr;
649 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
650 type->tp_setattro = PyObject_GenericSetAttr;
651 }
652 type->tp_dealloc = subtype_dealloc;
653
654 /* Always override allocation strategy to use regular heap */
655 type->tp_alloc = PyType_GenericAlloc;
656 type->tp_free = _PyObject_Del;
657
658 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000659 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660 Py_DECREF(type);
661 return NULL;
662 }
663
664 /* Override slots that deserve it */
665 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000666
667 /* Special hack for __new__ */
668 if (type->tp_new == NULL) {
669 /* Can't do this earlier, or some nasty recursion happens. */
670 type->tp_new = PyType_GenericNew;
671 if (add_tp_new_wrapper(type) < 0) {
672 Py_DECREF(type);
673 return NULL;
674 }
675 }
676
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677 return (PyObject *)type;
678}
679
680/* Internal API to look for a name through the MRO.
681 This returns a borrowed reference, and doesn't set an exception! */
682PyObject *
683_PyType_Lookup(PyTypeObject *type, PyObject *name)
684{
685 int i, n;
686 PyObject *mro, *res, *dict;
687
688 /* For static types, look in tp_dict */
689 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
690 dict = type->tp_dict;
691 assert(dict && PyDict_Check(dict));
692 return PyDict_GetItem(dict, name);
693 }
694
695 /* For dynamic types, look in tp_defined of types in MRO */
696 mro = type->tp_mro;
697 assert(PyTuple_Check(mro));
698 n = PyTuple_GET_SIZE(mro);
699 for (i = 0; i < n; i++) {
700 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
701 assert(PyType_Check(type));
702 dict = type->tp_defined;
703 assert(dict && PyDict_Check(dict));
704 res = PyDict_GetItem(dict, name);
705 if (res != NULL)
706 return res;
707 }
708 return NULL;
709}
710
711/* This is similar to PyObject_GenericGetAttr(),
712 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
713static PyObject *
714type_getattro(PyTypeObject *type, PyObject *name)
715{
716 PyTypeObject *metatype = type->ob_type;
717 PyObject *descr, *res;
718 descrgetfunc f;
719
720 /* Initialize this type (we'll assume the metatype is initialized) */
721 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000722 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000723 return NULL;
724 }
725
726 /* Get a descriptor from the metatype */
727 descr = _PyType_Lookup(metatype, name);
728 f = NULL;
729 if (descr != NULL) {
730 f = descr->ob_type->tp_descr_get;
731 if (f != NULL && PyDescr_IsData(descr))
732 return f(descr,
733 (PyObject *)type, (PyObject *)metatype);
734 }
735
736 /* Look in tp_defined of this type and its bases */
737 res = _PyType_Lookup(type, name);
738 if (res != NULL) {
739 f = res->ob_type->tp_descr_get;
740 if (f != NULL)
741 return f(res, (PyObject *)NULL, (PyObject *)type);
742 Py_INCREF(res);
743 return res;
744 }
745
746 /* Use the descriptor from the metatype */
747 if (f != NULL) {
748 res = f(descr, (PyObject *)type, (PyObject *)metatype);
749 return res;
750 }
751 if (descr != NULL) {
752 Py_INCREF(descr);
753 return descr;
754 }
755
756 /* Give up */
757 PyErr_Format(PyExc_AttributeError,
758 "type object '%.50s' has no attribute '%.400s'",
759 type->tp_name, PyString_AS_STRING(name));
760 return NULL;
761}
762
763static int
764type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
765{
766 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
767 return PyObject_GenericSetAttr((PyObject *)type, name, value);
768 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
769 return -1;
770}
771
772static void
773type_dealloc(PyTypeObject *type)
774{
775 etype *et;
776
777 /* Assert this is a heap-allocated type object */
778 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
779 et = (etype *)type;
780 Py_XDECREF(type->tp_base);
781 Py_XDECREF(type->tp_dict);
782 Py_XDECREF(type->tp_bases);
783 Py_XDECREF(type->tp_mro);
784 Py_XDECREF(type->tp_defined);
785 /* XXX more? */
786 Py_XDECREF(et->name);
787 Py_XDECREF(et->slots);
788 type->ob_type->tp_free((PyObject *)type);
789}
790
791static PyMethodDef type_methods[] = {
792 {"mro", mro_external, METH_VARARGS,
793 "mro() -> list\nreturn a type's method resolution order"},
794 {0}
795};
796
797static char type_doc[] =
798"type(object) -> the object's type\n"
799"type(name, bases, dict) -> a new type";
800
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000801PyTypeObject PyType_Type = {
802 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000803 0, /* ob_size */
804 "type", /* tp_name */
805 sizeof(etype), /* tp_basicsize */
806 sizeof(struct memberlist), /* tp_itemsize */
807 (destructor)type_dealloc, /* tp_dealloc */
808 0, /* tp_print */
809 0, /* tp_getattr */
810 0, /* tp_setattr */
811 type_compare, /* tp_compare */
812 (reprfunc)type_repr, /* tp_repr */
813 0, /* tp_as_number */
814 0, /* tp_as_sequence */
815 0, /* tp_as_mapping */
816 (hashfunc)_Py_HashPointer, /* tp_hash */
817 (ternaryfunc)type_call, /* tp_call */
818 0, /* tp_str */
819 (getattrofunc)type_getattro, /* tp_getattro */
820 (setattrofunc)type_setattro, /* tp_setattro */
821 0, /* tp_as_buffer */
822 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
823 type_doc, /* tp_doc */
824 0, /* tp_traverse */
825 0, /* tp_clear */
826 0, /* tp_richcompare */
827 0, /* tp_weaklistoffset */
828 0, /* tp_iter */
829 0, /* tp_iternext */
830 type_methods, /* tp_methods */
831 type_members, /* tp_members */
832 type_getsets, /* tp_getset */
833 0, /* tp_base */
834 0, /* tp_dict */
835 0, /* tp_descr_get */
836 0, /* tp_descr_set */
837 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
838 0, /* tp_init */
839 0, /* tp_alloc */
840 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000841};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842
843
844/* The base type of all types (eventually)... except itself. */
845
846static int
847object_init(PyObject *self, PyObject *args, PyObject *kwds)
848{
849 return 0;
850}
851
852static void
853object_dealloc(PyObject *self)
854{
855 self->ob_type->tp_free(self);
856}
857
858static void
859object_free(PyObject *self)
860{
861 PyObject_Del(self);
862}
863
864static struct memberlist object_members[] = {
865 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
866 {0}
867};
868
869PyTypeObject PyBaseObject_Type = {
870 PyObject_HEAD_INIT(&PyType_Type)
871 0, /* ob_size */
872 "object", /* tp_name */
873 sizeof(PyObject), /* tp_basicsize */
874 0, /* tp_itemsize */
875 (destructor)object_dealloc, /* tp_dealloc */
876 0, /* tp_print */
877 0, /* tp_getattr */
878 0, /* tp_setattr */
879 0, /* tp_compare */
880 0, /* tp_repr */
881 0, /* tp_as_number */
882 0, /* tp_as_sequence */
883 0, /* tp_as_mapping */
884 0, /* tp_hash */
885 0, /* tp_call */
886 0, /* tp_str */
887 PyObject_GenericGetAttr, /* tp_getattro */
888 0, /* tp_setattro */
889 0, /* tp_as_buffer */
890 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
891 "The most base type", /* tp_doc */
892 0, /* tp_traverse */
893 0, /* tp_clear */
894 0, /* tp_richcompare */
895 0, /* tp_weaklistoffset */
896 0, /* tp_iter */
897 0, /* tp_iternext */
898 0, /* tp_methods */
899 object_members, /* tp_members */
900 0, /* tp_getset */
901 0, /* tp_base */
902 0, /* tp_dict */
903 0, /* tp_descr_get */
904 0, /* tp_descr_set */
905 0, /* tp_dictoffset */
906 object_init, /* tp_init */
907 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumf040ede2001-08-07 16:40:56 +0000908 0, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000909 object_free, /* tp_free */
910};
911
912
913/* Initialize the __dict__ in a type object */
914
915static int
916add_methods(PyTypeObject *type, PyMethodDef *meth)
917{
918 PyObject *dict = type->tp_defined;
919
920 for (; meth->ml_name != NULL; meth++) {
921 PyObject *descr;
922 if (PyDict_GetItemString(dict, meth->ml_name))
923 continue;
924 descr = PyDescr_NewMethod(type, meth);
925 if (descr == NULL)
926 return -1;
927 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
928 return -1;
929 Py_DECREF(descr);
930 }
931 return 0;
932}
933
934static int
Guido van Rossumf040ede2001-08-07 16:40:56 +0000935add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000936{
937 PyObject *dict = type->tp_defined;
938
Guido van Rossumf040ede2001-08-07 16:40:56 +0000939 for (; wraps->name != NULL; wraps++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000940 PyObject *descr;
Guido van Rossumf040ede2001-08-07 16:40:56 +0000941 if (PyDict_GetItemString(dict, wraps->name))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000942 continue;
Guido van Rossumf040ede2001-08-07 16:40:56 +0000943 descr = PyDescr_NewWrapper(type, wraps, wrapped);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000944 if (descr == NULL)
945 return -1;
Guido van Rossumf040ede2001-08-07 16:40:56 +0000946 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000947 return -1;
948 Py_DECREF(descr);
949 }
950 return 0;
951}
952
953static int
Tim Peters6d6c1a32001-08-02 04:15:00 +0000954add_members(PyTypeObject *type, struct memberlist *memb)
955{
956 PyObject *dict = type->tp_defined;
957
958 for (; memb->name != NULL; memb++) {
959 PyObject *descr;
960 if (PyDict_GetItemString(dict, memb->name))
961 continue;
962 descr = PyDescr_NewMember(type, memb);
963 if (descr == NULL)
964 return -1;
965 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
966 return -1;
967 Py_DECREF(descr);
968 }
969 return 0;
970}
971
972static int
973add_getset(PyTypeObject *type, struct getsetlist *gsp)
974{
975 PyObject *dict = type->tp_defined;
976
977 for (; gsp->name != NULL; gsp++) {
978 PyObject *descr;
979 if (PyDict_GetItemString(dict, gsp->name))
980 continue;
981 descr = PyDescr_NewGetSet(type, gsp);
982
983 if (descr == NULL)
984 return -1;
985 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
986 return -1;
987 Py_DECREF(descr);
988 }
989 return 0;
990}
991
992staticforward int add_operators(PyTypeObject *);
993
994static int
995inherit_slots(PyTypeObject *type, PyTypeObject *base)
996{
997 int oldsize, newsize;
998
999#undef COPYSLOT
1000#undef COPYNUM
1001#undef COPYSEQ
1002#undef COPYMAP
1003#define COPYSLOT(SLOT) \
1004 if (!type->SLOT) type->SLOT = base->SLOT
1005
1006#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1007#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1008#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1009
1010 if (type->tp_as_number == NULL)
1011 type->tp_as_number = base->tp_as_number;
1012 else if (base->tp_as_number) {
1013 COPYNUM(nb_add);
1014 COPYNUM(nb_subtract);
1015 COPYNUM(nb_multiply);
1016 COPYNUM(nb_divide);
1017 COPYNUM(nb_remainder);
1018 COPYNUM(nb_divmod);
1019 COPYNUM(nb_power);
1020 COPYNUM(nb_negative);
1021 COPYNUM(nb_positive);
1022 COPYNUM(nb_absolute);
1023 COPYNUM(nb_nonzero);
1024 COPYNUM(nb_invert);
1025 COPYNUM(nb_lshift);
1026 COPYNUM(nb_rshift);
1027 COPYNUM(nb_and);
1028 COPYNUM(nb_xor);
1029 COPYNUM(nb_or);
1030 COPYNUM(nb_coerce);
1031 COPYNUM(nb_int);
1032 COPYNUM(nb_long);
1033 COPYNUM(nb_float);
1034 COPYNUM(nb_oct);
1035 COPYNUM(nb_hex);
1036 COPYNUM(nb_inplace_add);
1037 COPYNUM(nb_inplace_subtract);
1038 COPYNUM(nb_inplace_multiply);
1039 COPYNUM(nb_inplace_divide);
1040 COPYNUM(nb_inplace_remainder);
1041 COPYNUM(nb_inplace_power);
1042 COPYNUM(nb_inplace_lshift);
1043 COPYNUM(nb_inplace_rshift);
1044 COPYNUM(nb_inplace_and);
1045 COPYNUM(nb_inplace_xor);
1046 COPYNUM(nb_inplace_or);
1047 }
1048
1049 if (type->tp_as_sequence == NULL)
1050 type->tp_as_sequence = base->tp_as_sequence;
1051 else if (base->tp_as_sequence) {
1052 COPYSEQ(sq_length);
1053 COPYSEQ(sq_concat);
1054 COPYSEQ(sq_repeat);
1055 COPYSEQ(sq_item);
1056 COPYSEQ(sq_slice);
1057 COPYSEQ(sq_ass_item);
1058 COPYSEQ(sq_ass_slice);
1059 COPYSEQ(sq_contains);
1060 COPYSEQ(sq_inplace_concat);
1061 COPYSEQ(sq_inplace_repeat);
1062 }
1063
1064 if (type->tp_as_mapping == NULL)
1065 type->tp_as_mapping = base->tp_as_mapping;
1066 else if (base->tp_as_mapping) {
1067 COPYMAP(mp_length);
1068 COPYMAP(mp_subscript);
1069 COPYMAP(mp_ass_subscript);
1070 }
1071
1072 /* Special flag magic */
1073 if (!type->tp_as_buffer && base->tp_as_buffer) {
1074 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1075 type->tp_flags |=
1076 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1077 }
1078 if (!type->tp_as_sequence && base->tp_as_sequence) {
1079 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1080 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1081 }
1082 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1083 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1084 if ((!type->tp_as_number && base->tp_as_number) ||
1085 (!type->tp_as_sequence && base->tp_as_sequence)) {
1086 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1087 if (!type->tp_as_number && !type->tp_as_sequence) {
1088 type->tp_flags |= base->tp_flags &
1089 Py_TPFLAGS_HAVE_INPLACEOPS;
1090 }
1091 }
1092 /* Wow */
1093 }
1094 if (!type->tp_as_number && base->tp_as_number) {
1095 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1096 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1097 }
1098
1099 /* Copying basicsize is connected to the GC flags */
1100 oldsize = PyType_BASICSIZE(base);
1101 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1102 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1103 (base->tp_flags & Py_TPFLAGS_GC) &&
1104 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1105 (!type->tp_traverse && !type->tp_clear)) {
1106 type->tp_flags |= Py_TPFLAGS_GC;
1107 COPYSLOT(tp_traverse);
1108 COPYSLOT(tp_clear);
1109 }
1110 PyType_SET_BASICSIZE(type, newsize);
1111
1112 COPYSLOT(tp_itemsize);
1113 COPYSLOT(tp_dealloc);
1114 COPYSLOT(tp_print);
1115 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1116 type->tp_getattr = base->tp_getattr;
1117 type->tp_getattro = base->tp_getattro;
1118 }
1119 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1120 type->tp_setattr = base->tp_setattr;
1121 type->tp_setattro = base->tp_setattro;
1122 }
1123 /* tp_compare see tp_richcompare */
1124 COPYSLOT(tp_repr);
1125 COPYSLOT(tp_hash);
1126 COPYSLOT(tp_call);
1127 COPYSLOT(tp_str);
1128 COPYSLOT(tp_as_buffer);
1129 COPYSLOT(tp_flags);
1130 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
1131 if (type->tp_compare == NULL && type->tp_richcompare == NULL) {
1132 type->tp_compare = base->tp_compare;
1133 type->tp_richcompare = base->tp_richcompare;
1134 }
1135 }
1136 else {
1137 COPYSLOT(tp_compare);
1138 }
1139 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1140 COPYSLOT(tp_weaklistoffset);
1141 }
1142 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1143 COPYSLOT(tp_iter);
1144 COPYSLOT(tp_iternext);
1145 }
1146 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1147 COPYSLOT(tp_descr_get);
1148 COPYSLOT(tp_descr_set);
1149 COPYSLOT(tp_dictoffset);
1150 COPYSLOT(tp_init);
1151 COPYSLOT(tp_alloc);
1152 COPYSLOT(tp_new);
1153 COPYSLOT(tp_free);
1154 }
1155
1156 return 0;
1157}
1158
1159int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001160PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161{
1162 PyObject *dict, *bases, *x;
1163 PyTypeObject *base;
1164 int i, n;
1165
1166 if (type->tp_dict != NULL)
1167 return 0; /* Already initialized */
1168
1169 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1170 base = type->tp_base;
1171 if (base == NULL && type != &PyBaseObject_Type)
1172 base = type->tp_base = &PyBaseObject_Type;
1173
1174 /* Initialize tp_bases */
1175 bases = type->tp_bases;
1176 if (bases == NULL) {
1177 if (base == NULL)
1178 bases = PyTuple_New(0);
1179 else
1180 bases = Py_BuildValue("(O)", base);
1181 if (bases == NULL)
1182 return -1;
1183 type->tp_bases = bases;
1184 }
1185
1186 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001187 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001188 if (PyType_Ready(base) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 return -1;
1190 }
1191
1192 /* Initialize tp_defined */
1193 dict = type->tp_defined;
1194 if (dict == NULL) {
1195 dict = PyDict_New();
1196 if (dict == NULL)
1197 return -1;
1198 type->tp_defined = dict;
1199 }
1200
1201 /* Add type-specific descriptors to tp_defined */
1202 if (add_operators(type) < 0)
1203 return -1;
1204 if (type->tp_methods != NULL) {
1205 if (add_methods(type, type->tp_methods) < 0)
1206 return -1;
1207 }
1208 if (type->tp_members != NULL) {
1209 if (add_members(type, type->tp_members) < 0)
1210 return -1;
1211 }
1212 if (type->tp_getset != NULL) {
1213 if (add_getset(type, type->tp_getset) < 0)
1214 return -1;
1215 }
1216
1217 /* Temporarily make tp_dict the same object as tp_defined.
1218 (This is needed to call mro(), and can stay this way for
1219 dynamic types). */
1220 Py_INCREF(type->tp_defined);
1221 type->tp_dict = type->tp_defined;
1222
1223 /* Calculate method resolution order */
1224 if (mro_internal(type) < 0) {
1225 return -1;
1226 }
1227
1228 /* Initialize tp_dict properly */
1229 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
1230 /* For a static type, tp_dict is the consolidation
1231 of the tp_defined of its bases in MRO. Earlier
1232 bases override later bases; since d.update() works
1233 the other way, we walk the MRO sequence backwards. */
1234 Py_DECREF(type->tp_dict);
1235 type->tp_dict = PyDict_New();
1236 if (type->tp_dict == NULL)
1237 return -1;
1238 bases = type->tp_mro;
1239 assert(bases != NULL);
1240 assert(PyTuple_Check(bases));
1241 n = PyTuple_GET_SIZE(bases);
1242 for (i = n; --i >= 0; ) {
1243 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1244 assert(PyType_Check(base));
1245 x = base->tp_defined;
1246 if (x != NULL && PyDict_Update(type->tp_dict, x) < 0)
1247 return -1;
1248 }
1249 }
1250
1251 /* Inherit slots from direct base */
1252 if (type->tp_base != NULL)
1253 if (inherit_slots(type, type->tp_base) < 0)
1254 return -1;
1255
1256 return 0;
1257}
1258
1259
1260/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1261
1262/* There's a wrapper *function* for each distinct function typedef used
1263 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1264 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1265 Most tables have only one entry; the tables for binary operators have two
1266 entries, one regular and one with reversed arguments. */
1267
1268static PyObject *
1269wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1270{
1271 inquiry func = (inquiry)wrapped;
1272 int res;
1273
1274 if (!PyArg_ParseTuple(args, ""))
1275 return NULL;
1276 res = (*func)(self);
1277 if (res == -1 && PyErr_Occurred())
1278 return NULL;
1279 return PyInt_FromLong((long)res);
1280}
1281
1282static struct wrapperbase tab_len[] = {
1283 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1284 {0}
1285};
1286
1287static PyObject *
1288wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1289{
1290 binaryfunc func = (binaryfunc)wrapped;
1291 PyObject *other;
1292
1293 if (!PyArg_ParseTuple(args, "O", &other))
1294 return NULL;
1295 return (*func)(self, other);
1296}
1297
1298static PyObject *
1299wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1300{
1301 binaryfunc func = (binaryfunc)wrapped;
1302 PyObject *other;
1303
1304 if (!PyArg_ParseTuple(args, "O", &other))
1305 return NULL;
1306 return (*func)(other, self);
1307}
1308
1309#undef BINARY
1310#define BINARY(NAME, OP) \
1311static struct wrapperbase tab_##NAME[] = { \
1312 {"__" #NAME "__", \
1313 (wrapperfunc)wrap_binaryfunc, \
1314 "x.__" #NAME "__(y) <==> " #OP}, \
1315 {"__r" #NAME "__", \
1316 (wrapperfunc)wrap_binaryfunc_r, \
1317 "y.__r" #NAME "__(x) <==> " #OP}, \
1318 {0} \
1319}
1320
1321BINARY(add, "x+y");
1322BINARY(sub, "x-y");
1323BINARY(mul, "x*y");
1324BINARY(div, "x/y");
1325BINARY(mod, "x%y");
1326BINARY(divmod, "divmod(x,y)");
1327BINARY(lshift, "x<<y");
1328BINARY(rshift, "x>>y");
1329BINARY(and, "x&y");
1330BINARY(xor, "x^y");
1331BINARY(or, "x|y");
1332
1333static PyObject *
1334wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1335{
1336 ternaryfunc func = (ternaryfunc)wrapped;
1337 PyObject *other;
1338 PyObject *third = Py_None;
1339
1340 /* Note: This wrapper only works for __pow__() */
1341
1342 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1343 return NULL;
1344 return (*func)(self, other, third);
1345}
1346
1347#undef TERNARY
1348#define TERNARY(NAME, OP) \
1349static struct wrapperbase tab_##NAME[] = { \
1350 {"__" #NAME "__", \
1351 (wrapperfunc)wrap_ternaryfunc, \
1352 "x.__" #NAME "__(y, z) <==> " #OP}, \
1353 {"__r" #NAME "__", \
1354 (wrapperfunc)wrap_ternaryfunc, \
1355 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1356 {0} \
1357}
1358
1359TERNARY(pow, "(x**y) % z");
1360
1361#undef UNARY
1362#define UNARY(NAME, OP) \
1363static struct wrapperbase tab_##NAME[] = { \
1364 {"__" #NAME "__", \
1365 (wrapperfunc)wrap_unaryfunc, \
1366 "x.__" #NAME "__() <==> " #OP}, \
1367 {0} \
1368}
1369
1370static PyObject *
1371wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1372{
1373 unaryfunc func = (unaryfunc)wrapped;
1374
1375 if (!PyArg_ParseTuple(args, ""))
1376 return NULL;
1377 return (*func)(self);
1378}
1379
1380UNARY(neg, "-x");
1381UNARY(pos, "+x");
1382UNARY(abs, "abs(x)");
1383UNARY(nonzero, "x != 0");
1384UNARY(invert, "~x");
1385UNARY(int, "int(x)");
1386UNARY(long, "long(x)");
1387UNARY(float, "float(x)");
1388UNARY(oct, "oct(x)");
1389UNARY(hex, "hex(x)");
1390
1391#undef IBINARY
1392#define IBINARY(NAME, OP) \
1393static struct wrapperbase tab_##NAME[] = { \
1394 {"__" #NAME "__", \
1395 (wrapperfunc)wrap_binaryfunc, \
1396 "x.__" #NAME "__(y) <==> " #OP}, \
1397 {0} \
1398}
1399
1400IBINARY(iadd, "x+=y");
1401IBINARY(isub, "x-=y");
1402IBINARY(imul, "x*=y");
1403IBINARY(idiv, "x/=y");
1404IBINARY(imod, "x%=y");
1405IBINARY(ilshift, "x<<=y");
1406IBINARY(irshift, "x>>=y");
1407IBINARY(iand, "x&=y");
1408IBINARY(ixor, "x^=y");
1409IBINARY(ior, "x|=y");
1410
1411#undef ITERNARY
1412#define ITERNARY(NAME, OP) \
1413static struct wrapperbase tab_##NAME[] = { \
1414 {"__" #NAME "__", \
1415 (wrapperfunc)wrap_ternaryfunc, \
1416 "x.__" #NAME "__(y) <==> " #OP}, \
1417 {0} \
1418}
1419
1420ITERNARY(ipow, "x = (x**y) % z");
1421
1422static struct wrapperbase tab_getitem[] = {
1423 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1424 "x.__getitem__(y) <==> x[y]"},
1425 {0}
1426};
1427
1428static PyObject *
1429wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1430{
1431 intargfunc func = (intargfunc)wrapped;
1432 int i;
1433
1434 if (!PyArg_ParseTuple(args, "i", &i))
1435 return NULL;
1436 return (*func)(self, i);
1437}
1438
1439static struct wrapperbase tab_mul_int[] = {
1440 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1441 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1442 {0}
1443};
1444
1445static struct wrapperbase tab_concat[] = {
1446 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1447 {0}
1448};
1449
1450static struct wrapperbase tab_imul_int[] = {
1451 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1452 {0}
1453};
1454
1455static struct wrapperbase tab_getitem_int[] = {
1456 {"__getitem__", (wrapperfunc)wrap_intargfunc,
1457 "x.__getitem__(i) <==> x[i]"},
1458 {0}
1459};
1460
1461static PyObject *
1462wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1463{
1464 intintargfunc func = (intintargfunc)wrapped;
1465 int i, j;
1466
1467 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1468 return NULL;
1469 return (*func)(self, i, j);
1470}
1471
1472static struct wrapperbase tab_getslice[] = {
1473 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1474 "x.__getslice__(i, j) <==> x[i:j]"},
1475 {0}
1476};
1477
1478static PyObject *
1479wrap_intobjargproc(PyObject *self, PyObject *args, void *wrapped)
1480{
1481 intobjargproc func = (intobjargproc)wrapped;
1482 int i, res;
1483 PyObject *value;
1484
1485 if (!PyArg_ParseTuple(args, "iO", &i, &value))
1486 return NULL;
1487 res = (*func)(self, i, value);
1488 if (res == -1 && PyErr_Occurred())
1489 return NULL;
1490 Py_INCREF(Py_None);
1491 return Py_None;
1492}
1493
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001494static PyObject *
1495wrap_delitem_int(PyObject *self, PyObject *args, void *wrapped)
1496{
1497 intobjargproc func = (intobjargproc)wrapped;
1498 int i, res;
1499
1500 if (!PyArg_ParseTuple(args, "i", &i))
1501 return NULL;
1502 res = (*func)(self, i, NULL);
1503 if (res == -1 && PyErr_Occurred())
1504 return NULL;
1505 Py_INCREF(Py_None);
1506 return Py_None;
1507}
1508
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509static struct wrapperbase tab_setitem_int[] = {
1510 {"__setitem__", (wrapperfunc)wrap_intobjargproc,
1511 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001512 {"__delitem__", (wrapperfunc)wrap_delitem_int,
1513 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514 {0}
1515};
1516
1517static PyObject *
1518wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1519{
1520 intintobjargproc func = (intintobjargproc)wrapped;
1521 int i, j, res;
1522 PyObject *value;
1523
1524 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1525 return NULL;
1526 res = (*func)(self, i, j, value);
1527 if (res == -1 && PyErr_Occurred())
1528 return NULL;
1529 Py_INCREF(Py_None);
1530 return Py_None;
1531}
1532
1533static struct wrapperbase tab_setslice[] = {
1534 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1535 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1536 {0}
1537};
1538
1539/* XXX objobjproc is a misnomer; should be objargpred */
1540static PyObject *
1541wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1542{
1543 objobjproc func = (objobjproc)wrapped;
1544 int res;
1545 PyObject *value;
1546
1547 if (!PyArg_ParseTuple(args, "O", &value))
1548 return NULL;
1549 res = (*func)(self, value);
1550 if (res == -1 && PyErr_Occurred())
1551 return NULL;
1552 return PyInt_FromLong((long)res);
1553}
1554
1555static struct wrapperbase tab_contains[] = {
1556 {"__contains__", (wrapperfunc)wrap_objobjproc,
1557 "x.__contains__(y) <==> y in x"},
1558 {0}
1559};
1560
1561static PyObject *
1562wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1563{
1564 objobjargproc func = (objobjargproc)wrapped;
1565 int res;
1566 PyObject *key, *value;
1567
1568 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1569 return NULL;
1570 res = (*func)(self, key, value);
1571 if (res == -1 && PyErr_Occurred())
1572 return NULL;
1573 Py_INCREF(Py_None);
1574 return Py_None;
1575}
1576
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001577static PyObject *
1578wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1579{
1580 objobjargproc func = (objobjargproc)wrapped;
1581 int res;
1582 PyObject *key;
1583
1584 if (!PyArg_ParseTuple(args, "O", &key))
1585 return NULL;
1586 res = (*func)(self, key, NULL);
1587 if (res == -1 && PyErr_Occurred())
1588 return NULL;
1589 Py_INCREF(Py_None);
1590 return Py_None;
1591}
1592
Tim Peters6d6c1a32001-08-02 04:15:00 +00001593static struct wrapperbase tab_setitem[] = {
1594 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1595 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001596 {"__delitem__", (wrapperfunc)wrap_delitem,
1597 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598 {0}
1599};
1600
1601static PyObject *
1602wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1603{
1604 cmpfunc func = (cmpfunc)wrapped;
1605 int res;
1606 PyObject *other;
1607
1608 if (!PyArg_ParseTuple(args, "O", &other))
1609 return NULL;
1610 res = (*func)(self, other);
1611 if (PyErr_Occurred())
1612 return NULL;
1613 return PyInt_FromLong((long)res);
1614}
1615
1616static struct wrapperbase tab_cmp[] = {
1617 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1618 "x.__cmp__(y) <==> cmp(x,y)"},
1619 {0}
1620};
1621
1622static struct wrapperbase tab_repr[] = {
1623 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1624 "x.__repr__() <==> repr(x)"},
1625 {0}
1626};
1627
1628static struct wrapperbase tab_getattr[] = {
1629 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1630 "x.__getattr__('name') <==> x.name"},
1631 {0}
1632};
1633
1634static PyObject *
1635wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1636{
1637 setattrofunc func = (setattrofunc)wrapped;
1638 int res;
1639 PyObject *name, *value;
1640
1641 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1642 return NULL;
1643 res = (*func)(self, name, value);
1644 if (res < 0)
1645 return NULL;
1646 Py_INCREF(Py_None);
1647 return Py_None;
1648}
1649
1650static PyObject *
1651wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1652{
1653 setattrofunc func = (setattrofunc)wrapped;
1654 int res;
1655 PyObject *name;
1656
1657 if (!PyArg_ParseTuple(args, "O", &name))
1658 return NULL;
1659 res = (*func)(self, name, NULL);
1660 if (res < 0)
1661 return NULL;
1662 Py_INCREF(Py_None);
1663 return Py_None;
1664}
1665
1666static struct wrapperbase tab_setattr[] = {
1667 {"__setattr__", (wrapperfunc)wrap_setattr,
1668 "x.__setattr__('name', value) <==> x.name = value"},
1669 {"__delattr__", (wrapperfunc)wrap_delattr,
1670 "x.__delattr__('name') <==> del x.name"},
1671 {0}
1672};
1673
1674static PyObject *
1675wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1676{
1677 hashfunc func = (hashfunc)wrapped;
1678 long res;
1679
1680 if (!PyArg_ParseTuple(args, ""))
1681 return NULL;
1682 res = (*func)(self);
1683 if (res == -1 && PyErr_Occurred())
1684 return NULL;
1685 return PyInt_FromLong(res);
1686}
1687
1688static struct wrapperbase tab_hash[] = {
1689 {"__hash__", (wrapperfunc)wrap_hashfunc,
1690 "x.__hash__() <==> hash(x)"},
1691 {0}
1692};
1693
1694static PyObject *
1695wrap_call(PyObject *self, PyObject *args, void *wrapped)
1696{
1697 ternaryfunc func = (ternaryfunc)wrapped;
1698
1699 /* XXX What about keyword arguments? */
1700 return (*func)(self, args, NULL);
1701}
1702
1703static struct wrapperbase tab_call[] = {
1704 {"__call__", (wrapperfunc)wrap_call,
1705 "x.__call__(...) <==> x(...)"},
1706 {0}
1707};
1708
1709static struct wrapperbase tab_str[] = {
1710 {"__str__", (wrapperfunc)wrap_unaryfunc,
1711 "x.__str__() <==> str(x)"},
1712 {0}
1713};
1714
1715static PyObject *
1716wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1717{
1718 richcmpfunc func = (richcmpfunc)wrapped;
1719 PyObject *other;
1720
1721 if (!PyArg_ParseTuple(args, "O", &other))
1722 return NULL;
1723 return (*func)(self, other, op);
1724}
1725
1726#undef RICHCMP_WRAPPER
1727#define RICHCMP_WRAPPER(NAME, OP) \
1728static PyObject * \
1729richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1730{ \
1731 return wrap_richcmpfunc(self, args, wrapped, OP); \
1732}
1733
1734RICHCMP_WRAPPER(lt, Py_LT);
1735RICHCMP_WRAPPER(le, Py_LE);
1736RICHCMP_WRAPPER(eq, Py_EQ);
1737RICHCMP_WRAPPER(ne, Py_NE);
1738RICHCMP_WRAPPER(gt, Py_GT);
1739RICHCMP_WRAPPER(ge, Py_GE);
1740
1741#undef RICHCMP_ENTRY
1742#define RICHCMP_ENTRY(NAME, EXPR) \
1743 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1744 "x.__" #NAME "__(y) <==> " EXPR}
1745
1746static struct wrapperbase tab_richcmp[] = {
1747 RICHCMP_ENTRY(lt, "x<y"),
1748 RICHCMP_ENTRY(le, "x<=y"),
1749 RICHCMP_ENTRY(eq, "x==y"),
1750 RICHCMP_ENTRY(ne, "x!=y"),
1751 RICHCMP_ENTRY(gt, "x>y"),
1752 RICHCMP_ENTRY(ge, "x>=y"),
1753 {0}
1754};
1755
1756static struct wrapperbase tab_iter[] = {
1757 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
1758 {0}
1759};
1760
1761static PyObject *
1762wrap_next(PyObject *self, PyObject *args, void *wrapped)
1763{
1764 unaryfunc func = (unaryfunc)wrapped;
1765 PyObject *res;
1766
1767 if (!PyArg_ParseTuple(args, ""))
1768 return NULL;
1769 res = (*func)(self);
1770 if (res == NULL && !PyErr_Occurred())
1771 PyErr_SetNone(PyExc_StopIteration);
1772 return res;
1773}
1774
1775static struct wrapperbase tab_next[] = {
1776 {"next", (wrapperfunc)wrap_next,
1777 "x.next() -> the next value, or raise StopIteration"},
1778 {0}
1779};
1780
1781static PyObject *
1782wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
1783{
1784 descrgetfunc func = (descrgetfunc)wrapped;
1785 PyObject *obj;
1786 PyObject *type = NULL;
1787
1788 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
1789 return NULL;
1790 if (type == NULL)
1791 type = (PyObject *)obj->ob_type;
1792 return (*func)(self, obj, type);
1793}
1794
1795static struct wrapperbase tab_descr_get[] = {
1796 {"__get__", (wrapperfunc)wrap_descr_get,
1797 "descr.__get__(obj, type) -> value"},
1798 {0}
1799};
1800
1801static PyObject *
1802wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
1803{
1804 descrsetfunc func = (descrsetfunc)wrapped;
1805 PyObject *obj, *value;
1806 int ret;
1807
1808 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
1809 return NULL;
1810 ret = (*func)(self, obj, value);
1811 if (ret < 0)
1812 return NULL;
1813 Py_INCREF(Py_None);
1814 return Py_None;
1815}
1816
1817static struct wrapperbase tab_descr_set[] = {
1818 {"__set__", (wrapperfunc)wrap_descrsetfunc,
1819 "descr.__set__(obj, value)"},
1820 {0}
1821};
1822
1823static PyObject *
1824wrap_init(PyObject *self, PyObject *args, void *wrapped)
1825{
1826 initproc func = (initproc)wrapped;
1827
1828 /* XXX What about keyword arguments? */
1829 if (func(self, args, NULL) < 0)
1830 return NULL;
1831 Py_INCREF(Py_None);
1832 return Py_None;
1833}
1834
1835static struct wrapperbase tab_init[] = {
1836 {"__init__", (wrapperfunc)wrap_init,
1837 "x.__init__(...) initializes x; "
1838 "see x.__type__.__doc__ for signature"},
1839 {0}
1840};
1841
1842static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001843tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844{
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001845 PyTypeObject *type, *subtype;
1846 PyObject *arg0, *res;
1847
1848 if (self == NULL || !PyType_Check(self))
1849 Py_FatalError("__new__() called with non-type 'self'");
1850 type = (PyTypeObject *)self;
1851 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
1852 PyErr_SetString(PyExc_TypeError,
1853 "T.__new__(): not enough arguments");
1854 return NULL;
1855 }
1856 arg0 = PyTuple_GET_ITEM(args, 0);
1857 if (!PyType_Check(arg0)) {
1858 PyErr_SetString(PyExc_TypeError,
1859 "T.__new__(S): S is not a type object");
1860 return NULL;
1861 }
1862 subtype = (PyTypeObject *)arg0;
1863 if (!PyType_IsSubtype(subtype, type)) {
1864 PyErr_SetString(PyExc_TypeError,
1865 "T.__new__(S): S is not a subtype of T");
1866 return NULL;
1867 }
1868 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
1869 if (args == NULL)
1870 return NULL;
1871 res = type->tp_new(subtype, args, kwds);
1872 Py_DECREF(args);
1873 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874}
1875
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001876static struct PyMethodDef tp_new_methoddef[] = {
1877 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
1878 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 {0}
1880};
1881
1882static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001883add_tp_new_wrapper(PyTypeObject *type)
1884{
Guido van Rossumf040ede2001-08-07 16:40:56 +00001885 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001886
Guido van Rossumf040ede2001-08-07 16:40:56 +00001887 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
1888 return 0;
1889 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001890 if (func == NULL)
1891 return -1;
1892 return PyDict_SetItemString(type->tp_defined, "__new__", func);
1893}
1894
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001895/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00001896 dictionary with method descriptors for function slots. For each
1897 function slot (like tp_repr) that's defined in the type, one or
1898 more corresponding descriptors are added in the type's tp_defined
1899 dictionary under the appropriate name (like __repr__). Some
1900 function slots cause more than one descriptor to be added (for
1901 example, the nb_add slot adds both __add__ and __radd__
1902 descriptors) and some function slots compete for the same
1903 descriptor (for example both sq_item and mp_subscript generate a
1904 __getitem__ descriptor). This only adds new descriptors and
1905 doesn't overwrite entries in tp_defined that were previously
1906 defined. The descriptors contain a reference to the C function
1907 they must call, so that it's safe if they are copied into a
1908 subtype's __dict__ and the subtype has a different C function in
1909 its slot -- calling the method defined by the descriptor will call
1910 the C function that was used to create it, rather than the C
1911 function present in the slot when it is called. (This is important
1912 because a subtype may have a C function in the slot that calls the
1913 method from the dictionary, and we want to avoid infinite recursion
1914 here.) */
1915
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001916static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917add_operators(PyTypeObject *type)
1918{
1919 PySequenceMethods *sq;
1920 PyMappingMethods *mp;
1921 PyNumberMethods *nb;
1922
1923#undef ADD
1924#define ADD(SLOT, TABLE) \
1925 if (SLOT) { \
1926 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
1927 return -1; \
1928 }
1929
1930 if ((sq = type->tp_as_sequence) != NULL) {
1931 ADD(sq->sq_length, tab_len);
1932 ADD(sq->sq_concat, tab_concat);
1933 ADD(sq->sq_repeat, tab_mul_int);
1934 ADD(sq->sq_item, tab_getitem_int);
1935 ADD(sq->sq_slice, tab_getslice);
1936 ADD(sq->sq_ass_item, tab_setitem_int);
1937 ADD(sq->sq_ass_slice, tab_setslice);
1938 ADD(sq->sq_contains, tab_contains);
1939 ADD(sq->sq_inplace_concat, tab_iadd);
1940 ADD(sq->sq_inplace_repeat, tab_imul_int);
1941 }
1942
1943 if ((mp = type->tp_as_mapping) != NULL) {
1944 if (sq->sq_length == NULL)
1945 ADD(mp->mp_length, tab_len);
1946 ADD(mp->mp_subscript, tab_getitem);
1947 ADD(mp->mp_ass_subscript, tab_setitem);
1948 }
1949
1950 /* We don't support "old-style numbers" because their binary
1951 operators require that both arguments have the same type;
1952 the wrappers here only work for new-style numbers. */
1953 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
1954 (nb = type->tp_as_number) != NULL) {
1955 ADD(nb->nb_add, tab_add);
1956 ADD(nb->nb_subtract, tab_sub);
1957 ADD(nb->nb_multiply, tab_mul);
1958 ADD(nb->nb_divide, tab_div);
1959 ADD(nb->nb_remainder, tab_mod);
1960 ADD(nb->nb_divmod, tab_divmod);
1961 ADD(nb->nb_power, tab_pow);
1962 ADD(nb->nb_negative, tab_neg);
1963 ADD(nb->nb_positive, tab_pos);
1964 ADD(nb->nb_absolute, tab_abs);
1965 ADD(nb->nb_nonzero, tab_nonzero);
1966 ADD(nb->nb_invert, tab_invert);
1967 ADD(nb->nb_lshift, tab_lshift);
1968 ADD(nb->nb_rshift, tab_rshift);
1969 ADD(nb->nb_and, tab_and);
1970 ADD(nb->nb_xor, tab_xor);
1971 ADD(nb->nb_or, tab_or);
1972 /* We don't support coerce() -- see above comment */
1973 ADD(nb->nb_int, tab_int);
1974 ADD(nb->nb_long, tab_long);
1975 ADD(nb->nb_float, tab_float);
1976 ADD(nb->nb_oct, tab_oct);
1977 ADD(nb->nb_hex, tab_hex);
1978 ADD(nb->nb_inplace_add, tab_iadd);
1979 ADD(nb->nb_inplace_subtract, tab_isub);
1980 ADD(nb->nb_inplace_multiply, tab_imul);
1981 ADD(nb->nb_inplace_divide, tab_idiv);
1982 ADD(nb->nb_inplace_remainder, tab_imod);
1983 ADD(nb->nb_inplace_power, tab_ipow);
1984 ADD(nb->nb_inplace_lshift, tab_ilshift);
1985 ADD(nb->nb_inplace_rshift, tab_irshift);
1986 ADD(nb->nb_inplace_and, tab_iand);
1987 ADD(nb->nb_inplace_xor, tab_ixor);
1988 ADD(nb->nb_inplace_or, tab_ior);
1989 }
1990
1991 ADD(type->tp_getattro, tab_getattr);
1992 ADD(type->tp_setattro, tab_setattr);
1993 ADD(type->tp_compare, tab_cmp);
1994 ADD(type->tp_repr, tab_repr);
1995 ADD(type->tp_hash, tab_hash);
1996 ADD(type->tp_call, tab_call);
1997 ADD(type->tp_str, tab_str);
1998 ADD(type->tp_richcompare, tab_richcmp);
1999 ADD(type->tp_iter, tab_iter);
2000 ADD(type->tp_iternext, tab_next);
2001 ADD(type->tp_descr_get, tab_descr_get);
2002 ADD(type->tp_descr_set, tab_descr_set);
2003 ADD(type->tp_init, tab_init);
2004
Guido van Rossumf040ede2001-08-07 16:40:56 +00002005 if (type->tp_new != NULL) {
2006 if (add_tp_new_wrapper(type) < 0)
2007 return -1;
2008 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009
2010 return 0;
2011}
2012
Guido van Rossumf040ede2001-08-07 16:40:56 +00002013/* Slot wrappers that call the corresponding __foo__ slot. See comments
2014 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015
2016#define SLOT0(SLOTNAME, OPNAME) \
2017static PyObject * \
2018slot_##SLOTNAME(PyObject *self) \
2019{ \
2020 return PyObject_CallMethod(self, "__" #OPNAME "__", ""); \
2021}
2022
2023#define SLOT1(SLOTNAME, OPNAME, ARG1TYPE, ARGCODES) \
2024static PyObject * \
2025slot_##SLOTNAME(PyObject *self, ARG1TYPE arg1) \
2026{ \
2027 return PyObject_CallMethod(self, "__" #OPNAME "__", #ARGCODES, arg1); \
2028}
2029
2030#define SLOT2(SLOTNAME, OPNAME, ARG1TYPE, ARG2TYPE, ARGCODES) \
2031static PyObject * \
2032slot_##SLOTNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2033{ \
2034 return PyObject_CallMethod(self, "__" #OPNAME "__", \
2035 #ARGCODES, arg1, arg2); \
2036}
2037
2038static int
2039slot_sq_length(PyObject *self)
2040{
2041 PyObject *res = PyObject_CallMethod(self, "__len__", "");
2042
2043 if (res == NULL)
2044 return -1;
2045 return (int)PyInt_AsLong(res);
2046}
2047
2048SLOT1(sq_concat, add, PyObject *, O);
2049SLOT1(sq_repeat, mul, int, i);
2050SLOT1(sq_item, getitem, int, i);
2051SLOT2(sq_slice, getslice, int, int, ii);
2052
2053static int
2054slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2055{
2056 PyObject *res;
2057
2058 if (value == NULL)
2059 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2060 else
2061 res = PyObject_CallMethod(self, "__setitem__",
2062 "iO", index, value);
2063 if (res == NULL)
2064 return -1;
2065 Py_DECREF(res);
2066 return 0;
2067}
2068
2069static int
2070slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2071{
2072 PyObject *res;
2073
2074 if (value == NULL)
2075 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2076 else
2077 res = PyObject_CallMethod(self, "__setslice__",
2078 "iiO", i, j, value);
2079 if (res == NULL)
2080 return -1;
2081 Py_DECREF(res);
2082 return 0;
2083}
2084
2085static int
2086slot_sq_contains(PyObject *self, PyObject *value)
2087{
2088 PyObject *res = PyObject_CallMethod(self, "__contains__", "O", value);
2089 int r;
2090
2091 if (res == NULL)
2092 return -1;
2093 r = PyInt_AsLong(res);
2094 Py_DECREF(res);
2095 return r;
2096}
2097
2098SLOT1(sq_inplace_concat, iadd, PyObject *, O);
2099SLOT1(sq_inplace_repeat, imul, int, i);
2100
2101#define slot_mp_length slot_sq_length
2102
2103SLOT1(mp_subscript, getitem, PyObject *, O);
2104
2105static int
2106slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2107{
2108 PyObject *res;
2109
2110 if (value == NULL)
2111 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2112 else
2113 res = PyObject_CallMethod(self, "__setitem__",
2114 "OO", key, value);
2115 if (res == NULL)
2116 return -1;
2117 Py_DECREF(res);
2118 return 0;
2119}
2120
2121/* XXX the numerical slots should call the reverse operators too;
2122 but how do they know their type? */
2123SLOT1(nb_add, add, PyObject *, O);
2124SLOT1(nb_subtract, sub, PyObject *, O);
2125SLOT1(nb_multiply, mul, PyObject *, O);
2126SLOT1(nb_divide, div, PyObject *, O);
2127SLOT1(nb_remainder, mod, PyObject *, O);
2128SLOT1(nb_divmod, divmod, PyObject *, O);
2129SLOT2(nb_power, pow, PyObject *, PyObject *, OO);
2130SLOT0(nb_negative, neg);
2131SLOT0(nb_positive, pos);
2132SLOT0(nb_absolute, abs);
2133
2134static int
2135slot_nb_nonzero(PyObject *self)
2136{
2137 PyObject *res = PyObject_CallMethod(self, "__nonzero__", "");
2138
2139 if (res == NULL)
2140 return -1;
2141 return (int)PyInt_AsLong(res);
2142}
2143
2144SLOT0(nb_invert, invert);
2145SLOT1(nb_lshift, lshift, PyObject *, O);
2146SLOT1(nb_rshift, rshift, PyObject *, O);
2147SLOT1(nb_and, and, PyObject *, O);
2148SLOT1(nb_xor, xor, PyObject *, O);
2149SLOT1(nb_or, or, PyObject *, O);
2150/* Not coerce() */
2151SLOT0(nb_int, int);
2152SLOT0(nb_long, long);
2153SLOT0(nb_float, float);
2154SLOT0(nb_oct, oct);
2155SLOT0(nb_hex, hex);
2156SLOT1(nb_inplace_add, iadd, PyObject *, O);
2157SLOT1(nb_inplace_subtract, isub, PyObject *, O);
2158SLOT1(nb_inplace_multiply, imul, PyObject *, O);
2159SLOT1(nb_inplace_divide, idiv, PyObject *, O);
2160SLOT1(nb_inplace_remainder, imod, PyObject *, O);
2161SLOT2(nb_inplace_power, ipow, PyObject *, PyObject *, OO);
2162SLOT1(nb_inplace_lshift, ilshift, PyObject *, O);
2163SLOT1(nb_inplace_rshift, irshift, PyObject *, O);
2164SLOT1(nb_inplace_and, iand, PyObject *, O);
2165SLOT1(nb_inplace_xor, ixor, PyObject *, O);
2166SLOT1(nb_inplace_or, ior, PyObject *, O);
2167
2168static int
2169slot_tp_compare(PyObject *self, PyObject *other)
2170{
2171 PyObject *res = PyObject_CallMethod(self, "__cmp__", "O", other);
2172 long r;
2173
2174 if (res == NULL)
2175 return -1;
2176 r = PyInt_AsLong(res);
2177 Py_DECREF(res);
2178 return (int)r;
2179}
2180
2181SLOT0(tp_repr, repr);
2182
2183static long
2184slot_tp_hash(PyObject *self)
2185{
2186 PyObject *res = PyObject_CallMethod(self, "__hash__", "");
2187 long h;
2188
2189 if (res == NULL)
2190 return -1;
2191 h = PyInt_AsLong(res);
2192 if (h == -1 && !PyErr_Occurred())
2193 h = -2;
2194 return h;
2195}
2196
2197static PyObject *
2198slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2199{
2200 PyObject *meth = PyObject_GetAttrString(self, "__call__");
2201 PyObject *res;
2202
2203 if (meth == NULL)
2204 return NULL;
2205 res = PyObject_Call(meth, args, kwds);
2206 Py_DECREF(meth);
2207 return res;
2208}
2209
2210SLOT0(tp_str, str);
2211
2212static PyObject *
2213slot_tp_getattro(PyObject *self, PyObject *name)
2214{
2215 PyTypeObject *tp = self->ob_type;
2216 PyObject *dict = NULL;
2217 PyObject *getattr;
2218
2219 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE)
2220 dict = tp->tp_dict;
2221 if (dict == NULL) {
2222 PyErr_Format(PyExc_SystemError,
2223 "'%.100s' type object has no __dict__???",
2224 tp->tp_name);
2225 return NULL;
2226 }
2227 getattr = PyDict_GetItemString(dict, "__getattr__");
2228 if (getattr == NULL) {
2229 PyErr_SetString(PyExc_AttributeError, "__getattr__");
2230 return NULL;
2231 }
2232 return PyObject_CallFunction(getattr, "OO", self, name);
2233}
2234
2235static int
2236slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2237{
2238 PyObject *res;
2239
2240 if (value == NULL)
2241 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2242 else
2243 res = PyObject_CallMethod(self, "__setattr__",
2244 "OO", name, value);
2245 if (res == NULL)
2246 return -1;
2247 Py_DECREF(res);
2248 return 0;
2249}
2250
2251/* Map rich comparison operators to their __xx__ namesakes */
2252static char *name_op[] = {
2253 "__lt__",
2254 "__le__",
2255 "__eq__",
2256 "__ne__",
2257 "__gt__",
2258 "__ge__",
2259};
2260
2261static PyObject *
2262slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2263{
2264 PyObject *meth = PyObject_GetAttrString(self, name_op[op]);
2265 PyObject *res;
2266
2267 if (meth == NULL)
2268 return NULL;
2269 res = PyObject_CallFunction(meth, "O", other);
2270 Py_DECREF(meth);
2271 return res;
2272}
2273
2274SLOT0(tp_iter, iter);
2275
2276static PyObject *
2277slot_tp_iternext(PyObject *self)
2278{
2279 return PyObject_CallMethod(self, "next", "");
2280}
2281
2282SLOT2(tp_descr_get, get, PyObject *, PyObject *, OO);
2283
2284static int
2285slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2286{
2287 PyObject *res = PyObject_CallMethod(self, "__set__",
2288 "OO", target, value);
2289 if (res == NULL)
2290 return -1;
2291 Py_DECREF(res);
2292 return 0;
2293}
2294
2295static int
2296slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2297{
2298 PyObject *meth = PyObject_GetAttrString(self, "__init__");
2299 PyObject *res;
2300
2301 if (meth == NULL)
2302 return -1;
2303 res = PyObject_Call(meth, args, kwds);
2304 Py_DECREF(meth);
2305 if (res == NULL)
2306 return -1;
2307 Py_DECREF(res);
2308 return 0;
2309}
2310
2311static PyObject *
2312slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2313{
2314 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2315 PyObject *newargs, *x;
2316 int i, n;
2317
2318 if (func == NULL)
2319 return NULL;
2320 assert(PyTuple_Check(args));
2321 n = PyTuple_GET_SIZE(args);
2322 newargs = PyTuple_New(n+1);
2323 if (newargs == NULL)
2324 return NULL;
2325 Py_INCREF(type);
2326 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2327 for (i = 0; i < n; i++) {
2328 x = PyTuple_GET_ITEM(args, i);
2329 Py_INCREF(x);
2330 PyTuple_SET_ITEM(newargs, i+1, x);
2331 }
2332 x = PyObject_Call(func, newargs, kwds);
2333 Py_DECREF(func);
2334 return x;
2335}
2336
Guido van Rossumf040ede2001-08-07 16:40:56 +00002337/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002338 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002339 The dict argument is the dictionary argument passed to type_new(),
2340 which is the local namespace of the class statement, in other
2341 words, it contains the methods. For each special method (like
2342 __repr__) defined in the dictionary, the corresponding function
2343 slot in the type object (like tp_repr) is set to a special function
2344 whose name is 'slot_' followed by the slot name and whose signature
2345 is whatever is required for that slot. These slot functions look
2346 up the corresponding method in the type's dictionary and call it.
2347 The slot functions have to take care of the various peculiarities
2348 of the mapping between slots and special methods, such as mapping
2349 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2350 etc.) or mapping multiple slots to a single method (sq_item,
2351 mp_subscript <--> __getitem__). */
2352
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353static void
2354override_slots(PyTypeObject *type, PyObject *dict)
2355{
2356 PySequenceMethods *sq = type->tp_as_sequence;
2357 PyMappingMethods *mp = type->tp_as_mapping;
2358 PyNumberMethods *nb = type->tp_as_number;
2359
2360#define SQSLOT(OPNAME, SLOTNAME) \
2361 if (PyDict_GetItemString(dict, OPNAME)) { \
2362 sq->SLOTNAME = slot_##SLOTNAME; \
2363 }
2364
2365#define MPSLOT(OPNAME, SLOTNAME) \
2366 if (PyDict_GetItemString(dict, OPNAME)) { \
2367 mp->SLOTNAME = slot_##SLOTNAME; \
2368 }
2369
2370#define NBSLOT(OPNAME, SLOTNAME) \
2371 if (PyDict_GetItemString(dict, OPNAME)) { \
2372 nb->SLOTNAME = slot_##SLOTNAME; \
2373 }
2374
2375#define TPSLOT(OPNAME, SLOTNAME) \
2376 if (PyDict_GetItemString(dict, OPNAME)) { \
2377 type->SLOTNAME = slot_##SLOTNAME; \
2378 }
2379
2380 SQSLOT("__len__", sq_length);
2381 SQSLOT("__add__", sq_concat);
2382 SQSLOT("__mul__", sq_repeat);
2383 SQSLOT("__getitem__", sq_item);
2384 SQSLOT("__getslice__", sq_slice);
2385 SQSLOT("__setitem__", sq_ass_item);
2386 SQSLOT("__delitem__", sq_ass_item);
2387 SQSLOT("__setslice__", sq_ass_slice);
2388 SQSLOT("__delslice__", sq_ass_slice);
2389 SQSLOT("__contains__", sq_contains);
2390 SQSLOT("__iadd__", sq_inplace_concat);
2391 SQSLOT("__imul__", sq_inplace_repeat);
2392
2393 MPSLOT("__len__", mp_length);
2394 MPSLOT("__getitem__", mp_subscript);
2395 MPSLOT("__setitem__", mp_ass_subscript);
2396 MPSLOT("__delitem__", mp_ass_subscript);
2397
2398 NBSLOT("__add__", nb_add);
2399 NBSLOT("__sub__", nb_subtract);
2400 NBSLOT("__mul__", nb_multiply);
2401 NBSLOT("__div__", nb_divide);
2402 NBSLOT("__mod__", nb_remainder);
2403 NBSLOT("__divmod__", nb_divmod);
2404 NBSLOT("__pow__", nb_power);
2405 NBSLOT("__neg__", nb_negative);
2406 NBSLOT("__pos__", nb_positive);
2407 NBSLOT("__abs__", nb_absolute);
2408 NBSLOT("__nonzero__", nb_nonzero);
2409 NBSLOT("__invert__", nb_invert);
2410 NBSLOT("__lshift__", nb_lshift);
2411 NBSLOT("__rshift__", nb_rshift);
2412 NBSLOT("__and__", nb_and);
2413 NBSLOT("__xor__", nb_xor);
2414 NBSLOT("__or__", nb_or);
2415 /* Not coerce() */
2416 NBSLOT("__int__", nb_int);
2417 NBSLOT("__long__", nb_long);
2418 NBSLOT("__float__", nb_float);
2419 NBSLOT("__oct__", nb_oct);
2420 NBSLOT("__hex__", nb_hex);
2421 NBSLOT("__iadd__", nb_inplace_add);
2422 NBSLOT("__isub__", nb_inplace_subtract);
2423 NBSLOT("__imul__", nb_inplace_multiply);
2424 NBSLOT("__idiv__", nb_inplace_divide);
2425 NBSLOT("__imod__", nb_inplace_remainder);
2426 NBSLOT("__ipow__", nb_inplace_power);
2427 NBSLOT("__ilshift__", nb_inplace_lshift);
2428 NBSLOT("__irshift__", nb_inplace_rshift);
2429 NBSLOT("__iand__", nb_inplace_and);
2430 NBSLOT("__ixor__", nb_inplace_xor);
2431 NBSLOT("__ior__", nb_inplace_or);
2432
2433 if (PyDict_GetItemString(dict, "__str__") ||
2434 PyDict_GetItemString(dict, "__repr__"))
2435 type->tp_print = NULL;
2436
2437 TPSLOT("__cmp__", tp_compare);
2438 TPSLOT("__repr__", tp_repr);
2439 TPSLOT("__hash__", tp_hash);
2440 TPSLOT("__call__", tp_call);
2441 TPSLOT("__str__", tp_str);
2442 TPSLOT("__getattr__", tp_getattro);
2443 TPSLOT("__setattr__", tp_setattro);
2444 TPSLOT("__lt__", tp_richcompare);
2445 TPSLOT("__le__", tp_richcompare);
2446 TPSLOT("__eq__", tp_richcompare);
2447 TPSLOT("__ne__", tp_richcompare);
2448 TPSLOT("__gt__", tp_richcompare);
2449 TPSLOT("__ge__", tp_richcompare);
2450 TPSLOT("__iter__", tp_iter);
2451 TPSLOT("next", tp_iternext);
2452 TPSLOT("__get__", tp_descr_get);
2453 TPSLOT("__set__", tp_descr_set);
2454 TPSLOT("__init__", tp_init);
2455 TPSLOT("__new__", tp_new);
2456}