blob: 926d151cd600f4ed4024efd5b4e1a8684049cfc3 [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
Guido van Rossumd614f972001-08-10 17:39:49 +00001172 if (type->tp_flags & Py_TPFLAGS_READY) {
1173 assert(type->tp_dict != NULL);
1174 return 0;
1175 }
1176 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1177 assert(type->tp_dict == NULL);
1178
1179 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180
1181 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1182 base = type->tp_base;
1183 if (base == NULL && type != &PyBaseObject_Type)
1184 base = type->tp_base = &PyBaseObject_Type;
1185
1186 /* Initialize tp_bases */
1187 bases = type->tp_bases;
1188 if (bases == NULL) {
1189 if (base == NULL)
1190 bases = PyTuple_New(0);
1191 else
1192 bases = Py_BuildValue("(O)", base);
1193 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001194 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 type->tp_bases = bases;
1196 }
1197
1198 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001199 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001200 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001201 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 }
1203
1204 /* Initialize tp_defined */
1205 dict = type->tp_defined;
1206 if (dict == NULL) {
1207 dict = PyDict_New();
1208 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001209 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 type->tp_defined = dict;
1211 }
1212
1213 /* Add type-specific descriptors to tp_defined */
1214 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001215 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 if (type->tp_methods != NULL) {
1217 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001218 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219 }
1220 if (type->tp_members != NULL) {
1221 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001222 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 }
1224 if (type->tp_getset != NULL) {
1225 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001226 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227 }
1228
1229 /* Temporarily make tp_dict the same object as tp_defined.
1230 (This is needed to call mro(), and can stay this way for
1231 dynamic types). */
1232 Py_INCREF(type->tp_defined);
1233 type->tp_dict = type->tp_defined;
1234
1235 /* Calculate method resolution order */
1236 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001237 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 }
1239
1240 /* Initialize tp_dict properly */
1241 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
1242 /* For a static type, tp_dict is the consolidation
1243 of the tp_defined of its bases in MRO. Earlier
1244 bases override later bases; since d.update() works
1245 the other way, we walk the MRO sequence backwards. */
1246 Py_DECREF(type->tp_dict);
1247 type->tp_dict = PyDict_New();
1248 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001249 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250 bases = type->tp_mro;
1251 assert(bases != NULL);
1252 assert(PyTuple_Check(bases));
1253 n = PyTuple_GET_SIZE(bases);
1254 for (i = n; --i >= 0; ) {
1255 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1256 assert(PyType_Check(base));
1257 x = base->tp_defined;
1258 if (x != NULL && PyDict_Update(type->tp_dict, x) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001259 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 }
1261 }
1262
1263 /* Inherit slots from direct base */
1264 if (type->tp_base != NULL)
1265 if (inherit_slots(type, type->tp_base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001266 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267
Guido van Rossumd614f972001-08-10 17:39:49 +00001268 assert(type->tp_dict != NULL);
1269 type->tp_flags =
1270 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001271 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001272
1273 error:
1274 type->tp_flags &= ~Py_TPFLAGS_READYING;
1275 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276}
1277
1278
1279/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1280
1281/* There's a wrapper *function* for each distinct function typedef used
1282 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1283 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1284 Most tables have only one entry; the tables for binary operators have two
1285 entries, one regular and one with reversed arguments. */
1286
1287static PyObject *
1288wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1289{
1290 inquiry func = (inquiry)wrapped;
1291 int res;
1292
1293 if (!PyArg_ParseTuple(args, ""))
1294 return NULL;
1295 res = (*func)(self);
1296 if (res == -1 && PyErr_Occurred())
1297 return NULL;
1298 return PyInt_FromLong((long)res);
1299}
1300
1301static struct wrapperbase tab_len[] = {
1302 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1303 {0}
1304};
1305
1306static PyObject *
1307wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1308{
1309 binaryfunc func = (binaryfunc)wrapped;
1310 PyObject *other;
1311
1312 if (!PyArg_ParseTuple(args, "O", &other))
1313 return NULL;
1314 return (*func)(self, other);
1315}
1316
1317static PyObject *
1318wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1319{
1320 binaryfunc func = (binaryfunc)wrapped;
1321 PyObject *other;
1322
1323 if (!PyArg_ParseTuple(args, "O", &other))
1324 return NULL;
1325 return (*func)(other, self);
1326}
1327
1328#undef BINARY
1329#define BINARY(NAME, OP) \
1330static struct wrapperbase tab_##NAME[] = { \
1331 {"__" #NAME "__", \
1332 (wrapperfunc)wrap_binaryfunc, \
1333 "x.__" #NAME "__(y) <==> " #OP}, \
1334 {"__r" #NAME "__", \
1335 (wrapperfunc)wrap_binaryfunc_r, \
1336 "y.__r" #NAME "__(x) <==> " #OP}, \
1337 {0} \
1338}
1339
1340BINARY(add, "x+y");
1341BINARY(sub, "x-y");
1342BINARY(mul, "x*y");
1343BINARY(div, "x/y");
1344BINARY(mod, "x%y");
1345BINARY(divmod, "divmod(x,y)");
1346BINARY(lshift, "x<<y");
1347BINARY(rshift, "x>>y");
1348BINARY(and, "x&y");
1349BINARY(xor, "x^y");
1350BINARY(or, "x|y");
1351
1352static PyObject *
1353wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1354{
1355 ternaryfunc func = (ternaryfunc)wrapped;
1356 PyObject *other;
1357 PyObject *third = Py_None;
1358
1359 /* Note: This wrapper only works for __pow__() */
1360
1361 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1362 return NULL;
1363 return (*func)(self, other, third);
1364}
1365
1366#undef TERNARY
1367#define TERNARY(NAME, OP) \
1368static struct wrapperbase tab_##NAME[] = { \
1369 {"__" #NAME "__", \
1370 (wrapperfunc)wrap_ternaryfunc, \
1371 "x.__" #NAME "__(y, z) <==> " #OP}, \
1372 {"__r" #NAME "__", \
1373 (wrapperfunc)wrap_ternaryfunc, \
1374 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1375 {0} \
1376}
1377
1378TERNARY(pow, "(x**y) % z");
1379
1380#undef UNARY
1381#define UNARY(NAME, OP) \
1382static struct wrapperbase tab_##NAME[] = { \
1383 {"__" #NAME "__", \
1384 (wrapperfunc)wrap_unaryfunc, \
1385 "x.__" #NAME "__() <==> " #OP}, \
1386 {0} \
1387}
1388
1389static PyObject *
1390wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1391{
1392 unaryfunc func = (unaryfunc)wrapped;
1393
1394 if (!PyArg_ParseTuple(args, ""))
1395 return NULL;
1396 return (*func)(self);
1397}
1398
1399UNARY(neg, "-x");
1400UNARY(pos, "+x");
1401UNARY(abs, "abs(x)");
1402UNARY(nonzero, "x != 0");
1403UNARY(invert, "~x");
1404UNARY(int, "int(x)");
1405UNARY(long, "long(x)");
1406UNARY(float, "float(x)");
1407UNARY(oct, "oct(x)");
1408UNARY(hex, "hex(x)");
1409
1410#undef IBINARY
1411#define IBINARY(NAME, OP) \
1412static struct wrapperbase tab_##NAME[] = { \
1413 {"__" #NAME "__", \
1414 (wrapperfunc)wrap_binaryfunc, \
1415 "x.__" #NAME "__(y) <==> " #OP}, \
1416 {0} \
1417}
1418
1419IBINARY(iadd, "x+=y");
1420IBINARY(isub, "x-=y");
1421IBINARY(imul, "x*=y");
1422IBINARY(idiv, "x/=y");
1423IBINARY(imod, "x%=y");
1424IBINARY(ilshift, "x<<=y");
1425IBINARY(irshift, "x>>=y");
1426IBINARY(iand, "x&=y");
1427IBINARY(ixor, "x^=y");
1428IBINARY(ior, "x|=y");
1429
1430#undef ITERNARY
1431#define ITERNARY(NAME, OP) \
1432static struct wrapperbase tab_##NAME[] = { \
1433 {"__" #NAME "__", \
1434 (wrapperfunc)wrap_ternaryfunc, \
1435 "x.__" #NAME "__(y) <==> " #OP}, \
1436 {0} \
1437}
1438
1439ITERNARY(ipow, "x = (x**y) % z");
1440
1441static struct wrapperbase tab_getitem[] = {
1442 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1443 "x.__getitem__(y) <==> x[y]"},
1444 {0}
1445};
1446
1447static PyObject *
1448wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1449{
1450 intargfunc func = (intargfunc)wrapped;
1451 int i;
1452
1453 if (!PyArg_ParseTuple(args, "i", &i))
1454 return NULL;
1455 return (*func)(self, i);
1456}
1457
1458static struct wrapperbase tab_mul_int[] = {
1459 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1460 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1461 {0}
1462};
1463
1464static struct wrapperbase tab_concat[] = {
1465 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1466 {0}
1467};
1468
1469static struct wrapperbase tab_imul_int[] = {
1470 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1471 {0}
1472};
1473
1474static struct wrapperbase tab_getitem_int[] = {
1475 {"__getitem__", (wrapperfunc)wrap_intargfunc,
1476 "x.__getitem__(i) <==> x[i]"},
1477 {0}
1478};
1479
1480static PyObject *
1481wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1482{
1483 intintargfunc func = (intintargfunc)wrapped;
1484 int i, j;
1485
1486 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1487 return NULL;
1488 return (*func)(self, i, j);
1489}
1490
1491static struct wrapperbase tab_getslice[] = {
1492 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1493 "x.__getslice__(i, j) <==> x[i:j]"},
1494 {0}
1495};
1496
1497static PyObject *
1498wrap_intobjargproc(PyObject *self, PyObject *args, void *wrapped)
1499{
1500 intobjargproc func = (intobjargproc)wrapped;
1501 int i, res;
1502 PyObject *value;
1503
1504 if (!PyArg_ParseTuple(args, "iO", &i, &value))
1505 return NULL;
1506 res = (*func)(self, i, value);
1507 if (res == -1 && PyErr_Occurred())
1508 return NULL;
1509 Py_INCREF(Py_None);
1510 return Py_None;
1511}
1512
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001513static PyObject *
1514wrap_delitem_int(PyObject *self, PyObject *args, void *wrapped)
1515{
1516 intobjargproc func = (intobjargproc)wrapped;
1517 int i, res;
1518
1519 if (!PyArg_ParseTuple(args, "i", &i))
1520 return NULL;
1521 res = (*func)(self, i, NULL);
1522 if (res == -1 && PyErr_Occurred())
1523 return NULL;
1524 Py_INCREF(Py_None);
1525 return Py_None;
1526}
1527
Tim Peters6d6c1a32001-08-02 04:15:00 +00001528static struct wrapperbase tab_setitem_int[] = {
1529 {"__setitem__", (wrapperfunc)wrap_intobjargproc,
1530 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001531 {"__delitem__", (wrapperfunc)wrap_delitem_int,
1532 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533 {0}
1534};
1535
1536static PyObject *
1537wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1538{
1539 intintobjargproc func = (intintobjargproc)wrapped;
1540 int i, j, res;
1541 PyObject *value;
1542
1543 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1544 return NULL;
1545 res = (*func)(self, i, j, value);
1546 if (res == -1 && PyErr_Occurred())
1547 return NULL;
1548 Py_INCREF(Py_None);
1549 return Py_None;
1550}
1551
1552static struct wrapperbase tab_setslice[] = {
1553 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1554 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1555 {0}
1556};
1557
1558/* XXX objobjproc is a misnomer; should be objargpred */
1559static PyObject *
1560wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1561{
1562 objobjproc func = (objobjproc)wrapped;
1563 int res;
1564 PyObject *value;
1565
1566 if (!PyArg_ParseTuple(args, "O", &value))
1567 return NULL;
1568 res = (*func)(self, value);
1569 if (res == -1 && PyErr_Occurred())
1570 return NULL;
1571 return PyInt_FromLong((long)res);
1572}
1573
1574static struct wrapperbase tab_contains[] = {
1575 {"__contains__", (wrapperfunc)wrap_objobjproc,
1576 "x.__contains__(y) <==> y in x"},
1577 {0}
1578};
1579
1580static PyObject *
1581wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1582{
1583 objobjargproc func = (objobjargproc)wrapped;
1584 int res;
1585 PyObject *key, *value;
1586
1587 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1588 return NULL;
1589 res = (*func)(self, key, value);
1590 if (res == -1 && PyErr_Occurred())
1591 return NULL;
1592 Py_INCREF(Py_None);
1593 return Py_None;
1594}
1595
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001596static PyObject *
1597wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1598{
1599 objobjargproc func = (objobjargproc)wrapped;
1600 int res;
1601 PyObject *key;
1602
1603 if (!PyArg_ParseTuple(args, "O", &key))
1604 return NULL;
1605 res = (*func)(self, key, NULL);
1606 if (res == -1 && PyErr_Occurred())
1607 return NULL;
1608 Py_INCREF(Py_None);
1609 return Py_None;
1610}
1611
Tim Peters6d6c1a32001-08-02 04:15:00 +00001612static struct wrapperbase tab_setitem[] = {
1613 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1614 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001615 {"__delitem__", (wrapperfunc)wrap_delitem,
1616 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617 {0}
1618};
1619
1620static PyObject *
1621wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1622{
1623 cmpfunc func = (cmpfunc)wrapped;
1624 int res;
1625 PyObject *other;
1626
1627 if (!PyArg_ParseTuple(args, "O", &other))
1628 return NULL;
1629 res = (*func)(self, other);
1630 if (PyErr_Occurred())
1631 return NULL;
1632 return PyInt_FromLong((long)res);
1633}
1634
1635static struct wrapperbase tab_cmp[] = {
1636 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1637 "x.__cmp__(y) <==> cmp(x,y)"},
1638 {0}
1639};
1640
1641static struct wrapperbase tab_repr[] = {
1642 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1643 "x.__repr__() <==> repr(x)"},
1644 {0}
1645};
1646
1647static struct wrapperbase tab_getattr[] = {
1648 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1649 "x.__getattr__('name') <==> x.name"},
1650 {0}
1651};
1652
1653static PyObject *
1654wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1655{
1656 setattrofunc func = (setattrofunc)wrapped;
1657 int res;
1658 PyObject *name, *value;
1659
1660 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1661 return NULL;
1662 res = (*func)(self, name, value);
1663 if (res < 0)
1664 return NULL;
1665 Py_INCREF(Py_None);
1666 return Py_None;
1667}
1668
1669static PyObject *
1670wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1671{
1672 setattrofunc func = (setattrofunc)wrapped;
1673 int res;
1674 PyObject *name;
1675
1676 if (!PyArg_ParseTuple(args, "O", &name))
1677 return NULL;
1678 res = (*func)(self, name, NULL);
1679 if (res < 0)
1680 return NULL;
1681 Py_INCREF(Py_None);
1682 return Py_None;
1683}
1684
1685static struct wrapperbase tab_setattr[] = {
1686 {"__setattr__", (wrapperfunc)wrap_setattr,
1687 "x.__setattr__('name', value) <==> x.name = value"},
1688 {"__delattr__", (wrapperfunc)wrap_delattr,
1689 "x.__delattr__('name') <==> del x.name"},
1690 {0}
1691};
1692
1693static PyObject *
1694wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1695{
1696 hashfunc func = (hashfunc)wrapped;
1697 long res;
1698
1699 if (!PyArg_ParseTuple(args, ""))
1700 return NULL;
1701 res = (*func)(self);
1702 if (res == -1 && PyErr_Occurred())
1703 return NULL;
1704 return PyInt_FromLong(res);
1705}
1706
1707static struct wrapperbase tab_hash[] = {
1708 {"__hash__", (wrapperfunc)wrap_hashfunc,
1709 "x.__hash__() <==> hash(x)"},
1710 {0}
1711};
1712
1713static PyObject *
1714wrap_call(PyObject *self, PyObject *args, void *wrapped)
1715{
1716 ternaryfunc func = (ternaryfunc)wrapped;
1717
1718 /* XXX What about keyword arguments? */
1719 return (*func)(self, args, NULL);
1720}
1721
1722static struct wrapperbase tab_call[] = {
1723 {"__call__", (wrapperfunc)wrap_call,
1724 "x.__call__(...) <==> x(...)"},
1725 {0}
1726};
1727
1728static struct wrapperbase tab_str[] = {
1729 {"__str__", (wrapperfunc)wrap_unaryfunc,
1730 "x.__str__() <==> str(x)"},
1731 {0}
1732};
1733
1734static PyObject *
1735wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1736{
1737 richcmpfunc func = (richcmpfunc)wrapped;
1738 PyObject *other;
1739
1740 if (!PyArg_ParseTuple(args, "O", &other))
1741 return NULL;
1742 return (*func)(self, other, op);
1743}
1744
1745#undef RICHCMP_WRAPPER
1746#define RICHCMP_WRAPPER(NAME, OP) \
1747static PyObject * \
1748richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1749{ \
1750 return wrap_richcmpfunc(self, args, wrapped, OP); \
1751}
1752
Jack Jansen8e938b42001-08-08 15:29:49 +00001753RICHCMP_WRAPPER(lt, Py_LT)
1754RICHCMP_WRAPPER(le, Py_LE)
1755RICHCMP_WRAPPER(eq, Py_EQ)
1756RICHCMP_WRAPPER(ne, Py_NE)
1757RICHCMP_WRAPPER(gt, Py_GT)
1758RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759
1760#undef RICHCMP_ENTRY
1761#define RICHCMP_ENTRY(NAME, EXPR) \
1762 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1763 "x.__" #NAME "__(y) <==> " EXPR}
1764
1765static struct wrapperbase tab_richcmp[] = {
1766 RICHCMP_ENTRY(lt, "x<y"),
1767 RICHCMP_ENTRY(le, "x<=y"),
1768 RICHCMP_ENTRY(eq, "x==y"),
1769 RICHCMP_ENTRY(ne, "x!=y"),
1770 RICHCMP_ENTRY(gt, "x>y"),
1771 RICHCMP_ENTRY(ge, "x>=y"),
1772 {0}
1773};
1774
1775static struct wrapperbase tab_iter[] = {
1776 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
1777 {0}
1778};
1779
1780static PyObject *
1781wrap_next(PyObject *self, PyObject *args, void *wrapped)
1782{
1783 unaryfunc func = (unaryfunc)wrapped;
1784 PyObject *res;
1785
1786 if (!PyArg_ParseTuple(args, ""))
1787 return NULL;
1788 res = (*func)(self);
1789 if (res == NULL && !PyErr_Occurred())
1790 PyErr_SetNone(PyExc_StopIteration);
1791 return res;
1792}
1793
1794static struct wrapperbase tab_next[] = {
1795 {"next", (wrapperfunc)wrap_next,
1796 "x.next() -> the next value, or raise StopIteration"},
1797 {0}
1798};
1799
1800static PyObject *
1801wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
1802{
1803 descrgetfunc func = (descrgetfunc)wrapped;
1804 PyObject *obj;
1805 PyObject *type = NULL;
1806
1807 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
1808 return NULL;
1809 if (type == NULL)
1810 type = (PyObject *)obj->ob_type;
1811 return (*func)(self, obj, type);
1812}
1813
1814static struct wrapperbase tab_descr_get[] = {
1815 {"__get__", (wrapperfunc)wrap_descr_get,
1816 "descr.__get__(obj, type) -> value"},
1817 {0}
1818};
1819
1820static PyObject *
1821wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
1822{
1823 descrsetfunc func = (descrsetfunc)wrapped;
1824 PyObject *obj, *value;
1825 int ret;
1826
1827 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
1828 return NULL;
1829 ret = (*func)(self, obj, value);
1830 if (ret < 0)
1831 return NULL;
1832 Py_INCREF(Py_None);
1833 return Py_None;
1834}
1835
1836static struct wrapperbase tab_descr_set[] = {
1837 {"__set__", (wrapperfunc)wrap_descrsetfunc,
1838 "descr.__set__(obj, value)"},
1839 {0}
1840};
1841
1842static PyObject *
1843wrap_init(PyObject *self, PyObject *args, void *wrapped)
1844{
1845 initproc func = (initproc)wrapped;
1846
1847 /* XXX What about keyword arguments? */
1848 if (func(self, args, NULL) < 0)
1849 return NULL;
1850 Py_INCREF(Py_None);
1851 return Py_None;
1852}
1853
1854static struct wrapperbase tab_init[] = {
1855 {"__init__", (wrapperfunc)wrap_init,
1856 "x.__init__(...) initializes x; "
1857 "see x.__type__.__doc__ for signature"},
1858 {0}
1859};
1860
1861static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001862tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001863{
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001864 PyTypeObject *type, *subtype;
1865 PyObject *arg0, *res;
1866
1867 if (self == NULL || !PyType_Check(self))
1868 Py_FatalError("__new__() called with non-type 'self'");
1869 type = (PyTypeObject *)self;
1870 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
1871 PyErr_SetString(PyExc_TypeError,
1872 "T.__new__(): not enough arguments");
1873 return NULL;
1874 }
1875 arg0 = PyTuple_GET_ITEM(args, 0);
1876 if (!PyType_Check(arg0)) {
1877 PyErr_SetString(PyExc_TypeError,
1878 "T.__new__(S): S is not a type object");
1879 return NULL;
1880 }
1881 subtype = (PyTypeObject *)arg0;
1882 if (!PyType_IsSubtype(subtype, type)) {
1883 PyErr_SetString(PyExc_TypeError,
1884 "T.__new__(S): S is not a subtype of T");
1885 return NULL;
1886 }
1887 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
1888 if (args == NULL)
1889 return NULL;
1890 res = type->tp_new(subtype, args, kwds);
1891 Py_DECREF(args);
1892 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893}
1894
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001895static struct PyMethodDef tp_new_methoddef[] = {
1896 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
1897 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898 {0}
1899};
1900
1901static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001902add_tp_new_wrapper(PyTypeObject *type)
1903{
Guido van Rossumf040ede2001-08-07 16:40:56 +00001904 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001905
Guido van Rossumf040ede2001-08-07 16:40:56 +00001906 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
1907 return 0;
1908 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001909 if (func == NULL)
1910 return -1;
1911 return PyDict_SetItemString(type->tp_defined, "__new__", func);
1912}
1913
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001914/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00001915 dictionary with method descriptors for function slots. For each
1916 function slot (like tp_repr) that's defined in the type, one or
1917 more corresponding descriptors are added in the type's tp_defined
1918 dictionary under the appropriate name (like __repr__). Some
1919 function slots cause more than one descriptor to be added (for
1920 example, the nb_add slot adds both __add__ and __radd__
1921 descriptors) and some function slots compete for the same
1922 descriptor (for example both sq_item and mp_subscript generate a
1923 __getitem__ descriptor). This only adds new descriptors and
1924 doesn't overwrite entries in tp_defined that were previously
1925 defined. The descriptors contain a reference to the C function
1926 they must call, so that it's safe if they are copied into a
1927 subtype's __dict__ and the subtype has a different C function in
1928 its slot -- calling the method defined by the descriptor will call
1929 the C function that was used to create it, rather than the C
1930 function present in the slot when it is called. (This is important
1931 because a subtype may have a C function in the slot that calls the
1932 method from the dictionary, and we want to avoid infinite recursion
1933 here.) */
1934
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001935static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936add_operators(PyTypeObject *type)
1937{
1938 PySequenceMethods *sq;
1939 PyMappingMethods *mp;
1940 PyNumberMethods *nb;
1941
1942#undef ADD
1943#define ADD(SLOT, TABLE) \
1944 if (SLOT) { \
1945 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
1946 return -1; \
1947 }
1948
1949 if ((sq = type->tp_as_sequence) != NULL) {
1950 ADD(sq->sq_length, tab_len);
1951 ADD(sq->sq_concat, tab_concat);
1952 ADD(sq->sq_repeat, tab_mul_int);
1953 ADD(sq->sq_item, tab_getitem_int);
1954 ADD(sq->sq_slice, tab_getslice);
1955 ADD(sq->sq_ass_item, tab_setitem_int);
1956 ADD(sq->sq_ass_slice, tab_setslice);
1957 ADD(sq->sq_contains, tab_contains);
1958 ADD(sq->sq_inplace_concat, tab_iadd);
1959 ADD(sq->sq_inplace_repeat, tab_imul_int);
1960 }
1961
1962 if ((mp = type->tp_as_mapping) != NULL) {
1963 if (sq->sq_length == NULL)
1964 ADD(mp->mp_length, tab_len);
1965 ADD(mp->mp_subscript, tab_getitem);
1966 ADD(mp->mp_ass_subscript, tab_setitem);
1967 }
1968
1969 /* We don't support "old-style numbers" because their binary
1970 operators require that both arguments have the same type;
1971 the wrappers here only work for new-style numbers. */
1972 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
1973 (nb = type->tp_as_number) != NULL) {
1974 ADD(nb->nb_add, tab_add);
1975 ADD(nb->nb_subtract, tab_sub);
1976 ADD(nb->nb_multiply, tab_mul);
1977 ADD(nb->nb_divide, tab_div);
1978 ADD(nb->nb_remainder, tab_mod);
1979 ADD(nb->nb_divmod, tab_divmod);
1980 ADD(nb->nb_power, tab_pow);
1981 ADD(nb->nb_negative, tab_neg);
1982 ADD(nb->nb_positive, tab_pos);
1983 ADD(nb->nb_absolute, tab_abs);
1984 ADD(nb->nb_nonzero, tab_nonzero);
1985 ADD(nb->nb_invert, tab_invert);
1986 ADD(nb->nb_lshift, tab_lshift);
1987 ADD(nb->nb_rshift, tab_rshift);
1988 ADD(nb->nb_and, tab_and);
1989 ADD(nb->nb_xor, tab_xor);
1990 ADD(nb->nb_or, tab_or);
1991 /* We don't support coerce() -- see above comment */
1992 ADD(nb->nb_int, tab_int);
1993 ADD(nb->nb_long, tab_long);
1994 ADD(nb->nb_float, tab_float);
1995 ADD(nb->nb_oct, tab_oct);
1996 ADD(nb->nb_hex, tab_hex);
1997 ADD(nb->nb_inplace_add, tab_iadd);
1998 ADD(nb->nb_inplace_subtract, tab_isub);
1999 ADD(nb->nb_inplace_multiply, tab_imul);
2000 ADD(nb->nb_inplace_divide, tab_idiv);
2001 ADD(nb->nb_inplace_remainder, tab_imod);
2002 ADD(nb->nb_inplace_power, tab_ipow);
2003 ADD(nb->nb_inplace_lshift, tab_ilshift);
2004 ADD(nb->nb_inplace_rshift, tab_irshift);
2005 ADD(nb->nb_inplace_and, tab_iand);
2006 ADD(nb->nb_inplace_xor, tab_ixor);
2007 ADD(nb->nb_inplace_or, tab_ior);
2008 }
2009
2010 ADD(type->tp_getattro, tab_getattr);
2011 ADD(type->tp_setattro, tab_setattr);
2012 ADD(type->tp_compare, tab_cmp);
2013 ADD(type->tp_repr, tab_repr);
2014 ADD(type->tp_hash, tab_hash);
2015 ADD(type->tp_call, tab_call);
2016 ADD(type->tp_str, tab_str);
2017 ADD(type->tp_richcompare, tab_richcmp);
2018 ADD(type->tp_iter, tab_iter);
2019 ADD(type->tp_iternext, tab_next);
2020 ADD(type->tp_descr_get, tab_descr_get);
2021 ADD(type->tp_descr_set, tab_descr_set);
2022 ADD(type->tp_init, tab_init);
2023
Guido van Rossumf040ede2001-08-07 16:40:56 +00002024 if (type->tp_new != NULL) {
2025 if (add_tp_new_wrapper(type) < 0)
2026 return -1;
2027 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002028
2029 return 0;
2030}
2031
Guido van Rossumf040ede2001-08-07 16:40:56 +00002032/* Slot wrappers that call the corresponding __foo__ slot. See comments
2033 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034
Guido van Rossumdc91b992001-08-08 22:26:22 +00002035#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002037FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002039 return PyObject_CallMethod(self, OPSTR, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040}
2041
Guido van Rossumdc91b992001-08-08 22:26:22 +00002042#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002044FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002046 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047}
2048
Guido van Rossumdc91b992001-08-08 22:26:22 +00002049
2050#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002052FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002054 if (self->ob_type->tp_as_number != NULL && \
2055 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2056 PyObject *r; \
2057 r = PyObject_CallMethod( \
2058 self, OPSTR, "O", other); \
2059 if (r != Py_NotImplemented || \
2060 other->ob_type == self->ob_type) \
2061 return r; \
2062 Py_DECREF(r); \
2063 } \
2064 if (other->ob_type->tp_as_number != NULL && \
2065 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2066 return PyObject_CallMethod( \
2067 other, ROPSTR, "O", self); \
2068 } \
2069 Py_INCREF(Py_NotImplemented); \
2070 return Py_NotImplemented; \
2071}
2072
2073#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2074 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2075
2076#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2077static PyObject * \
2078FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2079{ \
2080 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002081}
2082
2083static int
2084slot_sq_length(PyObject *self)
2085{
2086 PyObject *res = PyObject_CallMethod(self, "__len__", "");
2087
2088 if (res == NULL)
2089 return -1;
2090 return (int)PyInt_AsLong(res);
2091}
2092
Guido van Rossumdc91b992001-08-08 22:26:22 +00002093SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2094SLOT1(slot_sq_repeat, "__mul__", int, "i")
2095SLOT1(slot_sq_item, "__getitem__", int, "i")
2096SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097
2098static int
2099slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2100{
2101 PyObject *res;
2102
2103 if (value == NULL)
2104 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2105 else
2106 res = PyObject_CallMethod(self, "__setitem__",
2107 "iO", index, value);
2108 if (res == NULL)
2109 return -1;
2110 Py_DECREF(res);
2111 return 0;
2112}
2113
2114static int
2115slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2116{
2117 PyObject *res;
2118
2119 if (value == NULL)
2120 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2121 else
2122 res = PyObject_CallMethod(self, "__setslice__",
2123 "iiO", i, j, value);
2124 if (res == NULL)
2125 return -1;
2126 Py_DECREF(res);
2127 return 0;
2128}
2129
2130static int
2131slot_sq_contains(PyObject *self, PyObject *value)
2132{
2133 PyObject *res = PyObject_CallMethod(self, "__contains__", "O", value);
2134 int r;
2135
2136 if (res == NULL)
2137 return -1;
2138 r = PyInt_AsLong(res);
2139 Py_DECREF(res);
2140 return r;
2141}
2142
Guido van Rossumdc91b992001-08-08 22:26:22 +00002143SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2144SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002145
2146#define slot_mp_length slot_sq_length
2147
Guido van Rossumdc91b992001-08-08 22:26:22 +00002148SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149
2150static int
2151slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2152{
2153 PyObject *res;
2154
2155 if (value == NULL)
2156 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2157 else
2158 res = PyObject_CallMethod(self, "__setitem__",
2159 "OO", key, value);
2160 if (res == NULL)
2161 return -1;
2162 Py_DECREF(res);
2163 return 0;
2164}
2165
Guido van Rossumdc91b992001-08-08 22:26:22 +00002166SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2167SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2168SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2169SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2170SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2171SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2172
2173staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2174
2175SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2176 nb_power, "__pow__", "__rpow__")
2177
2178static PyObject *
2179slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2180{
2181 if (modulus == Py_None)
2182 return slot_nb_power_binary(self, other);
2183 /* Three-arg power doesn't use __rpow__ */
2184 return PyObject_CallMethod(self, "__pow__", "OO", other, modulus);
2185}
2186
2187SLOT0(slot_nb_negative, "__neg__")
2188SLOT0(slot_nb_positive, "__pos__")
2189SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190
2191static int
2192slot_nb_nonzero(PyObject *self)
2193{
2194 PyObject *res = PyObject_CallMethod(self, "__nonzero__", "");
2195
2196 if (res == NULL)
2197 return -1;
2198 return (int)PyInt_AsLong(res);
2199}
2200
Guido van Rossumdc91b992001-08-08 22:26:22 +00002201SLOT0(slot_nb_invert, "__invert__")
2202SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2203SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2204SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2205SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2206SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002208SLOT0(slot_nb_int, "__int__")
2209SLOT0(slot_nb_long, "__long__")
2210SLOT0(slot_nb_float, "__float__")
2211SLOT0(slot_nb_oct, "__oct__")
2212SLOT0(slot_nb_hex, "__hex__")
2213SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2214SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2215SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2216SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2217SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2218SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2219SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2220SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2221SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2222SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2223SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2224SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2225 "__floordiv__", "__rfloordiv__")
2226SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2227SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2228SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229
2230static int
2231slot_tp_compare(PyObject *self, PyObject *other)
2232{
2233 PyObject *res = PyObject_CallMethod(self, "__cmp__", "O", other);
2234 long r;
2235
2236 if (res == NULL)
2237 return -1;
2238 r = PyInt_AsLong(res);
2239 Py_DECREF(res);
2240 return (int)r;
2241}
2242
Guido van Rossumdc91b992001-08-08 22:26:22 +00002243SLOT0(slot_tp_repr, "__repr__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244
2245static long
2246slot_tp_hash(PyObject *self)
2247{
2248 PyObject *res = PyObject_CallMethod(self, "__hash__", "");
2249 long h;
2250
2251 if (res == NULL)
2252 return -1;
2253 h = PyInt_AsLong(res);
2254 if (h == -1 && !PyErr_Occurred())
2255 h = -2;
2256 return h;
2257}
2258
2259static PyObject *
2260slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2261{
2262 PyObject *meth = PyObject_GetAttrString(self, "__call__");
2263 PyObject *res;
2264
2265 if (meth == NULL)
2266 return NULL;
2267 res = PyObject_Call(meth, args, kwds);
2268 Py_DECREF(meth);
2269 return res;
2270}
2271
Guido van Rossumdc91b992001-08-08 22:26:22 +00002272SLOT0(slot_tp_str, "__str__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002273
2274static PyObject *
2275slot_tp_getattro(PyObject *self, PyObject *name)
2276{
2277 PyTypeObject *tp = self->ob_type;
2278 PyObject *dict = NULL;
2279 PyObject *getattr;
2280
2281 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE)
2282 dict = tp->tp_dict;
2283 if (dict == NULL) {
2284 PyErr_Format(PyExc_SystemError,
2285 "'%.100s' type object has no __dict__???",
2286 tp->tp_name);
2287 return NULL;
2288 }
2289 getattr = PyDict_GetItemString(dict, "__getattr__");
2290 if (getattr == NULL) {
2291 PyErr_SetString(PyExc_AttributeError, "__getattr__");
2292 return NULL;
2293 }
2294 return PyObject_CallFunction(getattr, "OO", self, name);
2295}
2296
2297static int
2298slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2299{
2300 PyObject *res;
2301
2302 if (value == NULL)
2303 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2304 else
2305 res = PyObject_CallMethod(self, "__setattr__",
2306 "OO", name, value);
2307 if (res == NULL)
2308 return -1;
2309 Py_DECREF(res);
2310 return 0;
2311}
2312
2313/* Map rich comparison operators to their __xx__ namesakes */
2314static char *name_op[] = {
2315 "__lt__",
2316 "__le__",
2317 "__eq__",
2318 "__ne__",
2319 "__gt__",
2320 "__ge__",
2321};
2322
2323static PyObject *
2324slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2325{
2326 PyObject *meth = PyObject_GetAttrString(self, name_op[op]);
2327 PyObject *res;
2328
2329 if (meth == NULL)
2330 return NULL;
2331 res = PyObject_CallFunction(meth, "O", other);
2332 Py_DECREF(meth);
2333 return res;
2334}
2335
Guido van Rossumdc91b992001-08-08 22:26:22 +00002336SLOT0(slot_tp_iter, "__iter__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002337
2338static PyObject *
2339slot_tp_iternext(PyObject *self)
2340{
2341 return PyObject_CallMethod(self, "next", "");
2342}
2343
Guido van Rossumdc91b992001-08-08 22:26:22 +00002344SLOT2(slot_tp_descr_get, "__get__", PyObject *, PyObject *, "OO")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345
2346static int
2347slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2348{
2349 PyObject *res = PyObject_CallMethod(self, "__set__",
2350 "OO", target, value);
2351 if (res == NULL)
2352 return -1;
2353 Py_DECREF(res);
2354 return 0;
2355}
2356
2357static int
2358slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2359{
2360 PyObject *meth = PyObject_GetAttrString(self, "__init__");
2361 PyObject *res;
2362
2363 if (meth == NULL)
2364 return -1;
2365 res = PyObject_Call(meth, args, kwds);
2366 Py_DECREF(meth);
2367 if (res == NULL)
2368 return -1;
2369 Py_DECREF(res);
2370 return 0;
2371}
2372
2373static PyObject *
2374slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2375{
2376 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2377 PyObject *newargs, *x;
2378 int i, n;
2379
2380 if (func == NULL)
2381 return NULL;
2382 assert(PyTuple_Check(args));
2383 n = PyTuple_GET_SIZE(args);
2384 newargs = PyTuple_New(n+1);
2385 if (newargs == NULL)
2386 return NULL;
2387 Py_INCREF(type);
2388 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2389 for (i = 0; i < n; i++) {
2390 x = PyTuple_GET_ITEM(args, i);
2391 Py_INCREF(x);
2392 PyTuple_SET_ITEM(newargs, i+1, x);
2393 }
2394 x = PyObject_Call(func, newargs, kwds);
2395 Py_DECREF(func);
2396 return x;
2397}
2398
Guido van Rossumf040ede2001-08-07 16:40:56 +00002399/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002400 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002401 The dict argument is the dictionary argument passed to type_new(),
2402 which is the local namespace of the class statement, in other
2403 words, it contains the methods. For each special method (like
2404 __repr__) defined in the dictionary, the corresponding function
2405 slot in the type object (like tp_repr) is set to a special function
2406 whose name is 'slot_' followed by the slot name and whose signature
2407 is whatever is required for that slot. These slot functions look
2408 up the corresponding method in the type's dictionary and call it.
2409 The slot functions have to take care of the various peculiarities
2410 of the mapping between slots and special methods, such as mapping
2411 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2412 etc.) or mapping multiple slots to a single method (sq_item,
2413 mp_subscript <--> __getitem__). */
2414
Tim Peters6d6c1a32001-08-02 04:15:00 +00002415static void
2416override_slots(PyTypeObject *type, PyObject *dict)
2417{
2418 PySequenceMethods *sq = type->tp_as_sequence;
2419 PyMappingMethods *mp = type->tp_as_mapping;
2420 PyNumberMethods *nb = type->tp_as_number;
2421
Guido van Rossumdc91b992001-08-08 22:26:22 +00002422#define SQSLOT(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 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425 }
2426
Guido van Rossumdc91b992001-08-08 22:26:22 +00002427#define MPSLOT(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 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002430 }
2431
Guido van Rossumdc91b992001-08-08 22:26:22 +00002432#define NBSLOT(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 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435 }
2436
Guido van Rossumdc91b992001-08-08 22:26:22 +00002437#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002439 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002440 }
2441
Guido van Rossumdc91b992001-08-08 22:26:22 +00002442 SQSLOT("__len__", sq_length, slot_sq_length);
2443 SQSLOT("__add__", sq_concat, slot_sq_concat);
2444 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
2445 SQSLOT("__getitem__", sq_item, slot_sq_item);
2446 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
2447 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
2448 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
2449 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
2450 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
2451 SQSLOT("__contains__", sq_contains, slot_sq_contains);
2452 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
2453 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454
Guido van Rossumdc91b992001-08-08 22:26:22 +00002455 MPSLOT("__len__", mp_length, slot_mp_length);
2456 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
2457 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
2458 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459
Guido van Rossumdc91b992001-08-08 22:26:22 +00002460 NBSLOT("__add__", nb_add, slot_nb_add);
2461 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
2462 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
2463 NBSLOT("__div__", nb_divide, slot_nb_divide);
2464 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
2465 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
2466 NBSLOT("__pow__", nb_power, slot_nb_power);
2467 NBSLOT("__neg__", nb_negative, slot_nb_negative);
2468 NBSLOT("__pos__", nb_positive, slot_nb_positive);
2469 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
2470 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
2471 NBSLOT("__invert__", nb_invert, slot_nb_invert);
2472 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
2473 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
2474 NBSLOT("__and__", nb_and, slot_nb_and);
2475 NBSLOT("__xor__", nb_xor, slot_nb_xor);
2476 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002478 NBSLOT("__int__", nb_int, slot_nb_int);
2479 NBSLOT("__long__", nb_long, slot_nb_long);
2480 NBSLOT("__float__", nb_float, slot_nb_float);
2481 NBSLOT("__oct__", nb_oct, slot_nb_oct);
2482 NBSLOT("__hex__", nb_hex, slot_nb_hex);
2483 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
2484 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
2485 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
2486 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
2487 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
2488 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
2489 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
2490 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
2491 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
2492 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
2493 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
2494 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
2495 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
2496 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
2497 slot_nb_inplace_floor_divide);
2498 NBSLOT("__itruediv__", nb_inplace_true_divide,
2499 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500
2501 if (PyDict_GetItemString(dict, "__str__") ||
2502 PyDict_GetItemString(dict, "__repr__"))
2503 type->tp_print = NULL;
2504
Guido van Rossumdc91b992001-08-08 22:26:22 +00002505 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
2506 TPSLOT("__repr__", tp_repr, slot_tp_repr);
2507 TPSLOT("__hash__", tp_hash, slot_tp_hash);
2508 TPSLOT("__call__", tp_call, slot_tp_call);
2509 TPSLOT("__str__", tp_str, slot_tp_str);
2510 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
2511 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
2512 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
2513 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
2514 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
2515 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
2516 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
2517 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
2518 TPSLOT("__iter__", tp_iter, slot_tp_iter);
2519 TPSLOT("next", tp_iternext, slot_tp_iternext);
2520 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
2521 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
2522 TPSLOT("__init__", tp_init, slot_tp_init);
2523 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524}