blob: 0aabdae6662f7a39e01359adced49d00bbd8ed13 [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
Guido van Rossumdc91b992001-08-08 22:26:22 +0000586 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
588 Py_TPFLAGS_BASETYPE;
589 if (dynamic)
590 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000591
592 /* It's a new-style number unless it specifically inherits any
593 old-style numeric behavior */
594 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
595 (base->tp_as_number == NULL))
596 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
597
598 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000599 type->tp_as_number = &et->as_number;
600 type->tp_as_sequence = &et->as_sequence;
601 type->tp_as_mapping = &et->as_mapping;
602 type->tp_as_buffer = &et->as_buffer;
603 type->tp_name = PyString_AS_STRING(name);
604
605 /* Set tp_base and tp_bases */
606 type->tp_bases = bases;
607 Py_INCREF(base);
608 type->tp_base = base;
609
610 /* Initialize tp_defined from passed-in dict */
611 type->tp_defined = dict = PyDict_Copy(dict);
612 if (dict == NULL) {
613 Py_DECREF(type);
614 return NULL;
615 }
616
617 /* Special-case __new__: if it's a plain function,
618 make it a static function */
619 tmp = PyDict_GetItemString(dict, "__new__");
620 if (tmp != NULL && PyFunction_Check(tmp)) {
621 tmp = PyStaticMethod_New(tmp);
622 if (tmp == NULL) {
623 Py_DECREF(type);
624 return NULL;
625 }
626 PyDict_SetItemString(dict, "__new__", tmp);
627 Py_DECREF(tmp);
628 }
629
630 /* Add descriptors for custom slots from __slots__, or for __dict__ */
631 mp = et->members;
632 slotoffset = PyType_BASICSIZE(base);
633 if (slots != NULL) {
634 for (i = 0; i < nslots; i++, mp++) {
635 mp->name = PyString_AS_STRING(
636 PyTuple_GET_ITEM(slots, i));
637 mp->type = T_OBJECT;
638 mp->offset = slotoffset;
639 slotoffset += sizeof(PyObject *);
640 }
641 }
642 else if (nslots) {
643 type->tp_dictoffset = slotoffset;
644 mp->name = "__dict__";
645 mp->type = T_OBJECT;
646 mp->offset = slotoffset;
647 mp->readonly = 1;
648 slotoffset += sizeof(PyObject *);
649 }
650 type->tp_basicsize = slotoffset;
651 add_members(type, et->members);
652
653 /* Special case some slots */
654 if (type->tp_dictoffset != 0 || nslots > 0) {
655 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
656 type->tp_getattro = PyObject_GenericGetAttr;
657 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
658 type->tp_setattro = PyObject_GenericSetAttr;
659 }
660 type->tp_dealloc = subtype_dealloc;
661
662 /* Always override allocation strategy to use regular heap */
663 type->tp_alloc = PyType_GenericAlloc;
664 type->tp_free = _PyObject_Del;
665
666 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000667 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668 Py_DECREF(type);
669 return NULL;
670 }
671
672 /* Override slots that deserve it */
673 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000674
675 /* Special hack for __new__ */
676 if (type->tp_new == NULL) {
677 /* Can't do this earlier, or some nasty recursion happens. */
678 type->tp_new = PyType_GenericNew;
679 if (add_tp_new_wrapper(type) < 0) {
680 Py_DECREF(type);
681 return NULL;
682 }
683 }
684
Tim Peters6d6c1a32001-08-02 04:15:00 +0000685 return (PyObject *)type;
686}
687
688/* Internal API to look for a name through the MRO.
689 This returns a borrowed reference, and doesn't set an exception! */
690PyObject *
691_PyType_Lookup(PyTypeObject *type, PyObject *name)
692{
693 int i, n;
694 PyObject *mro, *res, *dict;
695
696 /* For static types, look in tp_dict */
697 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
698 dict = type->tp_dict;
699 assert(dict && PyDict_Check(dict));
700 return PyDict_GetItem(dict, name);
701 }
702
703 /* For dynamic types, look in tp_defined of types in MRO */
704 mro = type->tp_mro;
705 assert(PyTuple_Check(mro));
706 n = PyTuple_GET_SIZE(mro);
707 for (i = 0; i < n; i++) {
708 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
709 assert(PyType_Check(type));
710 dict = type->tp_defined;
711 assert(dict && PyDict_Check(dict));
712 res = PyDict_GetItem(dict, name);
713 if (res != NULL)
714 return res;
715 }
716 return NULL;
717}
718
719/* This is similar to PyObject_GenericGetAttr(),
720 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
721static PyObject *
722type_getattro(PyTypeObject *type, PyObject *name)
723{
724 PyTypeObject *metatype = type->ob_type;
725 PyObject *descr, *res;
726 descrgetfunc f;
727
728 /* Initialize this type (we'll assume the metatype is initialized) */
729 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000730 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000731 return NULL;
732 }
733
734 /* Get a descriptor from the metatype */
735 descr = _PyType_Lookup(metatype, name);
736 f = NULL;
737 if (descr != NULL) {
738 f = descr->ob_type->tp_descr_get;
739 if (f != NULL && PyDescr_IsData(descr))
740 return f(descr,
741 (PyObject *)type, (PyObject *)metatype);
742 }
743
744 /* Look in tp_defined of this type and its bases */
745 res = _PyType_Lookup(type, name);
746 if (res != NULL) {
747 f = res->ob_type->tp_descr_get;
748 if (f != NULL)
749 return f(res, (PyObject *)NULL, (PyObject *)type);
750 Py_INCREF(res);
751 return res;
752 }
753
754 /* Use the descriptor from the metatype */
755 if (f != NULL) {
756 res = f(descr, (PyObject *)type, (PyObject *)metatype);
757 return res;
758 }
759 if (descr != NULL) {
760 Py_INCREF(descr);
761 return descr;
762 }
763
764 /* Give up */
765 PyErr_Format(PyExc_AttributeError,
766 "type object '%.50s' has no attribute '%.400s'",
767 type->tp_name, PyString_AS_STRING(name));
768 return NULL;
769}
770
771static int
772type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
773{
774 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
775 return PyObject_GenericSetAttr((PyObject *)type, name, value);
776 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
777 return -1;
778}
779
780static void
781type_dealloc(PyTypeObject *type)
782{
783 etype *et;
784
785 /* Assert this is a heap-allocated type object */
786 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
787 et = (etype *)type;
788 Py_XDECREF(type->tp_base);
789 Py_XDECREF(type->tp_dict);
790 Py_XDECREF(type->tp_bases);
791 Py_XDECREF(type->tp_mro);
792 Py_XDECREF(type->tp_defined);
793 /* XXX more? */
794 Py_XDECREF(et->name);
795 Py_XDECREF(et->slots);
796 type->ob_type->tp_free((PyObject *)type);
797}
798
799static PyMethodDef type_methods[] = {
800 {"mro", mro_external, METH_VARARGS,
801 "mro() -> list\nreturn a type's method resolution order"},
802 {0}
803};
804
805static char type_doc[] =
806"type(object) -> the object's type\n"
807"type(name, bases, dict) -> a new type";
808
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809PyTypeObject PyType_Type = {
810 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811 0, /* ob_size */
812 "type", /* tp_name */
813 sizeof(etype), /* tp_basicsize */
814 sizeof(struct memberlist), /* tp_itemsize */
815 (destructor)type_dealloc, /* tp_dealloc */
816 0, /* tp_print */
817 0, /* tp_getattr */
818 0, /* tp_setattr */
819 type_compare, /* tp_compare */
820 (reprfunc)type_repr, /* tp_repr */
821 0, /* tp_as_number */
822 0, /* tp_as_sequence */
823 0, /* tp_as_mapping */
824 (hashfunc)_Py_HashPointer, /* tp_hash */
825 (ternaryfunc)type_call, /* tp_call */
826 0, /* tp_str */
827 (getattrofunc)type_getattro, /* tp_getattro */
828 (setattrofunc)type_setattro, /* tp_setattro */
829 0, /* tp_as_buffer */
830 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
831 type_doc, /* tp_doc */
832 0, /* tp_traverse */
833 0, /* tp_clear */
834 0, /* tp_richcompare */
835 0, /* tp_weaklistoffset */
836 0, /* tp_iter */
837 0, /* tp_iternext */
838 type_methods, /* tp_methods */
839 type_members, /* tp_members */
840 type_getsets, /* tp_getset */
841 0, /* tp_base */
842 0, /* tp_dict */
843 0, /* tp_descr_get */
844 0, /* tp_descr_set */
845 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
846 0, /* tp_init */
847 0, /* tp_alloc */
848 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000849};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850
851
852/* The base type of all types (eventually)... except itself. */
853
854static int
855object_init(PyObject *self, PyObject *args, PyObject *kwds)
856{
857 return 0;
858}
859
860static void
861object_dealloc(PyObject *self)
862{
863 self->ob_type->tp_free(self);
864}
865
866static void
867object_free(PyObject *self)
868{
869 PyObject_Del(self);
870}
871
872static struct memberlist object_members[] = {
873 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
874 {0}
875};
876
877PyTypeObject PyBaseObject_Type = {
878 PyObject_HEAD_INIT(&PyType_Type)
879 0, /* ob_size */
880 "object", /* tp_name */
881 sizeof(PyObject), /* tp_basicsize */
882 0, /* tp_itemsize */
883 (destructor)object_dealloc, /* tp_dealloc */
884 0, /* tp_print */
885 0, /* tp_getattr */
886 0, /* tp_setattr */
887 0, /* tp_compare */
888 0, /* tp_repr */
889 0, /* tp_as_number */
890 0, /* tp_as_sequence */
891 0, /* tp_as_mapping */
892 0, /* tp_hash */
893 0, /* tp_call */
894 0, /* tp_str */
895 PyObject_GenericGetAttr, /* tp_getattro */
896 0, /* tp_setattro */
897 0, /* tp_as_buffer */
898 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
899 "The most base type", /* tp_doc */
900 0, /* tp_traverse */
901 0, /* tp_clear */
902 0, /* tp_richcompare */
903 0, /* tp_weaklistoffset */
904 0, /* tp_iter */
905 0, /* tp_iternext */
906 0, /* tp_methods */
907 object_members, /* tp_members */
908 0, /* tp_getset */
909 0, /* tp_base */
910 0, /* tp_dict */
911 0, /* tp_descr_get */
912 0, /* tp_descr_set */
913 0, /* tp_dictoffset */
914 object_init, /* tp_init */
915 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumf040ede2001-08-07 16:40:56 +0000916 0, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917 object_free, /* tp_free */
918};
919
920
921/* Initialize the __dict__ in a type object */
922
923static int
924add_methods(PyTypeObject *type, PyMethodDef *meth)
925{
926 PyObject *dict = type->tp_defined;
927
928 for (; meth->ml_name != NULL; meth++) {
929 PyObject *descr;
930 if (PyDict_GetItemString(dict, meth->ml_name))
931 continue;
932 descr = PyDescr_NewMethod(type, meth);
933 if (descr == NULL)
934 return -1;
935 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
936 return -1;
937 Py_DECREF(descr);
938 }
939 return 0;
940}
941
942static int
Guido van Rossumf040ede2001-08-07 16:40:56 +0000943add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000944{
945 PyObject *dict = type->tp_defined;
946
Guido van Rossumf040ede2001-08-07 16:40:56 +0000947 for (; wraps->name != NULL; wraps++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000948 PyObject *descr;
Guido van Rossumf040ede2001-08-07 16:40:56 +0000949 if (PyDict_GetItemString(dict, wraps->name))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000950 continue;
Guido van Rossumf040ede2001-08-07 16:40:56 +0000951 descr = PyDescr_NewWrapper(type, wraps, wrapped);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000952 if (descr == NULL)
953 return -1;
Guido van Rossumf040ede2001-08-07 16:40:56 +0000954 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000955 return -1;
956 Py_DECREF(descr);
957 }
958 return 0;
959}
960
961static int
Tim Peters6d6c1a32001-08-02 04:15:00 +0000962add_members(PyTypeObject *type, struct memberlist *memb)
963{
964 PyObject *dict = type->tp_defined;
965
966 for (; memb->name != NULL; memb++) {
967 PyObject *descr;
968 if (PyDict_GetItemString(dict, memb->name))
969 continue;
970 descr = PyDescr_NewMember(type, memb);
971 if (descr == NULL)
972 return -1;
973 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
974 return -1;
975 Py_DECREF(descr);
976 }
977 return 0;
978}
979
980static int
981add_getset(PyTypeObject *type, struct getsetlist *gsp)
982{
983 PyObject *dict = type->tp_defined;
984
985 for (; gsp->name != NULL; gsp++) {
986 PyObject *descr;
987 if (PyDict_GetItemString(dict, gsp->name))
988 continue;
989 descr = PyDescr_NewGetSet(type, gsp);
990
991 if (descr == NULL)
992 return -1;
993 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
994 return -1;
995 Py_DECREF(descr);
996 }
997 return 0;
998}
999
1000staticforward int add_operators(PyTypeObject *);
1001
1002static int
1003inherit_slots(PyTypeObject *type, PyTypeObject *base)
1004{
1005 int oldsize, newsize;
1006
1007#undef COPYSLOT
1008#undef COPYNUM
1009#undef COPYSEQ
1010#undef COPYMAP
1011#define COPYSLOT(SLOT) \
1012 if (!type->SLOT) type->SLOT = base->SLOT
1013
1014#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1015#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1016#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1017
1018 if (type->tp_as_number == NULL)
1019 type->tp_as_number = base->tp_as_number;
1020 else if (base->tp_as_number) {
1021 COPYNUM(nb_add);
1022 COPYNUM(nb_subtract);
1023 COPYNUM(nb_multiply);
1024 COPYNUM(nb_divide);
1025 COPYNUM(nb_remainder);
1026 COPYNUM(nb_divmod);
1027 COPYNUM(nb_power);
1028 COPYNUM(nb_negative);
1029 COPYNUM(nb_positive);
1030 COPYNUM(nb_absolute);
1031 COPYNUM(nb_nonzero);
1032 COPYNUM(nb_invert);
1033 COPYNUM(nb_lshift);
1034 COPYNUM(nb_rshift);
1035 COPYNUM(nb_and);
1036 COPYNUM(nb_xor);
1037 COPYNUM(nb_or);
1038 COPYNUM(nb_coerce);
1039 COPYNUM(nb_int);
1040 COPYNUM(nb_long);
1041 COPYNUM(nb_float);
1042 COPYNUM(nb_oct);
1043 COPYNUM(nb_hex);
1044 COPYNUM(nb_inplace_add);
1045 COPYNUM(nb_inplace_subtract);
1046 COPYNUM(nb_inplace_multiply);
1047 COPYNUM(nb_inplace_divide);
1048 COPYNUM(nb_inplace_remainder);
1049 COPYNUM(nb_inplace_power);
1050 COPYNUM(nb_inplace_lshift);
1051 COPYNUM(nb_inplace_rshift);
1052 COPYNUM(nb_inplace_and);
1053 COPYNUM(nb_inplace_xor);
1054 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001055 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1056 COPYNUM(nb_true_divide);
1057 COPYNUM(nb_floor_divide);
1058 COPYNUM(nb_inplace_true_divide);
1059 COPYNUM(nb_inplace_floor_divide);
1060 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001061 }
1062
1063 if (type->tp_as_sequence == NULL)
1064 type->tp_as_sequence = base->tp_as_sequence;
1065 else if (base->tp_as_sequence) {
1066 COPYSEQ(sq_length);
1067 COPYSEQ(sq_concat);
1068 COPYSEQ(sq_repeat);
1069 COPYSEQ(sq_item);
1070 COPYSEQ(sq_slice);
1071 COPYSEQ(sq_ass_item);
1072 COPYSEQ(sq_ass_slice);
1073 COPYSEQ(sq_contains);
1074 COPYSEQ(sq_inplace_concat);
1075 COPYSEQ(sq_inplace_repeat);
1076 }
1077
1078 if (type->tp_as_mapping == NULL)
1079 type->tp_as_mapping = base->tp_as_mapping;
1080 else if (base->tp_as_mapping) {
1081 COPYMAP(mp_length);
1082 COPYMAP(mp_subscript);
1083 COPYMAP(mp_ass_subscript);
1084 }
1085
1086 /* Special flag magic */
1087 if (!type->tp_as_buffer && base->tp_as_buffer) {
1088 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1089 type->tp_flags |=
1090 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1091 }
1092 if (!type->tp_as_sequence && base->tp_as_sequence) {
1093 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1094 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1095 }
1096 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1097 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1098 if ((!type->tp_as_number && base->tp_as_number) ||
1099 (!type->tp_as_sequence && base->tp_as_sequence)) {
1100 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1101 if (!type->tp_as_number && !type->tp_as_sequence) {
1102 type->tp_flags |= base->tp_flags &
1103 Py_TPFLAGS_HAVE_INPLACEOPS;
1104 }
1105 }
1106 /* Wow */
1107 }
1108 if (!type->tp_as_number && base->tp_as_number) {
1109 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1110 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1111 }
1112
1113 /* Copying basicsize is connected to the GC flags */
1114 oldsize = PyType_BASICSIZE(base);
1115 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1116 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1117 (base->tp_flags & Py_TPFLAGS_GC) &&
1118 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1119 (!type->tp_traverse && !type->tp_clear)) {
1120 type->tp_flags |= Py_TPFLAGS_GC;
1121 COPYSLOT(tp_traverse);
1122 COPYSLOT(tp_clear);
1123 }
1124 PyType_SET_BASICSIZE(type, newsize);
1125
1126 COPYSLOT(tp_itemsize);
1127 COPYSLOT(tp_dealloc);
1128 COPYSLOT(tp_print);
1129 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1130 type->tp_getattr = base->tp_getattr;
1131 type->tp_getattro = base->tp_getattro;
1132 }
1133 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1134 type->tp_setattr = base->tp_setattr;
1135 type->tp_setattro = base->tp_setattro;
1136 }
1137 /* tp_compare see tp_richcompare */
1138 COPYSLOT(tp_repr);
1139 COPYSLOT(tp_hash);
1140 COPYSLOT(tp_call);
1141 COPYSLOT(tp_str);
1142 COPYSLOT(tp_as_buffer);
1143 COPYSLOT(tp_flags);
1144 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
1145 if (type->tp_compare == NULL && type->tp_richcompare == NULL) {
1146 type->tp_compare = base->tp_compare;
1147 type->tp_richcompare = base->tp_richcompare;
1148 }
1149 }
1150 else {
1151 COPYSLOT(tp_compare);
1152 }
1153 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1154 COPYSLOT(tp_weaklistoffset);
1155 }
1156 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1157 COPYSLOT(tp_iter);
1158 COPYSLOT(tp_iternext);
1159 }
1160 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1161 COPYSLOT(tp_descr_get);
1162 COPYSLOT(tp_descr_set);
1163 COPYSLOT(tp_dictoffset);
1164 COPYSLOT(tp_init);
1165 COPYSLOT(tp_alloc);
1166 COPYSLOT(tp_new);
1167 COPYSLOT(tp_free);
1168 }
1169
1170 return 0;
1171}
1172
1173int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001174PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175{
1176 PyObject *dict, *bases, *x;
1177 PyTypeObject *base;
1178 int i, n;
1179
1180 if (type->tp_dict != NULL)
1181 return 0; /* Already initialized */
1182
1183 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1184 base = type->tp_base;
1185 if (base == NULL && type != &PyBaseObject_Type)
1186 base = type->tp_base = &PyBaseObject_Type;
1187
1188 /* Initialize tp_bases */
1189 bases = type->tp_bases;
1190 if (bases == NULL) {
1191 if (base == NULL)
1192 bases = PyTuple_New(0);
1193 else
1194 bases = Py_BuildValue("(O)", base);
1195 if (bases == NULL)
1196 return -1;
1197 type->tp_bases = bases;
1198 }
1199
1200 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001201 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001202 if (PyType_Ready(base) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 return -1;
1204 }
1205
1206 /* Initialize tp_defined */
1207 dict = type->tp_defined;
1208 if (dict == NULL) {
1209 dict = PyDict_New();
1210 if (dict == NULL)
1211 return -1;
1212 type->tp_defined = dict;
1213 }
1214
1215 /* Add type-specific descriptors to tp_defined */
1216 if (add_operators(type) < 0)
1217 return -1;
1218 if (type->tp_methods != NULL) {
1219 if (add_methods(type, type->tp_methods) < 0)
1220 return -1;
1221 }
1222 if (type->tp_members != NULL) {
1223 if (add_members(type, type->tp_members) < 0)
1224 return -1;
1225 }
1226 if (type->tp_getset != NULL) {
1227 if (add_getset(type, type->tp_getset) < 0)
1228 return -1;
1229 }
1230
1231 /* Temporarily make tp_dict the same object as tp_defined.
1232 (This is needed to call mro(), and can stay this way for
1233 dynamic types). */
1234 Py_INCREF(type->tp_defined);
1235 type->tp_dict = type->tp_defined;
1236
1237 /* Calculate method resolution order */
1238 if (mro_internal(type) < 0) {
1239 return -1;
1240 }
1241
1242 /* Initialize tp_dict properly */
1243 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
1244 /* For a static type, tp_dict is the consolidation
1245 of the tp_defined of its bases in MRO. Earlier
1246 bases override later bases; since d.update() works
1247 the other way, we walk the MRO sequence backwards. */
1248 Py_DECREF(type->tp_dict);
1249 type->tp_dict = PyDict_New();
1250 if (type->tp_dict == NULL)
1251 return -1;
1252 bases = type->tp_mro;
1253 assert(bases != NULL);
1254 assert(PyTuple_Check(bases));
1255 n = PyTuple_GET_SIZE(bases);
1256 for (i = n; --i >= 0; ) {
1257 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1258 assert(PyType_Check(base));
1259 x = base->tp_defined;
1260 if (x != NULL && PyDict_Update(type->tp_dict, x) < 0)
1261 return -1;
1262 }
1263 }
1264
1265 /* Inherit slots from direct base */
1266 if (type->tp_base != NULL)
1267 if (inherit_slots(type, type->tp_base) < 0)
1268 return -1;
1269
1270 return 0;
1271}
1272
1273
1274/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1275
1276/* There's a wrapper *function* for each distinct function typedef used
1277 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1278 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1279 Most tables have only one entry; the tables for binary operators have two
1280 entries, one regular and one with reversed arguments. */
1281
1282static PyObject *
1283wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1284{
1285 inquiry func = (inquiry)wrapped;
1286 int res;
1287
1288 if (!PyArg_ParseTuple(args, ""))
1289 return NULL;
1290 res = (*func)(self);
1291 if (res == -1 && PyErr_Occurred())
1292 return NULL;
1293 return PyInt_FromLong((long)res);
1294}
1295
1296static struct wrapperbase tab_len[] = {
1297 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1298 {0}
1299};
1300
1301static PyObject *
1302wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1303{
1304 binaryfunc func = (binaryfunc)wrapped;
1305 PyObject *other;
1306
1307 if (!PyArg_ParseTuple(args, "O", &other))
1308 return NULL;
1309 return (*func)(self, other);
1310}
1311
1312static PyObject *
1313wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1314{
1315 binaryfunc func = (binaryfunc)wrapped;
1316 PyObject *other;
1317
1318 if (!PyArg_ParseTuple(args, "O", &other))
1319 return NULL;
1320 return (*func)(other, self);
1321}
1322
1323#undef BINARY
1324#define BINARY(NAME, OP) \
1325static struct wrapperbase tab_##NAME[] = { \
1326 {"__" #NAME "__", \
1327 (wrapperfunc)wrap_binaryfunc, \
1328 "x.__" #NAME "__(y) <==> " #OP}, \
1329 {"__r" #NAME "__", \
1330 (wrapperfunc)wrap_binaryfunc_r, \
1331 "y.__r" #NAME "__(x) <==> " #OP}, \
1332 {0} \
1333}
1334
1335BINARY(add, "x+y");
1336BINARY(sub, "x-y");
1337BINARY(mul, "x*y");
1338BINARY(div, "x/y");
1339BINARY(mod, "x%y");
1340BINARY(divmod, "divmod(x,y)");
1341BINARY(lshift, "x<<y");
1342BINARY(rshift, "x>>y");
1343BINARY(and, "x&y");
1344BINARY(xor, "x^y");
1345BINARY(or, "x|y");
1346
1347static PyObject *
1348wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1349{
1350 ternaryfunc func = (ternaryfunc)wrapped;
1351 PyObject *other;
1352 PyObject *third = Py_None;
1353
1354 /* Note: This wrapper only works for __pow__() */
1355
1356 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1357 return NULL;
1358 return (*func)(self, other, third);
1359}
1360
1361#undef TERNARY
1362#define TERNARY(NAME, OP) \
1363static struct wrapperbase tab_##NAME[] = { \
1364 {"__" #NAME "__", \
1365 (wrapperfunc)wrap_ternaryfunc, \
1366 "x.__" #NAME "__(y, z) <==> " #OP}, \
1367 {"__r" #NAME "__", \
1368 (wrapperfunc)wrap_ternaryfunc, \
1369 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1370 {0} \
1371}
1372
1373TERNARY(pow, "(x**y) % z");
1374
1375#undef UNARY
1376#define UNARY(NAME, OP) \
1377static struct wrapperbase tab_##NAME[] = { \
1378 {"__" #NAME "__", \
1379 (wrapperfunc)wrap_unaryfunc, \
1380 "x.__" #NAME "__() <==> " #OP}, \
1381 {0} \
1382}
1383
1384static PyObject *
1385wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1386{
1387 unaryfunc func = (unaryfunc)wrapped;
1388
1389 if (!PyArg_ParseTuple(args, ""))
1390 return NULL;
1391 return (*func)(self);
1392}
1393
1394UNARY(neg, "-x");
1395UNARY(pos, "+x");
1396UNARY(abs, "abs(x)");
1397UNARY(nonzero, "x != 0");
1398UNARY(invert, "~x");
1399UNARY(int, "int(x)");
1400UNARY(long, "long(x)");
1401UNARY(float, "float(x)");
1402UNARY(oct, "oct(x)");
1403UNARY(hex, "hex(x)");
1404
1405#undef IBINARY
1406#define IBINARY(NAME, OP) \
1407static struct wrapperbase tab_##NAME[] = { \
1408 {"__" #NAME "__", \
1409 (wrapperfunc)wrap_binaryfunc, \
1410 "x.__" #NAME "__(y) <==> " #OP}, \
1411 {0} \
1412}
1413
1414IBINARY(iadd, "x+=y");
1415IBINARY(isub, "x-=y");
1416IBINARY(imul, "x*=y");
1417IBINARY(idiv, "x/=y");
1418IBINARY(imod, "x%=y");
1419IBINARY(ilshift, "x<<=y");
1420IBINARY(irshift, "x>>=y");
1421IBINARY(iand, "x&=y");
1422IBINARY(ixor, "x^=y");
1423IBINARY(ior, "x|=y");
1424
1425#undef ITERNARY
1426#define ITERNARY(NAME, OP) \
1427static struct wrapperbase tab_##NAME[] = { \
1428 {"__" #NAME "__", \
1429 (wrapperfunc)wrap_ternaryfunc, \
1430 "x.__" #NAME "__(y) <==> " #OP}, \
1431 {0} \
1432}
1433
1434ITERNARY(ipow, "x = (x**y) % z");
1435
1436static struct wrapperbase tab_getitem[] = {
1437 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1438 "x.__getitem__(y) <==> x[y]"},
1439 {0}
1440};
1441
1442static PyObject *
1443wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1444{
1445 intargfunc func = (intargfunc)wrapped;
1446 int i;
1447
1448 if (!PyArg_ParseTuple(args, "i", &i))
1449 return NULL;
1450 return (*func)(self, i);
1451}
1452
1453static struct wrapperbase tab_mul_int[] = {
1454 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1455 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1456 {0}
1457};
1458
1459static struct wrapperbase tab_concat[] = {
1460 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1461 {0}
1462};
1463
1464static struct wrapperbase tab_imul_int[] = {
1465 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1466 {0}
1467};
1468
1469static struct wrapperbase tab_getitem_int[] = {
1470 {"__getitem__", (wrapperfunc)wrap_intargfunc,
1471 "x.__getitem__(i) <==> x[i]"},
1472 {0}
1473};
1474
1475static PyObject *
1476wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1477{
1478 intintargfunc func = (intintargfunc)wrapped;
1479 int i, j;
1480
1481 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1482 return NULL;
1483 return (*func)(self, i, j);
1484}
1485
1486static struct wrapperbase tab_getslice[] = {
1487 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1488 "x.__getslice__(i, j) <==> x[i:j]"},
1489 {0}
1490};
1491
1492static PyObject *
1493wrap_intobjargproc(PyObject *self, PyObject *args, void *wrapped)
1494{
1495 intobjargproc func = (intobjargproc)wrapped;
1496 int i, res;
1497 PyObject *value;
1498
1499 if (!PyArg_ParseTuple(args, "iO", &i, &value))
1500 return NULL;
1501 res = (*func)(self, i, value);
1502 if (res == -1 && PyErr_Occurred())
1503 return NULL;
1504 Py_INCREF(Py_None);
1505 return Py_None;
1506}
1507
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001508static PyObject *
1509wrap_delitem_int(PyObject *self, PyObject *args, void *wrapped)
1510{
1511 intobjargproc func = (intobjargproc)wrapped;
1512 int i, res;
1513
1514 if (!PyArg_ParseTuple(args, "i", &i))
1515 return NULL;
1516 res = (*func)(self, i, NULL);
1517 if (res == -1 && PyErr_Occurred())
1518 return NULL;
1519 Py_INCREF(Py_None);
1520 return Py_None;
1521}
1522
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523static struct wrapperbase tab_setitem_int[] = {
1524 {"__setitem__", (wrapperfunc)wrap_intobjargproc,
1525 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001526 {"__delitem__", (wrapperfunc)wrap_delitem_int,
1527 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001528 {0}
1529};
1530
1531static PyObject *
1532wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1533{
1534 intintobjargproc func = (intintobjargproc)wrapped;
1535 int i, j, res;
1536 PyObject *value;
1537
1538 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1539 return NULL;
1540 res = (*func)(self, i, j, value);
1541 if (res == -1 && PyErr_Occurred())
1542 return NULL;
1543 Py_INCREF(Py_None);
1544 return Py_None;
1545}
1546
1547static struct wrapperbase tab_setslice[] = {
1548 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1549 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1550 {0}
1551};
1552
1553/* XXX objobjproc is a misnomer; should be objargpred */
1554static PyObject *
1555wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1556{
1557 objobjproc func = (objobjproc)wrapped;
1558 int res;
1559 PyObject *value;
1560
1561 if (!PyArg_ParseTuple(args, "O", &value))
1562 return NULL;
1563 res = (*func)(self, value);
1564 if (res == -1 && PyErr_Occurred())
1565 return NULL;
1566 return PyInt_FromLong((long)res);
1567}
1568
1569static struct wrapperbase tab_contains[] = {
1570 {"__contains__", (wrapperfunc)wrap_objobjproc,
1571 "x.__contains__(y) <==> y in x"},
1572 {0}
1573};
1574
1575static PyObject *
1576wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1577{
1578 objobjargproc func = (objobjargproc)wrapped;
1579 int res;
1580 PyObject *key, *value;
1581
1582 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1583 return NULL;
1584 res = (*func)(self, key, value);
1585 if (res == -1 && PyErr_Occurred())
1586 return NULL;
1587 Py_INCREF(Py_None);
1588 return Py_None;
1589}
1590
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001591static PyObject *
1592wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1593{
1594 objobjargproc func = (objobjargproc)wrapped;
1595 int res;
1596 PyObject *key;
1597
1598 if (!PyArg_ParseTuple(args, "O", &key))
1599 return NULL;
1600 res = (*func)(self, key, NULL);
1601 if (res == -1 && PyErr_Occurred())
1602 return NULL;
1603 Py_INCREF(Py_None);
1604 return Py_None;
1605}
1606
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607static struct wrapperbase tab_setitem[] = {
1608 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1609 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001610 {"__delitem__", (wrapperfunc)wrap_delitem,
1611 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001612 {0}
1613};
1614
1615static PyObject *
1616wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1617{
1618 cmpfunc func = (cmpfunc)wrapped;
1619 int res;
1620 PyObject *other;
1621
1622 if (!PyArg_ParseTuple(args, "O", &other))
1623 return NULL;
1624 res = (*func)(self, other);
1625 if (PyErr_Occurred())
1626 return NULL;
1627 return PyInt_FromLong((long)res);
1628}
1629
1630static struct wrapperbase tab_cmp[] = {
1631 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1632 "x.__cmp__(y) <==> cmp(x,y)"},
1633 {0}
1634};
1635
1636static struct wrapperbase tab_repr[] = {
1637 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1638 "x.__repr__() <==> repr(x)"},
1639 {0}
1640};
1641
1642static struct wrapperbase tab_getattr[] = {
1643 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1644 "x.__getattr__('name') <==> x.name"},
1645 {0}
1646};
1647
1648static PyObject *
1649wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1650{
1651 setattrofunc func = (setattrofunc)wrapped;
1652 int res;
1653 PyObject *name, *value;
1654
1655 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1656 return NULL;
1657 res = (*func)(self, name, value);
1658 if (res < 0)
1659 return NULL;
1660 Py_INCREF(Py_None);
1661 return Py_None;
1662}
1663
1664static PyObject *
1665wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1666{
1667 setattrofunc func = (setattrofunc)wrapped;
1668 int res;
1669 PyObject *name;
1670
1671 if (!PyArg_ParseTuple(args, "O", &name))
1672 return NULL;
1673 res = (*func)(self, name, NULL);
1674 if (res < 0)
1675 return NULL;
1676 Py_INCREF(Py_None);
1677 return Py_None;
1678}
1679
1680static struct wrapperbase tab_setattr[] = {
1681 {"__setattr__", (wrapperfunc)wrap_setattr,
1682 "x.__setattr__('name', value) <==> x.name = value"},
1683 {"__delattr__", (wrapperfunc)wrap_delattr,
1684 "x.__delattr__('name') <==> del x.name"},
1685 {0}
1686};
1687
1688static PyObject *
1689wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1690{
1691 hashfunc func = (hashfunc)wrapped;
1692 long res;
1693
1694 if (!PyArg_ParseTuple(args, ""))
1695 return NULL;
1696 res = (*func)(self);
1697 if (res == -1 && PyErr_Occurred())
1698 return NULL;
1699 return PyInt_FromLong(res);
1700}
1701
1702static struct wrapperbase tab_hash[] = {
1703 {"__hash__", (wrapperfunc)wrap_hashfunc,
1704 "x.__hash__() <==> hash(x)"},
1705 {0}
1706};
1707
1708static PyObject *
1709wrap_call(PyObject *self, PyObject *args, void *wrapped)
1710{
1711 ternaryfunc func = (ternaryfunc)wrapped;
1712
1713 /* XXX What about keyword arguments? */
1714 return (*func)(self, args, NULL);
1715}
1716
1717static struct wrapperbase tab_call[] = {
1718 {"__call__", (wrapperfunc)wrap_call,
1719 "x.__call__(...) <==> x(...)"},
1720 {0}
1721};
1722
1723static struct wrapperbase tab_str[] = {
1724 {"__str__", (wrapperfunc)wrap_unaryfunc,
1725 "x.__str__() <==> str(x)"},
1726 {0}
1727};
1728
1729static PyObject *
1730wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1731{
1732 richcmpfunc func = (richcmpfunc)wrapped;
1733 PyObject *other;
1734
1735 if (!PyArg_ParseTuple(args, "O", &other))
1736 return NULL;
1737 return (*func)(self, other, op);
1738}
1739
1740#undef RICHCMP_WRAPPER
1741#define RICHCMP_WRAPPER(NAME, OP) \
1742static PyObject * \
1743richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1744{ \
1745 return wrap_richcmpfunc(self, args, wrapped, OP); \
1746}
1747
Jack Jansen8e938b42001-08-08 15:29:49 +00001748RICHCMP_WRAPPER(lt, Py_LT)
1749RICHCMP_WRAPPER(le, Py_LE)
1750RICHCMP_WRAPPER(eq, Py_EQ)
1751RICHCMP_WRAPPER(ne, Py_NE)
1752RICHCMP_WRAPPER(gt, Py_GT)
1753RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001754
1755#undef RICHCMP_ENTRY
1756#define RICHCMP_ENTRY(NAME, EXPR) \
1757 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1758 "x.__" #NAME "__(y) <==> " EXPR}
1759
1760static struct wrapperbase tab_richcmp[] = {
1761 RICHCMP_ENTRY(lt, "x<y"),
1762 RICHCMP_ENTRY(le, "x<=y"),
1763 RICHCMP_ENTRY(eq, "x==y"),
1764 RICHCMP_ENTRY(ne, "x!=y"),
1765 RICHCMP_ENTRY(gt, "x>y"),
1766 RICHCMP_ENTRY(ge, "x>=y"),
1767 {0}
1768};
1769
1770static struct wrapperbase tab_iter[] = {
1771 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
1772 {0}
1773};
1774
1775static PyObject *
1776wrap_next(PyObject *self, PyObject *args, void *wrapped)
1777{
1778 unaryfunc func = (unaryfunc)wrapped;
1779 PyObject *res;
1780
1781 if (!PyArg_ParseTuple(args, ""))
1782 return NULL;
1783 res = (*func)(self);
1784 if (res == NULL && !PyErr_Occurred())
1785 PyErr_SetNone(PyExc_StopIteration);
1786 return res;
1787}
1788
1789static struct wrapperbase tab_next[] = {
1790 {"next", (wrapperfunc)wrap_next,
1791 "x.next() -> the next value, or raise StopIteration"},
1792 {0}
1793};
1794
1795static PyObject *
1796wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
1797{
1798 descrgetfunc func = (descrgetfunc)wrapped;
1799 PyObject *obj;
1800 PyObject *type = NULL;
1801
1802 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
1803 return NULL;
1804 if (type == NULL)
1805 type = (PyObject *)obj->ob_type;
1806 return (*func)(self, obj, type);
1807}
1808
1809static struct wrapperbase tab_descr_get[] = {
1810 {"__get__", (wrapperfunc)wrap_descr_get,
1811 "descr.__get__(obj, type) -> value"},
1812 {0}
1813};
1814
1815static PyObject *
1816wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
1817{
1818 descrsetfunc func = (descrsetfunc)wrapped;
1819 PyObject *obj, *value;
1820 int ret;
1821
1822 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
1823 return NULL;
1824 ret = (*func)(self, obj, value);
1825 if (ret < 0)
1826 return NULL;
1827 Py_INCREF(Py_None);
1828 return Py_None;
1829}
1830
1831static struct wrapperbase tab_descr_set[] = {
1832 {"__set__", (wrapperfunc)wrap_descrsetfunc,
1833 "descr.__set__(obj, value)"},
1834 {0}
1835};
1836
1837static PyObject *
1838wrap_init(PyObject *self, PyObject *args, void *wrapped)
1839{
1840 initproc func = (initproc)wrapped;
1841
1842 /* XXX What about keyword arguments? */
1843 if (func(self, args, NULL) < 0)
1844 return NULL;
1845 Py_INCREF(Py_None);
1846 return Py_None;
1847}
1848
1849static struct wrapperbase tab_init[] = {
1850 {"__init__", (wrapperfunc)wrap_init,
1851 "x.__init__(...) initializes x; "
1852 "see x.__type__.__doc__ for signature"},
1853 {0}
1854};
1855
1856static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001857tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858{
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001859 PyTypeObject *type, *subtype;
1860 PyObject *arg0, *res;
1861
1862 if (self == NULL || !PyType_Check(self))
1863 Py_FatalError("__new__() called with non-type 'self'");
1864 type = (PyTypeObject *)self;
1865 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
1866 PyErr_SetString(PyExc_TypeError,
1867 "T.__new__(): not enough arguments");
1868 return NULL;
1869 }
1870 arg0 = PyTuple_GET_ITEM(args, 0);
1871 if (!PyType_Check(arg0)) {
1872 PyErr_SetString(PyExc_TypeError,
1873 "T.__new__(S): S is not a type object");
1874 return NULL;
1875 }
1876 subtype = (PyTypeObject *)arg0;
1877 if (!PyType_IsSubtype(subtype, type)) {
1878 PyErr_SetString(PyExc_TypeError,
1879 "T.__new__(S): S is not a subtype of T");
1880 return NULL;
1881 }
1882 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
1883 if (args == NULL)
1884 return NULL;
1885 res = type->tp_new(subtype, args, kwds);
1886 Py_DECREF(args);
1887 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888}
1889
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001890static struct PyMethodDef tp_new_methoddef[] = {
1891 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
1892 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893 {0}
1894};
1895
1896static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001897add_tp_new_wrapper(PyTypeObject *type)
1898{
Guido van Rossumf040ede2001-08-07 16:40:56 +00001899 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001900
Guido van Rossumf040ede2001-08-07 16:40:56 +00001901 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
1902 return 0;
1903 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001904 if (func == NULL)
1905 return -1;
1906 return PyDict_SetItemString(type->tp_defined, "__new__", func);
1907}
1908
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001909/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00001910 dictionary with method descriptors for function slots. For each
1911 function slot (like tp_repr) that's defined in the type, one or
1912 more corresponding descriptors are added in the type's tp_defined
1913 dictionary under the appropriate name (like __repr__). Some
1914 function slots cause more than one descriptor to be added (for
1915 example, the nb_add slot adds both __add__ and __radd__
1916 descriptors) and some function slots compete for the same
1917 descriptor (for example both sq_item and mp_subscript generate a
1918 __getitem__ descriptor). This only adds new descriptors and
1919 doesn't overwrite entries in tp_defined that were previously
1920 defined. The descriptors contain a reference to the C function
1921 they must call, so that it's safe if they are copied into a
1922 subtype's __dict__ and the subtype has a different C function in
1923 its slot -- calling the method defined by the descriptor will call
1924 the C function that was used to create it, rather than the C
1925 function present in the slot when it is called. (This is important
1926 because a subtype may have a C function in the slot that calls the
1927 method from the dictionary, and we want to avoid infinite recursion
1928 here.) */
1929
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001930static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931add_operators(PyTypeObject *type)
1932{
1933 PySequenceMethods *sq;
1934 PyMappingMethods *mp;
1935 PyNumberMethods *nb;
1936
1937#undef ADD
1938#define ADD(SLOT, TABLE) \
1939 if (SLOT) { \
1940 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
1941 return -1; \
1942 }
1943
1944 if ((sq = type->tp_as_sequence) != NULL) {
1945 ADD(sq->sq_length, tab_len);
1946 ADD(sq->sq_concat, tab_concat);
1947 ADD(sq->sq_repeat, tab_mul_int);
1948 ADD(sq->sq_item, tab_getitem_int);
1949 ADD(sq->sq_slice, tab_getslice);
1950 ADD(sq->sq_ass_item, tab_setitem_int);
1951 ADD(sq->sq_ass_slice, tab_setslice);
1952 ADD(sq->sq_contains, tab_contains);
1953 ADD(sq->sq_inplace_concat, tab_iadd);
1954 ADD(sq->sq_inplace_repeat, tab_imul_int);
1955 }
1956
1957 if ((mp = type->tp_as_mapping) != NULL) {
1958 if (sq->sq_length == NULL)
1959 ADD(mp->mp_length, tab_len);
1960 ADD(mp->mp_subscript, tab_getitem);
1961 ADD(mp->mp_ass_subscript, tab_setitem);
1962 }
1963
1964 /* We don't support "old-style numbers" because their binary
1965 operators require that both arguments have the same type;
1966 the wrappers here only work for new-style numbers. */
1967 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
1968 (nb = type->tp_as_number) != NULL) {
1969 ADD(nb->nb_add, tab_add);
1970 ADD(nb->nb_subtract, tab_sub);
1971 ADD(nb->nb_multiply, tab_mul);
1972 ADD(nb->nb_divide, tab_div);
1973 ADD(nb->nb_remainder, tab_mod);
1974 ADD(nb->nb_divmod, tab_divmod);
1975 ADD(nb->nb_power, tab_pow);
1976 ADD(nb->nb_negative, tab_neg);
1977 ADD(nb->nb_positive, tab_pos);
1978 ADD(nb->nb_absolute, tab_abs);
1979 ADD(nb->nb_nonzero, tab_nonzero);
1980 ADD(nb->nb_invert, tab_invert);
1981 ADD(nb->nb_lshift, tab_lshift);
1982 ADD(nb->nb_rshift, tab_rshift);
1983 ADD(nb->nb_and, tab_and);
1984 ADD(nb->nb_xor, tab_xor);
1985 ADD(nb->nb_or, tab_or);
1986 /* We don't support coerce() -- see above comment */
1987 ADD(nb->nb_int, tab_int);
1988 ADD(nb->nb_long, tab_long);
1989 ADD(nb->nb_float, tab_float);
1990 ADD(nb->nb_oct, tab_oct);
1991 ADD(nb->nb_hex, tab_hex);
1992 ADD(nb->nb_inplace_add, tab_iadd);
1993 ADD(nb->nb_inplace_subtract, tab_isub);
1994 ADD(nb->nb_inplace_multiply, tab_imul);
1995 ADD(nb->nb_inplace_divide, tab_idiv);
1996 ADD(nb->nb_inplace_remainder, tab_imod);
1997 ADD(nb->nb_inplace_power, tab_ipow);
1998 ADD(nb->nb_inplace_lshift, tab_ilshift);
1999 ADD(nb->nb_inplace_rshift, tab_irshift);
2000 ADD(nb->nb_inplace_and, tab_iand);
2001 ADD(nb->nb_inplace_xor, tab_ixor);
2002 ADD(nb->nb_inplace_or, tab_ior);
2003 }
2004
2005 ADD(type->tp_getattro, tab_getattr);
2006 ADD(type->tp_setattro, tab_setattr);
2007 ADD(type->tp_compare, tab_cmp);
2008 ADD(type->tp_repr, tab_repr);
2009 ADD(type->tp_hash, tab_hash);
2010 ADD(type->tp_call, tab_call);
2011 ADD(type->tp_str, tab_str);
2012 ADD(type->tp_richcompare, tab_richcmp);
2013 ADD(type->tp_iter, tab_iter);
2014 ADD(type->tp_iternext, tab_next);
2015 ADD(type->tp_descr_get, tab_descr_get);
2016 ADD(type->tp_descr_set, tab_descr_set);
2017 ADD(type->tp_init, tab_init);
2018
Guido van Rossumf040ede2001-08-07 16:40:56 +00002019 if (type->tp_new != NULL) {
2020 if (add_tp_new_wrapper(type) < 0)
2021 return -1;
2022 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002023
2024 return 0;
2025}
2026
Guido van Rossumf040ede2001-08-07 16:40:56 +00002027/* Slot wrappers that call the corresponding __foo__ slot. See comments
2028 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029
Guido van Rossumdc91b992001-08-08 22:26:22 +00002030#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002032FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002034 return PyObject_CallMethod(self, OPSTR, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035}
2036
Guido van Rossumdc91b992001-08-08 22:26:22 +00002037#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002039FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002041 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042}
2043
Guido van Rossumdc91b992001-08-08 22:26:22 +00002044
2045#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002047FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002049 if (self->ob_type->tp_as_number != NULL && \
2050 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2051 PyObject *r; \
2052 r = PyObject_CallMethod( \
2053 self, OPSTR, "O", other); \
2054 if (r != Py_NotImplemented || \
2055 other->ob_type == self->ob_type) \
2056 return r; \
2057 Py_DECREF(r); \
2058 } \
2059 if (other->ob_type->tp_as_number != NULL && \
2060 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2061 return PyObject_CallMethod( \
2062 other, ROPSTR, "O", self); \
2063 } \
2064 Py_INCREF(Py_NotImplemented); \
2065 return Py_NotImplemented; \
2066}
2067
2068#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2069 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2070
2071#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2072static PyObject * \
2073FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2074{ \
2075 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002076}
2077
2078static int
2079slot_sq_length(PyObject *self)
2080{
2081 PyObject *res = PyObject_CallMethod(self, "__len__", "");
2082
2083 if (res == NULL)
2084 return -1;
2085 return (int)PyInt_AsLong(res);
2086}
2087
Guido van Rossumdc91b992001-08-08 22:26:22 +00002088SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2089SLOT1(slot_sq_repeat, "__mul__", int, "i")
2090SLOT1(slot_sq_item, "__getitem__", int, "i")
2091SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092
2093static int
2094slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2095{
2096 PyObject *res;
2097
2098 if (value == NULL)
2099 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2100 else
2101 res = PyObject_CallMethod(self, "__setitem__",
2102 "iO", index, value);
2103 if (res == NULL)
2104 return -1;
2105 Py_DECREF(res);
2106 return 0;
2107}
2108
2109static int
2110slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2111{
2112 PyObject *res;
2113
2114 if (value == NULL)
2115 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2116 else
2117 res = PyObject_CallMethod(self, "__setslice__",
2118 "iiO", i, j, value);
2119 if (res == NULL)
2120 return -1;
2121 Py_DECREF(res);
2122 return 0;
2123}
2124
2125static int
2126slot_sq_contains(PyObject *self, PyObject *value)
2127{
2128 PyObject *res = PyObject_CallMethod(self, "__contains__", "O", value);
2129 int r;
2130
2131 if (res == NULL)
2132 return -1;
2133 r = PyInt_AsLong(res);
2134 Py_DECREF(res);
2135 return r;
2136}
2137
Guido van Rossumdc91b992001-08-08 22:26:22 +00002138SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2139SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140
2141#define slot_mp_length slot_sq_length
2142
Guido van Rossumdc91b992001-08-08 22:26:22 +00002143SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144
2145static int
2146slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2147{
2148 PyObject *res;
2149
2150 if (value == NULL)
2151 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2152 else
2153 res = PyObject_CallMethod(self, "__setitem__",
2154 "OO", key, value);
2155 if (res == NULL)
2156 return -1;
2157 Py_DECREF(res);
2158 return 0;
2159}
2160
Guido van Rossumdc91b992001-08-08 22:26:22 +00002161SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2162SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2163SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2164SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2165SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2166SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2167
2168staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2169
2170SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2171 nb_power, "__pow__", "__rpow__")
2172
2173static PyObject *
2174slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2175{
2176 if (modulus == Py_None)
2177 return slot_nb_power_binary(self, other);
2178 /* Three-arg power doesn't use __rpow__ */
2179 return PyObject_CallMethod(self, "__pow__", "OO", other, modulus);
2180}
2181
2182SLOT0(slot_nb_negative, "__neg__")
2183SLOT0(slot_nb_positive, "__pos__")
2184SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185
2186static int
2187slot_nb_nonzero(PyObject *self)
2188{
2189 PyObject *res = PyObject_CallMethod(self, "__nonzero__", "");
2190
2191 if (res == NULL)
2192 return -1;
2193 return (int)PyInt_AsLong(res);
2194}
2195
Guido van Rossumdc91b992001-08-08 22:26:22 +00002196SLOT0(slot_nb_invert, "__invert__")
2197SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2198SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2199SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2200SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2201SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002203SLOT0(slot_nb_int, "__int__")
2204SLOT0(slot_nb_long, "__long__")
2205SLOT0(slot_nb_float, "__float__")
2206SLOT0(slot_nb_oct, "__oct__")
2207SLOT0(slot_nb_hex, "__hex__")
2208SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2209SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2210SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2211SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2212SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2213SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2214SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2215SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2216SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2217SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2218SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2219SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2220 "__floordiv__", "__rfloordiv__")
2221SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2222SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2223SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224
2225static int
2226slot_tp_compare(PyObject *self, PyObject *other)
2227{
2228 PyObject *res = PyObject_CallMethod(self, "__cmp__", "O", other);
2229 long r;
2230
2231 if (res == NULL)
2232 return -1;
2233 r = PyInt_AsLong(res);
2234 Py_DECREF(res);
2235 return (int)r;
2236}
2237
Guido van Rossumdc91b992001-08-08 22:26:22 +00002238SLOT0(slot_tp_repr, "__repr__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239
2240static long
2241slot_tp_hash(PyObject *self)
2242{
2243 PyObject *res = PyObject_CallMethod(self, "__hash__", "");
2244 long h;
2245
2246 if (res == NULL)
2247 return -1;
2248 h = PyInt_AsLong(res);
2249 if (h == -1 && !PyErr_Occurred())
2250 h = -2;
2251 return h;
2252}
2253
2254static PyObject *
2255slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2256{
2257 PyObject *meth = PyObject_GetAttrString(self, "__call__");
2258 PyObject *res;
2259
2260 if (meth == NULL)
2261 return NULL;
2262 res = PyObject_Call(meth, args, kwds);
2263 Py_DECREF(meth);
2264 return res;
2265}
2266
Guido van Rossumdc91b992001-08-08 22:26:22 +00002267SLOT0(slot_tp_str, "__str__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002268
2269static PyObject *
2270slot_tp_getattro(PyObject *self, PyObject *name)
2271{
2272 PyTypeObject *tp = self->ob_type;
2273 PyObject *dict = NULL;
2274 PyObject *getattr;
2275
2276 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE)
2277 dict = tp->tp_dict;
2278 if (dict == NULL) {
2279 PyErr_Format(PyExc_SystemError,
2280 "'%.100s' type object has no __dict__???",
2281 tp->tp_name);
2282 return NULL;
2283 }
2284 getattr = PyDict_GetItemString(dict, "__getattr__");
2285 if (getattr == NULL) {
2286 PyErr_SetString(PyExc_AttributeError, "__getattr__");
2287 return NULL;
2288 }
2289 return PyObject_CallFunction(getattr, "OO", self, name);
2290}
2291
2292static int
2293slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2294{
2295 PyObject *res;
2296
2297 if (value == NULL)
2298 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2299 else
2300 res = PyObject_CallMethod(self, "__setattr__",
2301 "OO", name, value);
2302 if (res == NULL)
2303 return -1;
2304 Py_DECREF(res);
2305 return 0;
2306}
2307
2308/* Map rich comparison operators to their __xx__ namesakes */
2309static char *name_op[] = {
2310 "__lt__",
2311 "__le__",
2312 "__eq__",
2313 "__ne__",
2314 "__gt__",
2315 "__ge__",
2316};
2317
2318static PyObject *
2319slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2320{
2321 PyObject *meth = PyObject_GetAttrString(self, name_op[op]);
2322 PyObject *res;
2323
2324 if (meth == NULL)
2325 return NULL;
2326 res = PyObject_CallFunction(meth, "O", other);
2327 Py_DECREF(meth);
2328 return res;
2329}
2330
Guido van Rossumdc91b992001-08-08 22:26:22 +00002331SLOT0(slot_tp_iter, "__iter__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332
2333static PyObject *
2334slot_tp_iternext(PyObject *self)
2335{
2336 return PyObject_CallMethod(self, "next", "");
2337}
2338
Guido van Rossumdc91b992001-08-08 22:26:22 +00002339SLOT2(slot_tp_descr_get, "__get__", PyObject *, PyObject *, "OO")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340
2341static int
2342slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2343{
2344 PyObject *res = PyObject_CallMethod(self, "__set__",
2345 "OO", target, value);
2346 if (res == NULL)
2347 return -1;
2348 Py_DECREF(res);
2349 return 0;
2350}
2351
2352static int
2353slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2354{
2355 PyObject *meth = PyObject_GetAttrString(self, "__init__");
2356 PyObject *res;
2357
2358 if (meth == NULL)
2359 return -1;
2360 res = PyObject_Call(meth, args, kwds);
2361 Py_DECREF(meth);
2362 if (res == NULL)
2363 return -1;
2364 Py_DECREF(res);
2365 return 0;
2366}
2367
2368static PyObject *
2369slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2370{
2371 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2372 PyObject *newargs, *x;
2373 int i, n;
2374
2375 if (func == NULL)
2376 return NULL;
2377 assert(PyTuple_Check(args));
2378 n = PyTuple_GET_SIZE(args);
2379 newargs = PyTuple_New(n+1);
2380 if (newargs == NULL)
2381 return NULL;
2382 Py_INCREF(type);
2383 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2384 for (i = 0; i < n; i++) {
2385 x = PyTuple_GET_ITEM(args, i);
2386 Py_INCREF(x);
2387 PyTuple_SET_ITEM(newargs, i+1, x);
2388 }
2389 x = PyObject_Call(func, newargs, kwds);
2390 Py_DECREF(func);
2391 return x;
2392}
2393
Guido van Rossumf040ede2001-08-07 16:40:56 +00002394/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002395 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002396 The dict argument is the dictionary argument passed to type_new(),
2397 which is the local namespace of the class statement, in other
2398 words, it contains the methods. For each special method (like
2399 __repr__) defined in the dictionary, the corresponding function
2400 slot in the type object (like tp_repr) is set to a special function
2401 whose name is 'slot_' followed by the slot name and whose signature
2402 is whatever is required for that slot. These slot functions look
2403 up the corresponding method in the type's dictionary and call it.
2404 The slot functions have to take care of the various peculiarities
2405 of the mapping between slots and special methods, such as mapping
2406 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2407 etc.) or mapping multiple slots to a single method (sq_item,
2408 mp_subscript <--> __getitem__). */
2409
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410static void
2411override_slots(PyTypeObject *type, PyObject *dict)
2412{
2413 PySequenceMethods *sq = type->tp_as_sequence;
2414 PyMappingMethods *mp = type->tp_as_mapping;
2415 PyNumberMethods *nb = type->tp_as_number;
2416
Guido van Rossumdc91b992001-08-08 22:26:22 +00002417#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002418 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002419 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420 }
2421
Guido van Rossumdc91b992001-08-08 22:26:22 +00002422#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002424 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425 }
2426
Guido van Rossumdc91b992001-08-08 22:26:22 +00002427#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002428 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002429 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002430 }
2431
Guido van Rossumdc91b992001-08-08 22:26:22 +00002432#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002434 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435 }
2436
Guido van Rossumdc91b992001-08-08 22:26:22 +00002437 SQSLOT("__len__", sq_length, slot_sq_length);
2438 SQSLOT("__add__", sq_concat, slot_sq_concat);
2439 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
2440 SQSLOT("__getitem__", sq_item, slot_sq_item);
2441 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
2442 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
2443 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
2444 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
2445 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
2446 SQSLOT("__contains__", sq_contains, slot_sq_contains);
2447 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
2448 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449
Guido van Rossumdc91b992001-08-08 22:26:22 +00002450 MPSLOT("__len__", mp_length, slot_mp_length);
2451 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
2452 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
2453 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454
Guido van Rossumdc91b992001-08-08 22:26:22 +00002455 NBSLOT("__add__", nb_add, slot_nb_add);
2456 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
2457 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
2458 NBSLOT("__div__", nb_divide, slot_nb_divide);
2459 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
2460 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
2461 NBSLOT("__pow__", nb_power, slot_nb_power);
2462 NBSLOT("__neg__", nb_negative, slot_nb_negative);
2463 NBSLOT("__pos__", nb_positive, slot_nb_positive);
2464 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
2465 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
2466 NBSLOT("__invert__", nb_invert, slot_nb_invert);
2467 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
2468 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
2469 NBSLOT("__and__", nb_and, slot_nb_and);
2470 NBSLOT("__xor__", nb_xor, slot_nb_xor);
2471 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002472 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002473 NBSLOT("__int__", nb_int, slot_nb_int);
2474 NBSLOT("__long__", nb_long, slot_nb_long);
2475 NBSLOT("__float__", nb_float, slot_nb_float);
2476 NBSLOT("__oct__", nb_oct, slot_nb_oct);
2477 NBSLOT("__hex__", nb_hex, slot_nb_hex);
2478 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
2479 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
2480 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
2481 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
2482 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
2483 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
2484 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
2485 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
2486 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
2487 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
2488 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
2489 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
2490 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
2491 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
2492 slot_nb_inplace_floor_divide);
2493 NBSLOT("__itruediv__", nb_inplace_true_divide,
2494 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002495
2496 if (PyDict_GetItemString(dict, "__str__") ||
2497 PyDict_GetItemString(dict, "__repr__"))
2498 type->tp_print = NULL;
2499
Guido van Rossumdc91b992001-08-08 22:26:22 +00002500 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
2501 TPSLOT("__repr__", tp_repr, slot_tp_repr);
2502 TPSLOT("__hash__", tp_hash, slot_tp_hash);
2503 TPSLOT("__call__", tp_call, slot_tp_call);
2504 TPSLOT("__str__", tp_str, slot_tp_str);
2505 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
2506 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
2507 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
2508 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
2509 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
2510 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
2511 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
2512 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
2513 TPSLOT("__iter__", tp_iter, slot_tp_iter);
2514 TPSLOT("next", tp_iternext, slot_tp_iternext);
2515 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
2516 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
2517 TPSLOT("__init__", tp_init, slot_tp_init);
2518 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519}