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