blob: 098d591975e26fb9e5ada757038ce0a4a214b1f9 [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 +00007static struct memberlist type_members[] = {
8 {"__name__", T_STRING, offsetof(PyTypeObject, tp_name), READONLY},
9 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
12 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
13 {"__weaklistoffset__", T_LONG,
14 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
15 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
16 {"__dictoffset__", T_LONG,
17 offsetof(PyTypeObject, tp_dictoffset), READONLY},
18 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
19 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
20 {0}
21};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000022
Guido van Rossumc0b618a1997-05-02 03:12:38 +000023static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000024type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000025{
Tim Peters6d6c1a32001-08-02 04:15:00 +000026 return PyString_FromString("__builtin__");
27}
28
29static PyObject *
30type_dict(PyTypeObject *type, void *context)
31{
32 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000033 Py_INCREF(Py_None);
34 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000035 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000036 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
37 Py_INCREF(type->tp_dict);
38 return type->tp_dict;
39 }
40 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000041}
42
Tim Peters6d6c1a32001-08-02 04:15:00 +000043static PyObject *
44type_defined(PyTypeObject *type, void *context)
45{
46 if (type->tp_defined == NULL) {
47 Py_INCREF(Py_None);
48 return Py_None;
49 }
50 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
51 Py_INCREF(type->tp_defined);
52 return type->tp_defined;
53 }
54 return PyDictProxy_New(type->tp_defined);
55}
56
57static PyObject *
58type_dynamic(PyTypeObject *type, void *context)
59{
60 PyObject *res;
61
62 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
63 Py_INCREF(res);
64 return res;
65}
66
67struct getsetlist type_getsets[] = {
68 {"__module__", (getter)type_module, NULL, NULL},
69 {"__dict__", (getter)type_dict, NULL, NULL},
70 {"__defined__", (getter)type_defined, NULL, NULL},
71 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
72 {0}
73};
74
Martin v. Löwis0163d6d2001-06-09 07:34:05 +000075static int
76type_compare(PyObject *v, PyObject *w)
77{
78 /* This is called with type objects only. So we
79 can just compare the addresses. */
80 Py_uintptr_t vv = (Py_uintptr_t)v;
81 Py_uintptr_t ww = (Py_uintptr_t)w;
82 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
83}
84
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000086type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000087{
88 char buf[100];
Tim Peters6d6c1a32001-08-02 04:15:00 +000089 sprintf(buf, "<type '%.80s'>", type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000090 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091}
92
Tim Peters6d6c1a32001-08-02 04:15:00 +000093static PyObject *
94type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
95{
96 PyObject *obj;
97
98 if (type->tp_new == NULL) {
99 PyErr_Format(PyExc_TypeError,
100 "cannot create '%.100s' instances",
101 type->tp_name);
102 return NULL;
103 }
104
105 obj = type->tp_new(type, args, NULL);
106 if (obj != NULL) {
107 type = obj->ob_type;
108 if (type->tp_init != NULL &&
109 type->tp_init(obj, args, kwds) < 0) {
110 Py_DECREF(obj);
111 obj = NULL;
112 }
113 }
114 return obj;
115}
116
117PyObject *
118PyType_GenericAlloc(PyTypeObject *type, int nitems)
119{
120 int size;
121 void *mem;
122 PyObject *obj;
123
124 /* Inline PyObject_New() so we can zero the memory */
125 size = _PyObject_VAR_SIZE(type, nitems);
126 mem = PyObject_MALLOC(size);
127 if (mem == NULL)
128 return PyErr_NoMemory();
129 memset(mem, '\0', size);
130 if (PyType_IS_GC(type))
131 obj = PyObject_FROM_GC(mem);
132 else
133 obj = (PyObject *)mem;
134 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
135 Py_INCREF(type);
136 if (type->tp_itemsize == 0)
137 PyObject_INIT(obj, type);
138 else
139 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
140 if (PyType_IS_GC(type))
141 PyObject_GC_Init(obj);
142 return obj;
143}
144
145PyObject *
146PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
147{
148 return type->tp_alloc(type, 0);
149}
150
151/* Helper for subtyping */
152
153static void
154subtype_dealloc(PyObject *self)
155{
156 int dictoffset = self->ob_type->tp_dictoffset;
157 PyTypeObject *type, *base;
158 destructor f;
159
160 /* This exists so we can DECREF self->ob_type */
161
162 /* Find the nearest base with a different tp_dealloc */
163 type = self->ob_type;
164 base = type->tp_base;
165 while ((f = base->tp_dealloc) == subtype_dealloc) {
166 base = base->tp_base;
167 assert(base);
168 }
169
170 /* If we added a dict, DECREF it */
171 if (dictoffset && !base->tp_dictoffset) {
172 PyObject **dictptr = (PyObject **) ((char *)self + dictoffset);
173 PyObject *dict = *dictptr;
174 if (dict != NULL) {
175 Py_DECREF(dict);
176 *dictptr = NULL;
177 }
178 }
179
180 /* Finalize GC if the base doesn't do GC and we do */
181 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
182 PyObject_GC_Fini(self);
183
184 /* Call the base tp_dealloc() */
185 assert(f);
186 f(self);
187
188 /* Can't reference self beyond this point */
189 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
190 Py_DECREF(type);
191 }
192}
193
194staticforward void override_slots(PyTypeObject *type, PyObject *dict);
195staticforward PyTypeObject *solid_base(PyTypeObject *type);
196
197typedef struct {
198 PyTypeObject type;
199 PyNumberMethods as_number;
200 PySequenceMethods as_sequence;
201 PyMappingMethods as_mapping;
202 PyBufferProcs as_buffer;
203 PyObject *name, *slots;
204 struct memberlist members[1];
205} etype;
206
207/* type test with subclassing support */
208
209int
210PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
211{
212 PyObject *mro;
213
214 mro = a->tp_mro;
215 if (mro != NULL) {
216 /* Deal with multiple inheritance without recursion
217 by walking the MRO tuple */
218 int i, n;
219 assert(PyTuple_Check(mro));
220 n = PyTuple_GET_SIZE(mro);
221 for (i = 0; i < n; i++) {
222 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
223 return 1;
224 }
225 return 0;
226 }
227 else {
228 /* a is not completely initilized yet; follow tp_base */
229 do {
230 if (a == b)
231 return 1;
232 a = a->tp_base;
233 } while (a != NULL);
234 return b == &PyBaseObject_Type;
235 }
236}
237
238/* Method resolution order algorithm from "Putting Metaclasses to Work"
239 by Forman and Danforth (Addison-Wesley 1999). */
240
241static int
242conservative_merge(PyObject *left, PyObject *right)
243{
244 int left_size;
245 int right_size;
246 int i, j, r, ok;
247 PyObject *temp, *rr;
248
249 assert(PyList_Check(left));
250 assert(PyList_Check(right));
251
252 again:
253 left_size = PyList_GET_SIZE(left);
254 right_size = PyList_GET_SIZE(right);
255 for (i = 0; i < left_size; i++) {
256 for (j = 0; j < right_size; j++) {
257 if (PyList_GET_ITEM(left, i) ==
258 PyList_GET_ITEM(right, j)) {
259 /* found a merge point */
260 temp = PyList_New(0);
261 if (temp == NULL)
262 return -1;
263 for (r = 0; r < j; r++) {
264 rr = PyList_GET_ITEM(right, r);
265 ok = PySequence_Contains(left, rr);
266 if (ok < 0) {
267 Py_DECREF(temp);
268 return -1;
269 }
270 if (!ok) {
271 ok = PyList_Append(temp, rr);
272 if (ok < 0) {
273 Py_DECREF(temp);
274 return -1;
275 }
276 }
277 }
278 ok = PyList_SetSlice(left, i, i, temp);
279 Py_DECREF(temp);
280 if (ok < 0)
281 return -1;
282 ok = PyList_SetSlice(right, 0, j+1, NULL);
283 if (ok < 0)
284 return -1;
285 goto again;
286 }
287 }
288 }
289 return PyList_SetSlice(left, left_size, left_size, right);
290}
291
292static int
293serious_order_disagreements(PyObject *left, PyObject *right)
294{
295 return 0; /* XXX later -- for now, we cheat: "don't do that" */
296}
297
298static PyObject *
299mro_implementation(PyTypeObject *type)
300{
301 int i, n, ok;
302 PyObject *bases, *result;
303
304 bases = type->tp_bases;
305 n = PyTuple_GET_SIZE(bases);
306 result = Py_BuildValue("[O]", (PyObject *)type);
307 if (result == NULL)
308 return NULL;
309 for (i = 0; i < n; i++) {
310 PyTypeObject *base =
311 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
312 PyObject *parentMRO = PySequence_List(base->tp_mro);
313 if (parentMRO == NULL) {
314 Py_DECREF(result);
315 return NULL;
316 }
317 if (serious_order_disagreements(result, parentMRO)) {
318 Py_DECREF(result);
319 return NULL;
320 }
321 ok = conservative_merge(result, parentMRO);
322 Py_DECREF(parentMRO);
323 if (ok < 0) {
324 Py_DECREF(result);
325 return NULL;
326 }
327 }
328 return result;
329}
330
331static PyObject *
332mro_external(PyObject *self, PyObject *args)
333{
334 PyTypeObject *type = (PyTypeObject *)self;
335
336 if (!PyArg_ParseTuple(args, ""))
337 return NULL;
338 return mro_implementation(type);
339}
340
341static int
342mro_internal(PyTypeObject *type)
343{
344 PyObject *mro, *result, *tuple;
345
346 if (type->ob_type == &PyType_Type) {
347 result = mro_implementation(type);
348 }
349 else {
350 mro = PyObject_GetAttrString((PyObject *)type, "mro");
351 if (mro == NULL)
352 return -1;
353 result = PyObject_CallObject(mro, NULL);
354 Py_DECREF(mro);
355 }
356 if (result == NULL)
357 return -1;
358 tuple = PySequence_Tuple(result);
359 Py_DECREF(result);
360 type->tp_mro = tuple;
361 return 0;
362}
363
364
365/* Calculate the best base amongst multiple base classes.
366 This is the first one that's on the path to the "solid base". */
367
368static PyTypeObject *
369best_base(PyObject *bases)
370{
371 int i, n;
372 PyTypeObject *base, *winner, *candidate, *base_i;
373
374 assert(PyTuple_Check(bases));
375 n = PyTuple_GET_SIZE(bases);
376 assert(n > 0);
377 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
378 winner = &PyBaseObject_Type;
379 for (i = 0; i < n; i++) {
380 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
381 if (!PyType_Check((PyObject *)base_i)) {
382 PyErr_SetString(
383 PyExc_TypeError,
384 "bases must be types");
385 return NULL;
386 }
387 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000388 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000389 return NULL;
390 }
391 candidate = solid_base(base_i);
392 if (PyType_IsSubtype(winner, candidate))
393 ;
394 else if (PyType_IsSubtype(candidate, winner)) {
395 winner = candidate;
396 base = base_i;
397 }
398 else {
399 PyErr_SetString(
400 PyExc_TypeError,
401 "multiple bases have "
402 "instance lay-out conflict");
403 return NULL;
404 }
405 }
406 assert(base != NULL);
407 return base;
408}
409
410static int
411extra_ivars(PyTypeObject *type, PyTypeObject *base)
412{
413 int t_size = PyType_BASICSIZE(type);
414 int b_size = PyType_BASICSIZE(base);
415
416 assert(t_size >= b_size); /* type smaller than base! */
417 if (type->tp_itemsize || base->tp_itemsize) {
418 /* If itemsize is involved, stricter rules */
419 return t_size != b_size ||
420 type->tp_itemsize != base->tp_itemsize;
421 }
422 if (t_size == b_size)
423 return 0;
424 if (type->tp_dictoffset != 0 && base->tp_dictoffset == 0 &&
425 type->tp_dictoffset == b_size &&
426 (size_t)t_size == b_size + sizeof(PyObject *))
427 return 0; /* "Forgive" adding a __dict__ only */
428 return 1;
429}
430
431static PyTypeObject *
432solid_base(PyTypeObject *type)
433{
434 PyTypeObject *base;
435
436 if (type->tp_base)
437 base = solid_base(type->tp_base);
438 else
439 base = &PyBaseObject_Type;
440 if (extra_ivars(type, base))
441 return type;
442 else
443 return base;
444}
445
446staticforward void object_dealloc(PyObject *);
447staticforward int object_init(PyObject *, PyObject *, PyObject *);
448
449static PyObject *
450type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
451{
452 PyObject *name, *bases, *dict;
453 static char *kwlist[] = {"name", "bases", "dict", 0};
454 PyObject *slots, *tmp;
455 PyTypeObject *type, *base, *tmptype;
456 etype *et;
457 struct memberlist *mp;
458 int i, nbases, nslots, slotoffset, dynamic;
459
460 if (metatype == &PyType_Type &&
461 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
462 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
463 /* type(x) -> x.__class__ */
464 PyObject *x = PyTuple_GET_ITEM(args, 0);
465 Py_INCREF(x->ob_type);
466 return (PyObject *) x->ob_type;
467 }
468
469 /* Check arguments */
470 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
471 &name,
472 &PyTuple_Type, &bases,
473 &PyDict_Type, &dict))
474 return NULL;
475
476 /* Determine the proper metatype to deal with this,
477 and check for metatype conflicts while we're at it.
478 Note that if some other metatype wins to contract,
479 it's possible that its instances are not types. */
480 nbases = PyTuple_GET_SIZE(bases);
481 for (i = 0; i < nbases; i++) {
482 tmp = PyTuple_GET_ITEM(bases, i);
483 tmptype = tmp->ob_type;
484 if (PyType_IsSubtype(metatype, tmptype))
485 continue;
486 if (PyType_IsSubtype(tmptype, metatype)) {
487 metatype = tmptype;
488 continue;
489 }
490 PyErr_SetString(PyExc_TypeError,
491 "metatype conflict among bases");
492 return NULL;
493 }
494 if (metatype->tp_new != type_new) /* Pass it to the winner */
495 return metatype->tp_new(metatype, args, kwds);
496
497 /* Adjust for empty tuple bases */
498 if (nbases == 0) {
499 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
500 if (bases == NULL)
501 return NULL;
502 nbases = 1;
503 }
504 else
505 Py_INCREF(bases);
506
507 /* XXX From here until type is allocated, "return NULL" leaks bases! */
508
509 /* Calculate best base, and check that all bases are type objects */
510 base = best_base(bases);
511 if (base == NULL)
512 return NULL;
513 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
514 PyErr_Format(PyExc_TypeError,
515 "type '%.100s' is not an acceptable base type",
516 base->tp_name);
517 return NULL;
518 }
519
520 /* Should this be a dynamic class (i.e. modifiable __dict__)? */
521 tmp = PyDict_GetItemString(dict, "__dynamic__");
522 if (tmp != NULL) {
523 /* The class author has a preference */
524 dynamic = PyObject_IsTrue(tmp);
525 Py_DECREF(tmp);
526 if (dynamic < 0)
527 return NULL;
528 }
529 else {
530 /* Make a new class dynamic if any of its bases is dynamic.
531 This is not always the same as inheriting the __dynamic__
532 class attribute! */
533 dynamic = 0;
534 for (i = 0; i < nbases; i++) {
535 tmptype = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
536 if (tmptype->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
537 dynamic = 1;
538 break;
539 }
540 }
541 }
542
543 /* Check for a __slots__ sequence variable in dict, and count it */
544 slots = PyDict_GetItemString(dict, "__slots__");
545 nslots = 0;
546 if (slots != NULL) {
547 /* Make it into a tuple */
548 if (PyString_Check(slots))
549 slots = Py_BuildValue("(O)", slots);
550 else
551 slots = PySequence_Tuple(slots);
552 if (slots == NULL)
553 return NULL;
554 nslots = PyTuple_GET_SIZE(slots);
555 for (i = 0; i < nslots; i++) {
556 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
557 PyErr_SetString(PyExc_TypeError,
558 "__slots__ must be a sequence of strings");
559 Py_DECREF(slots);
560 return NULL;
561 }
562 }
563 }
564 if (slots == NULL && base->tp_dictoffset == 0 &&
565 (base->tp_setattro == PyObject_GenericSetAttr ||
566 base->tp_setattro == NULL))
567 nslots = 1;
568
569 /* XXX From here until type is safely allocated,
570 "return NULL" may leak slots! */
571
572 /* Allocate the type object */
573 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
574 if (type == NULL)
575 return NULL;
576
577 /* Keep name and slots alive in the extended type object */
578 et = (etype *)type;
579 Py_INCREF(name);
580 et->name = name;
581 et->slots = slots;
582
Guido van Rossumdc91b992001-08-08 22:26:22 +0000583 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000584 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
585 Py_TPFLAGS_BASETYPE;
586 if (dynamic)
587 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000588
589 /* It's a new-style number unless it specifically inherits any
590 old-style numeric behavior */
591 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
592 (base->tp_as_number == NULL))
593 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
594
595 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596 type->tp_as_number = &et->as_number;
597 type->tp_as_sequence = &et->as_sequence;
598 type->tp_as_mapping = &et->as_mapping;
599 type->tp_as_buffer = &et->as_buffer;
600 type->tp_name = PyString_AS_STRING(name);
601
602 /* Set tp_base and tp_bases */
603 type->tp_bases = bases;
604 Py_INCREF(base);
605 type->tp_base = base;
606
607 /* Initialize tp_defined from passed-in dict */
608 type->tp_defined = dict = PyDict_Copy(dict);
609 if (dict == NULL) {
610 Py_DECREF(type);
611 return NULL;
612 }
613
614 /* Special-case __new__: if it's a plain function,
615 make it a static function */
616 tmp = PyDict_GetItemString(dict, "__new__");
617 if (tmp != NULL && PyFunction_Check(tmp)) {
618 tmp = PyStaticMethod_New(tmp);
619 if (tmp == NULL) {
620 Py_DECREF(type);
621 return NULL;
622 }
623 PyDict_SetItemString(dict, "__new__", tmp);
624 Py_DECREF(tmp);
625 }
626
627 /* Add descriptors for custom slots from __slots__, or for __dict__ */
628 mp = et->members;
629 slotoffset = PyType_BASICSIZE(base);
630 if (slots != NULL) {
631 for (i = 0; i < nslots; i++, mp++) {
632 mp->name = PyString_AS_STRING(
633 PyTuple_GET_ITEM(slots, i));
634 mp->type = T_OBJECT;
635 mp->offset = slotoffset;
636 slotoffset += sizeof(PyObject *);
637 }
638 }
639 else if (nslots) {
640 type->tp_dictoffset = slotoffset;
641 mp->name = "__dict__";
642 mp->type = T_OBJECT;
643 mp->offset = slotoffset;
644 mp->readonly = 1;
645 slotoffset += sizeof(PyObject *);
646 }
647 type->tp_basicsize = slotoffset;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000648 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000649
650 /* Special case some slots */
651 if (type->tp_dictoffset != 0 || nslots > 0) {
652 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
653 type->tp_getattro = PyObject_GenericGetAttr;
654 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
655 type->tp_setattro = PyObject_GenericSetAttr;
656 }
657 type->tp_dealloc = subtype_dealloc;
658
659 /* Always override allocation strategy to use regular heap */
660 type->tp_alloc = PyType_GenericAlloc;
661 type->tp_free = _PyObject_Del;
662
663 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000664 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665 Py_DECREF(type);
666 return NULL;
667 }
668
669 /* Override slots that deserve it */
670 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000671
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672 return (PyObject *)type;
673}
674
675/* Internal API to look for a name through the MRO.
676 This returns a borrowed reference, and doesn't set an exception! */
677PyObject *
678_PyType_Lookup(PyTypeObject *type, PyObject *name)
679{
680 int i, n;
681 PyObject *mro, *res, *dict;
682
683 /* For static types, look in tp_dict */
684 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
685 dict = type->tp_dict;
686 assert(dict && PyDict_Check(dict));
687 return PyDict_GetItem(dict, name);
688 }
689
690 /* For dynamic types, look in tp_defined of types in MRO */
691 mro = type->tp_mro;
692 assert(PyTuple_Check(mro));
693 n = PyTuple_GET_SIZE(mro);
694 for (i = 0; i < n; i++) {
695 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
696 assert(PyType_Check(type));
697 dict = type->tp_defined;
698 assert(dict && PyDict_Check(dict));
699 res = PyDict_GetItem(dict, name);
700 if (res != NULL)
701 return res;
702 }
703 return NULL;
704}
705
706/* This is similar to PyObject_GenericGetAttr(),
707 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
708static PyObject *
709type_getattro(PyTypeObject *type, PyObject *name)
710{
711 PyTypeObject *metatype = type->ob_type;
712 PyObject *descr, *res;
713 descrgetfunc f;
714
715 /* Initialize this type (we'll assume the metatype is initialized) */
716 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000717 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718 return NULL;
719 }
720
721 /* Get a descriptor from the metatype */
722 descr = _PyType_Lookup(metatype, name);
723 f = NULL;
724 if (descr != NULL) {
725 f = descr->ob_type->tp_descr_get;
726 if (f != NULL && PyDescr_IsData(descr))
727 return f(descr,
728 (PyObject *)type, (PyObject *)metatype);
729 }
730
731 /* Look in tp_defined of this type and its bases */
732 res = _PyType_Lookup(type, name);
733 if (res != NULL) {
734 f = res->ob_type->tp_descr_get;
735 if (f != NULL)
736 return f(res, (PyObject *)NULL, (PyObject *)type);
737 Py_INCREF(res);
738 return res;
739 }
740
741 /* Use the descriptor from the metatype */
742 if (f != NULL) {
743 res = f(descr, (PyObject *)type, (PyObject *)metatype);
744 return res;
745 }
746 if (descr != NULL) {
747 Py_INCREF(descr);
748 return descr;
749 }
750
751 /* Give up */
752 PyErr_Format(PyExc_AttributeError,
753 "type object '%.50s' has no attribute '%.400s'",
754 type->tp_name, PyString_AS_STRING(name));
755 return NULL;
756}
757
758static int
759type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
760{
761 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
762 return PyObject_GenericSetAttr((PyObject *)type, name, value);
763 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
764 return -1;
765}
766
767static void
768type_dealloc(PyTypeObject *type)
769{
770 etype *et;
771
772 /* Assert this is a heap-allocated type object */
773 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
774 et = (etype *)type;
775 Py_XDECREF(type->tp_base);
776 Py_XDECREF(type->tp_dict);
777 Py_XDECREF(type->tp_bases);
778 Py_XDECREF(type->tp_mro);
779 Py_XDECREF(type->tp_defined);
780 /* XXX more? */
781 Py_XDECREF(et->name);
782 Py_XDECREF(et->slots);
783 type->ob_type->tp_free((PyObject *)type);
784}
785
786static PyMethodDef type_methods[] = {
787 {"mro", mro_external, METH_VARARGS,
788 "mro() -> list\nreturn a type's method resolution order"},
789 {0}
790};
791
792static char type_doc[] =
793"type(object) -> the object's type\n"
794"type(name, bases, dict) -> a new type";
795
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000796PyTypeObject PyType_Type = {
797 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000798 0, /* ob_size */
799 "type", /* tp_name */
800 sizeof(etype), /* tp_basicsize */
801 sizeof(struct memberlist), /* tp_itemsize */
802 (destructor)type_dealloc, /* tp_dealloc */
803 0, /* tp_print */
804 0, /* tp_getattr */
805 0, /* tp_setattr */
806 type_compare, /* tp_compare */
807 (reprfunc)type_repr, /* tp_repr */
808 0, /* tp_as_number */
809 0, /* tp_as_sequence */
810 0, /* tp_as_mapping */
811 (hashfunc)_Py_HashPointer, /* tp_hash */
812 (ternaryfunc)type_call, /* tp_call */
813 0, /* tp_str */
814 (getattrofunc)type_getattro, /* tp_getattro */
815 (setattrofunc)type_setattro, /* tp_setattro */
816 0, /* tp_as_buffer */
817 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
818 type_doc, /* tp_doc */
819 0, /* tp_traverse */
820 0, /* tp_clear */
821 0, /* tp_richcompare */
822 0, /* tp_weaklistoffset */
823 0, /* tp_iter */
824 0, /* tp_iternext */
825 type_methods, /* tp_methods */
826 type_members, /* tp_members */
827 type_getsets, /* tp_getset */
828 0, /* tp_base */
829 0, /* tp_dict */
830 0, /* tp_descr_get */
831 0, /* tp_descr_set */
832 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
833 0, /* tp_init */
834 0, /* tp_alloc */
835 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000836};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000837
838
839/* The base type of all types (eventually)... except itself. */
840
841static int
842object_init(PyObject *self, PyObject *args, PyObject *kwds)
843{
844 return 0;
845}
846
847static void
848object_dealloc(PyObject *self)
849{
850 self->ob_type->tp_free(self);
851}
852
853static void
854object_free(PyObject *self)
855{
856 PyObject_Del(self);
857}
858
859static struct memberlist object_members[] = {
860 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
861 {0}
862};
863
864PyTypeObject PyBaseObject_Type = {
865 PyObject_HEAD_INIT(&PyType_Type)
866 0, /* ob_size */
867 "object", /* tp_name */
868 sizeof(PyObject), /* tp_basicsize */
869 0, /* tp_itemsize */
870 (destructor)object_dealloc, /* tp_dealloc */
871 0, /* tp_print */
872 0, /* tp_getattr */
873 0, /* tp_setattr */
874 0, /* tp_compare */
875 0, /* tp_repr */
876 0, /* tp_as_number */
877 0, /* tp_as_sequence */
878 0, /* tp_as_mapping */
879 0, /* tp_hash */
880 0, /* tp_call */
881 0, /* tp_str */
882 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +0000883 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884 0, /* tp_as_buffer */
885 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
886 "The most base type", /* tp_doc */
887 0, /* tp_traverse */
888 0, /* tp_clear */
889 0, /* tp_richcompare */
890 0, /* tp_weaklistoffset */
891 0, /* tp_iter */
892 0, /* tp_iternext */
893 0, /* tp_methods */
894 object_members, /* tp_members */
895 0, /* tp_getset */
896 0, /* tp_base */
897 0, /* tp_dict */
898 0, /* tp_descr_get */
899 0, /* tp_descr_set */
900 0, /* tp_dictoffset */
901 object_init, /* tp_init */
902 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +0000903 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000904 object_free, /* tp_free */
905};
906
907
908/* Initialize the __dict__ in a type object */
909
910static int
911add_methods(PyTypeObject *type, PyMethodDef *meth)
912{
913 PyObject *dict = type->tp_defined;
914
915 for (; meth->ml_name != NULL; meth++) {
916 PyObject *descr;
917 if (PyDict_GetItemString(dict, meth->ml_name))
918 continue;
919 descr = PyDescr_NewMethod(type, meth);
920 if (descr == NULL)
921 return -1;
922 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
923 return -1;
924 Py_DECREF(descr);
925 }
926 return 0;
927}
928
929static int
Tim Peters6d6c1a32001-08-02 04:15:00 +0000930add_members(PyTypeObject *type, struct memberlist *memb)
931{
932 PyObject *dict = type->tp_defined;
933
934 for (; memb->name != NULL; memb++) {
935 PyObject *descr;
936 if (PyDict_GetItemString(dict, memb->name))
937 continue;
938 descr = PyDescr_NewMember(type, memb);
939 if (descr == NULL)
940 return -1;
941 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
942 return -1;
943 Py_DECREF(descr);
944 }
945 return 0;
946}
947
948static int
949add_getset(PyTypeObject *type, struct getsetlist *gsp)
950{
951 PyObject *dict = type->tp_defined;
952
953 for (; gsp->name != NULL; gsp++) {
954 PyObject *descr;
955 if (PyDict_GetItemString(dict, gsp->name))
956 continue;
957 descr = PyDescr_NewGetSet(type, gsp);
958
959 if (descr == NULL)
960 return -1;
961 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
962 return -1;
963 Py_DECREF(descr);
964 }
965 return 0;
966}
967
Guido van Rossum13d52f02001-08-10 21:24:08 +0000968static void
969inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000970{
971 int oldsize, newsize;
972
Guido van Rossum13d52f02001-08-10 21:24:08 +0000973 /* Special flag magic */
974 if (!type->tp_as_buffer && base->tp_as_buffer) {
975 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
976 type->tp_flags |=
977 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
978 }
979 if (!type->tp_as_sequence && base->tp_as_sequence) {
980 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
981 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
982 }
983 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
984 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
985 if ((!type->tp_as_number && base->tp_as_number) ||
986 (!type->tp_as_sequence && base->tp_as_sequence)) {
987 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
988 if (!type->tp_as_number && !type->tp_as_sequence) {
989 type->tp_flags |= base->tp_flags &
990 Py_TPFLAGS_HAVE_INPLACEOPS;
991 }
992 }
993 /* Wow */
994 }
995 if (!type->tp_as_number && base->tp_as_number) {
996 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
997 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
998 }
999
1000 /* Copying basicsize is connected to the GC flags */
1001 oldsize = PyType_BASICSIZE(base);
1002 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1003 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1004 (base->tp_flags & Py_TPFLAGS_GC) &&
1005 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1006 (!type->tp_traverse && !type->tp_clear)) {
1007 type->tp_flags |= Py_TPFLAGS_GC;
1008 if (type->tp_traverse == NULL)
1009 type->tp_traverse = base->tp_traverse;
1010 if (type->tp_clear == NULL)
1011 type->tp_clear = base->tp_clear;
1012 }
1013 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1014 if (base != &PyBaseObject_Type ||
1015 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1016 if (type->tp_new == NULL)
1017 type->tp_new = base->tp_new;
1018 }
1019 }
1020 PyType_SET_BASICSIZE(type, newsize);
1021}
1022
1023static void
1024inherit_slots(PyTypeObject *type, PyTypeObject *base)
1025{
1026 PyTypeObject *basebase;
1027
1028#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029#undef COPYSLOT
1030#undef COPYNUM
1031#undef COPYSEQ
1032#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001033
1034#define SLOTDEFINED(SLOT) \
1035 (base->SLOT != 0 && \
1036 (basebase == NULL || base->SLOT != basebase->SLOT))
1037
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001039 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001040
1041#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1042#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1043#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1044
Guido van Rossum13d52f02001-08-10 21:24:08 +00001045 /* This won't inherit indirect slots (from tp_as_number etc.)
1046 if type doesn't provide the space. */
1047
1048 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1049 basebase = base->tp_base;
1050 if (basebase->tp_as_number == NULL)
1051 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052 COPYNUM(nb_add);
1053 COPYNUM(nb_subtract);
1054 COPYNUM(nb_multiply);
1055 COPYNUM(nb_divide);
1056 COPYNUM(nb_remainder);
1057 COPYNUM(nb_divmod);
1058 COPYNUM(nb_power);
1059 COPYNUM(nb_negative);
1060 COPYNUM(nb_positive);
1061 COPYNUM(nb_absolute);
1062 COPYNUM(nb_nonzero);
1063 COPYNUM(nb_invert);
1064 COPYNUM(nb_lshift);
1065 COPYNUM(nb_rshift);
1066 COPYNUM(nb_and);
1067 COPYNUM(nb_xor);
1068 COPYNUM(nb_or);
1069 COPYNUM(nb_coerce);
1070 COPYNUM(nb_int);
1071 COPYNUM(nb_long);
1072 COPYNUM(nb_float);
1073 COPYNUM(nb_oct);
1074 COPYNUM(nb_hex);
1075 COPYNUM(nb_inplace_add);
1076 COPYNUM(nb_inplace_subtract);
1077 COPYNUM(nb_inplace_multiply);
1078 COPYNUM(nb_inplace_divide);
1079 COPYNUM(nb_inplace_remainder);
1080 COPYNUM(nb_inplace_power);
1081 COPYNUM(nb_inplace_lshift);
1082 COPYNUM(nb_inplace_rshift);
1083 COPYNUM(nb_inplace_and);
1084 COPYNUM(nb_inplace_xor);
1085 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001086 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1087 COPYNUM(nb_true_divide);
1088 COPYNUM(nb_floor_divide);
1089 COPYNUM(nb_inplace_true_divide);
1090 COPYNUM(nb_inplace_floor_divide);
1091 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 }
1093
Guido van Rossum13d52f02001-08-10 21:24:08 +00001094 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1095 basebase = base->tp_base;
1096 if (basebase->tp_as_sequence == NULL)
1097 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098 COPYSEQ(sq_length);
1099 COPYSEQ(sq_concat);
1100 COPYSEQ(sq_repeat);
1101 COPYSEQ(sq_item);
1102 COPYSEQ(sq_slice);
1103 COPYSEQ(sq_ass_item);
1104 COPYSEQ(sq_ass_slice);
1105 COPYSEQ(sq_contains);
1106 COPYSEQ(sq_inplace_concat);
1107 COPYSEQ(sq_inplace_repeat);
1108 }
1109
Guido van Rossum13d52f02001-08-10 21:24:08 +00001110 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1111 basebase = base->tp_base;
1112 if (basebase->tp_as_mapping == NULL)
1113 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114 COPYMAP(mp_length);
1115 COPYMAP(mp_subscript);
1116 COPYMAP(mp_ass_subscript);
1117 }
1118
Guido van Rossum13d52f02001-08-10 21:24:08 +00001119 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120
1121 COPYSLOT(tp_itemsize);
1122 COPYSLOT(tp_dealloc);
1123 COPYSLOT(tp_print);
1124 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1125 type->tp_getattr = base->tp_getattr;
1126 type->tp_getattro = base->tp_getattro;
1127 }
1128 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1129 type->tp_setattr = base->tp_setattr;
1130 type->tp_setattro = base->tp_setattro;
1131 }
1132 /* tp_compare see tp_richcompare */
1133 COPYSLOT(tp_repr);
1134 COPYSLOT(tp_hash);
1135 COPYSLOT(tp_call);
1136 COPYSLOT(tp_str);
1137 COPYSLOT(tp_as_buffer);
1138 COPYSLOT(tp_flags);
1139 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
1140 if (type->tp_compare == NULL && type->tp_richcompare == NULL) {
1141 type->tp_compare = base->tp_compare;
1142 type->tp_richcompare = base->tp_richcompare;
1143 }
1144 }
1145 else {
1146 COPYSLOT(tp_compare);
1147 }
1148 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1149 COPYSLOT(tp_weaklistoffset);
1150 }
1151 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1152 COPYSLOT(tp_iter);
1153 COPYSLOT(tp_iternext);
1154 }
1155 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1156 COPYSLOT(tp_descr_get);
1157 COPYSLOT(tp_descr_set);
1158 COPYSLOT(tp_dictoffset);
1159 COPYSLOT(tp_init);
1160 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161 COPYSLOT(tp_free);
1162 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163}
1164
Guido van Rossum13d52f02001-08-10 21:24:08 +00001165staticforward int add_operators(PyTypeObject *);
1166
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001168PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169{
1170 PyObject *dict, *bases, *x;
1171 PyTypeObject *base;
1172 int i, n;
1173
Guido van Rossumd614f972001-08-10 17:39:49 +00001174 if (type->tp_flags & Py_TPFLAGS_READY) {
1175 assert(type->tp_dict != NULL);
1176 return 0;
1177 }
1178 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1179 assert(type->tp_dict == NULL);
1180
1181 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182
1183 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1184 base = type->tp_base;
1185 if (base == NULL && type != &PyBaseObject_Type)
1186 base = type->tp_base = &PyBaseObject_Type;
1187
1188 /* Initialize tp_bases */
1189 bases = type->tp_bases;
1190 if (bases == NULL) {
1191 if (base == NULL)
1192 bases = PyTuple_New(0);
1193 else
1194 bases = Py_BuildValue("(O)", base);
1195 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001196 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001197 type->tp_bases = bases;
1198 }
1199
1200 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001201 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001202 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001203 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204 }
1205
1206 /* Initialize tp_defined */
1207 dict = type->tp_defined;
1208 if (dict == NULL) {
1209 dict = PyDict_New();
1210 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001211 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 type->tp_defined = dict;
1213 }
1214
1215 /* Add type-specific descriptors to tp_defined */
1216 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001217 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 if (type->tp_methods != NULL) {
1219 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001220 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 }
1222 if (type->tp_members != NULL) {
1223 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001224 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225 }
1226 if (type->tp_getset != NULL) {
1227 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001228 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229 }
1230
1231 /* Temporarily make tp_dict the same object as tp_defined.
1232 (This is needed to call mro(), and can stay this way for
1233 dynamic types). */
1234 Py_INCREF(type->tp_defined);
1235 type->tp_dict = type->tp_defined;
1236
1237 /* Calculate method resolution order */
1238 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001239 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 }
1241
Guido van Rossum13d52f02001-08-10 21:24:08 +00001242 /* Inherit special flags from dominant base */
1243 if (type->tp_base != NULL)
1244 inherit_special(type, type->tp_base);
1245
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001247 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
1248 /* XXX This is not enough -- see checkin msg 2.30. */
1249 if (type->tp_base != NULL)
1250 inherit_slots(type, type->tp_base);
1251 }
1252 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001254 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001256 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001258 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259 bases = type->tp_mro;
1260 assert(bases != NULL);
1261 assert(PyTuple_Check(bases));
1262 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001263 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1265 assert(PyType_Check(base));
1266 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001267 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001268 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001269 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 }
1271 }
1272
Guido van Rossum13d52f02001-08-10 21:24:08 +00001273 /* Some more special stuff */
1274 base = type->tp_base;
1275 if (base != NULL) {
1276 if (type->tp_as_number == NULL)
1277 type->tp_as_number = base->tp_as_number;
1278 if (type->tp_as_sequence == NULL)
1279 type->tp_as_sequence = base->tp_as_sequence;
1280 if (type->tp_as_mapping == NULL)
1281 type->tp_as_mapping = base->tp_as_mapping;
1282 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283
Guido van Rossum13d52f02001-08-10 21:24:08 +00001284 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001285 assert(type->tp_dict != NULL);
1286 type->tp_flags =
1287 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001289
1290 error:
1291 type->tp_flags &= ~Py_TPFLAGS_READYING;
1292 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293}
1294
1295
1296/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1297
1298/* There's a wrapper *function* for each distinct function typedef used
1299 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1300 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1301 Most tables have only one entry; the tables for binary operators have two
1302 entries, one regular and one with reversed arguments. */
1303
1304static PyObject *
1305wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1306{
1307 inquiry func = (inquiry)wrapped;
1308 int res;
1309
1310 if (!PyArg_ParseTuple(args, ""))
1311 return NULL;
1312 res = (*func)(self);
1313 if (res == -1 && PyErr_Occurred())
1314 return NULL;
1315 return PyInt_FromLong((long)res);
1316}
1317
1318static struct wrapperbase tab_len[] = {
1319 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1320 {0}
1321};
1322
1323static PyObject *
1324wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1325{
1326 binaryfunc func = (binaryfunc)wrapped;
1327 PyObject *other;
1328
1329 if (!PyArg_ParseTuple(args, "O", &other))
1330 return NULL;
1331 return (*func)(self, other);
1332}
1333
1334static PyObject *
1335wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1336{
1337 binaryfunc func = (binaryfunc)wrapped;
1338 PyObject *other;
1339
1340 if (!PyArg_ParseTuple(args, "O", &other))
1341 return NULL;
1342 return (*func)(other, self);
1343}
1344
1345#undef BINARY
1346#define BINARY(NAME, OP) \
1347static struct wrapperbase tab_##NAME[] = { \
1348 {"__" #NAME "__", \
1349 (wrapperfunc)wrap_binaryfunc, \
1350 "x.__" #NAME "__(y) <==> " #OP}, \
1351 {"__r" #NAME "__", \
1352 (wrapperfunc)wrap_binaryfunc_r, \
1353 "y.__r" #NAME "__(x) <==> " #OP}, \
1354 {0} \
1355}
1356
1357BINARY(add, "x+y");
1358BINARY(sub, "x-y");
1359BINARY(mul, "x*y");
1360BINARY(div, "x/y");
1361BINARY(mod, "x%y");
1362BINARY(divmod, "divmod(x,y)");
1363BINARY(lshift, "x<<y");
1364BINARY(rshift, "x>>y");
1365BINARY(and, "x&y");
1366BINARY(xor, "x^y");
1367BINARY(or, "x|y");
1368
1369static PyObject *
1370wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1371{
1372 ternaryfunc func = (ternaryfunc)wrapped;
1373 PyObject *other;
1374 PyObject *third = Py_None;
1375
1376 /* Note: This wrapper only works for __pow__() */
1377
1378 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1379 return NULL;
1380 return (*func)(self, other, third);
1381}
1382
1383#undef TERNARY
1384#define TERNARY(NAME, OP) \
1385static struct wrapperbase tab_##NAME[] = { \
1386 {"__" #NAME "__", \
1387 (wrapperfunc)wrap_ternaryfunc, \
1388 "x.__" #NAME "__(y, z) <==> " #OP}, \
1389 {"__r" #NAME "__", \
1390 (wrapperfunc)wrap_ternaryfunc, \
1391 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1392 {0} \
1393}
1394
1395TERNARY(pow, "(x**y) % z");
1396
1397#undef UNARY
1398#define UNARY(NAME, OP) \
1399static struct wrapperbase tab_##NAME[] = { \
1400 {"__" #NAME "__", \
1401 (wrapperfunc)wrap_unaryfunc, \
1402 "x.__" #NAME "__() <==> " #OP}, \
1403 {0} \
1404}
1405
1406static PyObject *
1407wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1408{
1409 unaryfunc func = (unaryfunc)wrapped;
1410
1411 if (!PyArg_ParseTuple(args, ""))
1412 return NULL;
1413 return (*func)(self);
1414}
1415
1416UNARY(neg, "-x");
1417UNARY(pos, "+x");
1418UNARY(abs, "abs(x)");
1419UNARY(nonzero, "x != 0");
1420UNARY(invert, "~x");
1421UNARY(int, "int(x)");
1422UNARY(long, "long(x)");
1423UNARY(float, "float(x)");
1424UNARY(oct, "oct(x)");
1425UNARY(hex, "hex(x)");
1426
1427#undef IBINARY
1428#define IBINARY(NAME, OP) \
1429static struct wrapperbase tab_##NAME[] = { \
1430 {"__" #NAME "__", \
1431 (wrapperfunc)wrap_binaryfunc, \
1432 "x.__" #NAME "__(y) <==> " #OP}, \
1433 {0} \
1434}
1435
1436IBINARY(iadd, "x+=y");
1437IBINARY(isub, "x-=y");
1438IBINARY(imul, "x*=y");
1439IBINARY(idiv, "x/=y");
1440IBINARY(imod, "x%=y");
1441IBINARY(ilshift, "x<<=y");
1442IBINARY(irshift, "x>>=y");
1443IBINARY(iand, "x&=y");
1444IBINARY(ixor, "x^=y");
1445IBINARY(ior, "x|=y");
1446
1447#undef ITERNARY
1448#define ITERNARY(NAME, OP) \
1449static struct wrapperbase tab_##NAME[] = { \
1450 {"__" #NAME "__", \
1451 (wrapperfunc)wrap_ternaryfunc, \
1452 "x.__" #NAME "__(y) <==> " #OP}, \
1453 {0} \
1454}
1455
1456ITERNARY(ipow, "x = (x**y) % z");
1457
1458static struct wrapperbase tab_getitem[] = {
1459 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1460 "x.__getitem__(y) <==> x[y]"},
1461 {0}
1462};
1463
1464static PyObject *
1465wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1466{
1467 intargfunc func = (intargfunc)wrapped;
1468 int i;
1469
1470 if (!PyArg_ParseTuple(args, "i", &i))
1471 return NULL;
1472 return (*func)(self, i);
1473}
1474
1475static struct wrapperbase tab_mul_int[] = {
1476 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1477 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1478 {0}
1479};
1480
1481static struct wrapperbase tab_concat[] = {
1482 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1483 {0}
1484};
1485
1486static struct wrapperbase tab_imul_int[] = {
1487 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1488 {0}
1489};
1490
1491static struct wrapperbase tab_getitem_int[] = {
1492 {"__getitem__", (wrapperfunc)wrap_intargfunc,
1493 "x.__getitem__(i) <==> x[i]"},
1494 {0}
1495};
1496
1497static PyObject *
1498wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1499{
1500 intintargfunc func = (intintargfunc)wrapped;
1501 int i, j;
1502
1503 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1504 return NULL;
1505 return (*func)(self, i, j);
1506}
1507
1508static struct wrapperbase tab_getslice[] = {
1509 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1510 "x.__getslice__(i, j) <==> x[i:j]"},
1511 {0}
1512};
1513
1514static PyObject *
1515wrap_intobjargproc(PyObject *self, PyObject *args, void *wrapped)
1516{
1517 intobjargproc func = (intobjargproc)wrapped;
1518 int i, res;
1519 PyObject *value;
1520
1521 if (!PyArg_ParseTuple(args, "iO", &i, &value))
1522 return NULL;
1523 res = (*func)(self, i, value);
1524 if (res == -1 && PyErr_Occurred())
1525 return NULL;
1526 Py_INCREF(Py_None);
1527 return Py_None;
1528}
1529
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001530static PyObject *
1531wrap_delitem_int(PyObject *self, PyObject *args, void *wrapped)
1532{
1533 intobjargproc func = (intobjargproc)wrapped;
1534 int i, res;
1535
1536 if (!PyArg_ParseTuple(args, "i", &i))
1537 return NULL;
1538 res = (*func)(self, i, NULL);
1539 if (res == -1 && PyErr_Occurred())
1540 return NULL;
1541 Py_INCREF(Py_None);
1542 return Py_None;
1543}
1544
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545static struct wrapperbase tab_setitem_int[] = {
1546 {"__setitem__", (wrapperfunc)wrap_intobjargproc,
1547 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001548 {"__delitem__", (wrapperfunc)wrap_delitem_int,
1549 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 {0}
1551};
1552
1553static PyObject *
1554wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1555{
1556 intintobjargproc func = (intintobjargproc)wrapped;
1557 int i, j, res;
1558 PyObject *value;
1559
1560 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1561 return NULL;
1562 res = (*func)(self, i, j, value);
1563 if (res == -1 && PyErr_Occurred())
1564 return NULL;
1565 Py_INCREF(Py_None);
1566 return Py_None;
1567}
1568
1569static struct wrapperbase tab_setslice[] = {
1570 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1571 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1572 {0}
1573};
1574
1575/* XXX objobjproc is a misnomer; should be objargpred */
1576static PyObject *
1577wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1578{
1579 objobjproc func = (objobjproc)wrapped;
1580 int res;
1581 PyObject *value;
1582
1583 if (!PyArg_ParseTuple(args, "O", &value))
1584 return NULL;
1585 res = (*func)(self, value);
1586 if (res == -1 && PyErr_Occurred())
1587 return NULL;
1588 return PyInt_FromLong((long)res);
1589}
1590
1591static struct wrapperbase tab_contains[] = {
1592 {"__contains__", (wrapperfunc)wrap_objobjproc,
1593 "x.__contains__(y) <==> y in x"},
1594 {0}
1595};
1596
1597static PyObject *
1598wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1599{
1600 objobjargproc func = (objobjargproc)wrapped;
1601 int res;
1602 PyObject *key, *value;
1603
1604 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1605 return NULL;
1606 res = (*func)(self, key, value);
1607 if (res == -1 && PyErr_Occurred())
1608 return NULL;
1609 Py_INCREF(Py_None);
1610 return Py_None;
1611}
1612
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001613static PyObject *
1614wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1615{
1616 objobjargproc func = (objobjargproc)wrapped;
1617 int res;
1618 PyObject *key;
1619
1620 if (!PyArg_ParseTuple(args, "O", &key))
1621 return NULL;
1622 res = (*func)(self, key, NULL);
1623 if (res == -1 && PyErr_Occurred())
1624 return NULL;
1625 Py_INCREF(Py_None);
1626 return Py_None;
1627}
1628
Tim Peters6d6c1a32001-08-02 04:15:00 +00001629static struct wrapperbase tab_setitem[] = {
1630 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1631 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001632 {"__delitem__", (wrapperfunc)wrap_delitem,
1633 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001634 {0}
1635};
1636
1637static PyObject *
1638wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1639{
1640 cmpfunc func = (cmpfunc)wrapped;
1641 int res;
1642 PyObject *other;
1643
1644 if (!PyArg_ParseTuple(args, "O", &other))
1645 return NULL;
1646 res = (*func)(self, other);
1647 if (PyErr_Occurred())
1648 return NULL;
1649 return PyInt_FromLong((long)res);
1650}
1651
1652static struct wrapperbase tab_cmp[] = {
1653 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1654 "x.__cmp__(y) <==> cmp(x,y)"},
1655 {0}
1656};
1657
1658static struct wrapperbase tab_repr[] = {
1659 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1660 "x.__repr__() <==> repr(x)"},
1661 {0}
1662};
1663
1664static struct wrapperbase tab_getattr[] = {
1665 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1666 "x.__getattr__('name') <==> x.name"},
1667 {0}
1668};
1669
1670static PyObject *
1671wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1672{
1673 setattrofunc func = (setattrofunc)wrapped;
1674 int res;
1675 PyObject *name, *value;
1676
1677 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1678 return NULL;
1679 res = (*func)(self, name, value);
1680 if (res < 0)
1681 return NULL;
1682 Py_INCREF(Py_None);
1683 return Py_None;
1684}
1685
1686static PyObject *
1687wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1688{
1689 setattrofunc func = (setattrofunc)wrapped;
1690 int res;
1691 PyObject *name;
1692
1693 if (!PyArg_ParseTuple(args, "O", &name))
1694 return NULL;
1695 res = (*func)(self, name, NULL);
1696 if (res < 0)
1697 return NULL;
1698 Py_INCREF(Py_None);
1699 return Py_None;
1700}
1701
1702static struct wrapperbase tab_setattr[] = {
1703 {"__setattr__", (wrapperfunc)wrap_setattr,
1704 "x.__setattr__('name', value) <==> x.name = value"},
1705 {"__delattr__", (wrapperfunc)wrap_delattr,
1706 "x.__delattr__('name') <==> del x.name"},
1707 {0}
1708};
1709
1710static PyObject *
1711wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1712{
1713 hashfunc func = (hashfunc)wrapped;
1714 long res;
1715
1716 if (!PyArg_ParseTuple(args, ""))
1717 return NULL;
1718 res = (*func)(self);
1719 if (res == -1 && PyErr_Occurred())
1720 return NULL;
1721 return PyInt_FromLong(res);
1722}
1723
1724static struct wrapperbase tab_hash[] = {
1725 {"__hash__", (wrapperfunc)wrap_hashfunc,
1726 "x.__hash__() <==> hash(x)"},
1727 {0}
1728};
1729
1730static PyObject *
1731wrap_call(PyObject *self, PyObject *args, void *wrapped)
1732{
1733 ternaryfunc func = (ternaryfunc)wrapped;
1734
1735 /* XXX What about keyword arguments? */
1736 return (*func)(self, args, NULL);
1737}
1738
1739static struct wrapperbase tab_call[] = {
1740 {"__call__", (wrapperfunc)wrap_call,
1741 "x.__call__(...) <==> x(...)"},
1742 {0}
1743};
1744
1745static struct wrapperbase tab_str[] = {
1746 {"__str__", (wrapperfunc)wrap_unaryfunc,
1747 "x.__str__() <==> str(x)"},
1748 {0}
1749};
1750
1751static PyObject *
1752wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1753{
1754 richcmpfunc func = (richcmpfunc)wrapped;
1755 PyObject *other;
1756
1757 if (!PyArg_ParseTuple(args, "O", &other))
1758 return NULL;
1759 return (*func)(self, other, op);
1760}
1761
1762#undef RICHCMP_WRAPPER
1763#define RICHCMP_WRAPPER(NAME, OP) \
1764static PyObject * \
1765richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1766{ \
1767 return wrap_richcmpfunc(self, args, wrapped, OP); \
1768}
1769
Jack Jansen8e938b42001-08-08 15:29:49 +00001770RICHCMP_WRAPPER(lt, Py_LT)
1771RICHCMP_WRAPPER(le, Py_LE)
1772RICHCMP_WRAPPER(eq, Py_EQ)
1773RICHCMP_WRAPPER(ne, Py_NE)
1774RICHCMP_WRAPPER(gt, Py_GT)
1775RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776
1777#undef RICHCMP_ENTRY
1778#define RICHCMP_ENTRY(NAME, EXPR) \
1779 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1780 "x.__" #NAME "__(y) <==> " EXPR}
1781
1782static struct wrapperbase tab_richcmp[] = {
1783 RICHCMP_ENTRY(lt, "x<y"),
1784 RICHCMP_ENTRY(le, "x<=y"),
1785 RICHCMP_ENTRY(eq, "x==y"),
1786 RICHCMP_ENTRY(ne, "x!=y"),
1787 RICHCMP_ENTRY(gt, "x>y"),
1788 RICHCMP_ENTRY(ge, "x>=y"),
1789 {0}
1790};
1791
1792static struct wrapperbase tab_iter[] = {
1793 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
1794 {0}
1795};
1796
1797static PyObject *
1798wrap_next(PyObject *self, PyObject *args, void *wrapped)
1799{
1800 unaryfunc func = (unaryfunc)wrapped;
1801 PyObject *res;
1802
1803 if (!PyArg_ParseTuple(args, ""))
1804 return NULL;
1805 res = (*func)(self);
1806 if (res == NULL && !PyErr_Occurred())
1807 PyErr_SetNone(PyExc_StopIteration);
1808 return res;
1809}
1810
1811static struct wrapperbase tab_next[] = {
1812 {"next", (wrapperfunc)wrap_next,
1813 "x.next() -> the next value, or raise StopIteration"},
1814 {0}
1815};
1816
1817static PyObject *
1818wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
1819{
1820 descrgetfunc func = (descrgetfunc)wrapped;
1821 PyObject *obj;
1822 PyObject *type = NULL;
1823
1824 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
1825 return NULL;
1826 if (type == NULL)
1827 type = (PyObject *)obj->ob_type;
1828 return (*func)(self, obj, type);
1829}
1830
1831static struct wrapperbase tab_descr_get[] = {
1832 {"__get__", (wrapperfunc)wrap_descr_get,
1833 "descr.__get__(obj, type) -> value"},
1834 {0}
1835};
1836
1837static PyObject *
1838wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
1839{
1840 descrsetfunc func = (descrsetfunc)wrapped;
1841 PyObject *obj, *value;
1842 int ret;
1843
1844 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
1845 return NULL;
1846 ret = (*func)(self, obj, value);
1847 if (ret < 0)
1848 return NULL;
1849 Py_INCREF(Py_None);
1850 return Py_None;
1851}
1852
1853static struct wrapperbase tab_descr_set[] = {
1854 {"__set__", (wrapperfunc)wrap_descrsetfunc,
1855 "descr.__set__(obj, value)"},
1856 {0}
1857};
1858
1859static PyObject *
1860wrap_init(PyObject *self, PyObject *args, void *wrapped)
1861{
1862 initproc func = (initproc)wrapped;
1863
1864 /* XXX What about keyword arguments? */
1865 if (func(self, args, NULL) < 0)
1866 return NULL;
1867 Py_INCREF(Py_None);
1868 return Py_None;
1869}
1870
1871static struct wrapperbase tab_init[] = {
1872 {"__init__", (wrapperfunc)wrap_init,
1873 "x.__init__(...) initializes x; "
1874 "see x.__type__.__doc__ for signature"},
1875 {0}
1876};
1877
1878static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001879tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880{
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001881 PyTypeObject *type, *subtype;
1882 PyObject *arg0, *res;
1883
1884 if (self == NULL || !PyType_Check(self))
1885 Py_FatalError("__new__() called with non-type 'self'");
1886 type = (PyTypeObject *)self;
1887 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
1888 PyErr_SetString(PyExc_TypeError,
1889 "T.__new__(): not enough arguments");
1890 return NULL;
1891 }
1892 arg0 = PyTuple_GET_ITEM(args, 0);
1893 if (!PyType_Check(arg0)) {
1894 PyErr_SetString(PyExc_TypeError,
1895 "T.__new__(S): S is not a type object");
1896 return NULL;
1897 }
1898 subtype = (PyTypeObject *)arg0;
1899 if (!PyType_IsSubtype(subtype, type)) {
1900 PyErr_SetString(PyExc_TypeError,
1901 "T.__new__(S): S is not a subtype of T");
1902 return NULL;
1903 }
1904 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
1905 if (args == NULL)
1906 return NULL;
1907 res = type->tp_new(subtype, args, kwds);
1908 Py_DECREF(args);
1909 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910}
1911
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001912static struct PyMethodDef tp_new_methoddef[] = {
1913 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
1914 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001915 {0}
1916};
1917
1918static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001919add_tp_new_wrapper(PyTypeObject *type)
1920{
Guido van Rossumf040ede2001-08-07 16:40:56 +00001921 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001922
Guido van Rossumf040ede2001-08-07 16:40:56 +00001923 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
1924 return 0;
1925 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001926 if (func == NULL)
1927 return -1;
1928 return PyDict_SetItemString(type->tp_defined, "__new__", func);
1929}
1930
Guido van Rossum13d52f02001-08-10 21:24:08 +00001931static int
1932add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
1933{
1934 PyObject *dict = type->tp_defined;
1935
1936 for (; wraps->name != NULL; wraps++) {
1937 PyObject *descr;
1938 if (PyDict_GetItemString(dict, wraps->name))
1939 continue;
1940 descr = PyDescr_NewWrapper(type, wraps, wrapped);
1941 if (descr == NULL)
1942 return -1;
1943 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
1944 return -1;
1945 Py_DECREF(descr);
1946 }
1947 return 0;
1948}
1949
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001950/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00001951 dictionary with method descriptors for function slots. For each
1952 function slot (like tp_repr) that's defined in the type, one or
1953 more corresponding descriptors are added in the type's tp_defined
1954 dictionary under the appropriate name (like __repr__). Some
1955 function slots cause more than one descriptor to be added (for
1956 example, the nb_add slot adds both __add__ and __radd__
1957 descriptors) and some function slots compete for the same
1958 descriptor (for example both sq_item and mp_subscript generate a
1959 __getitem__ descriptor). This only adds new descriptors and
1960 doesn't overwrite entries in tp_defined that were previously
1961 defined. The descriptors contain a reference to the C function
1962 they must call, so that it's safe if they are copied into a
1963 subtype's __dict__ and the subtype has a different C function in
1964 its slot -- calling the method defined by the descriptor will call
1965 the C function that was used to create it, rather than the C
1966 function present in the slot when it is called. (This is important
1967 because a subtype may have a C function in the slot that calls the
1968 method from the dictionary, and we want to avoid infinite recursion
1969 here.) */
1970
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001971static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972add_operators(PyTypeObject *type)
1973{
1974 PySequenceMethods *sq;
1975 PyMappingMethods *mp;
1976 PyNumberMethods *nb;
1977
1978#undef ADD
1979#define ADD(SLOT, TABLE) \
1980 if (SLOT) { \
1981 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
1982 return -1; \
1983 }
1984
1985 if ((sq = type->tp_as_sequence) != NULL) {
1986 ADD(sq->sq_length, tab_len);
1987 ADD(sq->sq_concat, tab_concat);
1988 ADD(sq->sq_repeat, tab_mul_int);
1989 ADD(sq->sq_item, tab_getitem_int);
1990 ADD(sq->sq_slice, tab_getslice);
1991 ADD(sq->sq_ass_item, tab_setitem_int);
1992 ADD(sq->sq_ass_slice, tab_setslice);
1993 ADD(sq->sq_contains, tab_contains);
1994 ADD(sq->sq_inplace_concat, tab_iadd);
1995 ADD(sq->sq_inplace_repeat, tab_imul_int);
1996 }
1997
1998 if ((mp = type->tp_as_mapping) != NULL) {
1999 if (sq->sq_length == NULL)
2000 ADD(mp->mp_length, tab_len);
2001 ADD(mp->mp_subscript, tab_getitem);
2002 ADD(mp->mp_ass_subscript, tab_setitem);
2003 }
2004
2005 /* We don't support "old-style numbers" because their binary
2006 operators require that both arguments have the same type;
2007 the wrappers here only work for new-style numbers. */
2008 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2009 (nb = type->tp_as_number) != NULL) {
2010 ADD(nb->nb_add, tab_add);
2011 ADD(nb->nb_subtract, tab_sub);
2012 ADD(nb->nb_multiply, tab_mul);
2013 ADD(nb->nb_divide, tab_div);
2014 ADD(nb->nb_remainder, tab_mod);
2015 ADD(nb->nb_divmod, tab_divmod);
2016 ADD(nb->nb_power, tab_pow);
2017 ADD(nb->nb_negative, tab_neg);
2018 ADD(nb->nb_positive, tab_pos);
2019 ADD(nb->nb_absolute, tab_abs);
2020 ADD(nb->nb_nonzero, tab_nonzero);
2021 ADD(nb->nb_invert, tab_invert);
2022 ADD(nb->nb_lshift, tab_lshift);
2023 ADD(nb->nb_rshift, tab_rshift);
2024 ADD(nb->nb_and, tab_and);
2025 ADD(nb->nb_xor, tab_xor);
2026 ADD(nb->nb_or, tab_or);
2027 /* We don't support coerce() -- see above comment */
2028 ADD(nb->nb_int, tab_int);
2029 ADD(nb->nb_long, tab_long);
2030 ADD(nb->nb_float, tab_float);
2031 ADD(nb->nb_oct, tab_oct);
2032 ADD(nb->nb_hex, tab_hex);
2033 ADD(nb->nb_inplace_add, tab_iadd);
2034 ADD(nb->nb_inplace_subtract, tab_isub);
2035 ADD(nb->nb_inplace_multiply, tab_imul);
2036 ADD(nb->nb_inplace_divide, tab_idiv);
2037 ADD(nb->nb_inplace_remainder, tab_imod);
2038 ADD(nb->nb_inplace_power, tab_ipow);
2039 ADD(nb->nb_inplace_lshift, tab_ilshift);
2040 ADD(nb->nb_inplace_rshift, tab_irshift);
2041 ADD(nb->nb_inplace_and, tab_iand);
2042 ADD(nb->nb_inplace_xor, tab_ixor);
2043 ADD(nb->nb_inplace_or, tab_ior);
2044 }
2045
2046 ADD(type->tp_getattro, tab_getattr);
2047 ADD(type->tp_setattro, tab_setattr);
2048 ADD(type->tp_compare, tab_cmp);
2049 ADD(type->tp_repr, tab_repr);
2050 ADD(type->tp_hash, tab_hash);
2051 ADD(type->tp_call, tab_call);
2052 ADD(type->tp_str, tab_str);
2053 ADD(type->tp_richcompare, tab_richcmp);
2054 ADD(type->tp_iter, tab_iter);
2055 ADD(type->tp_iternext, tab_next);
2056 ADD(type->tp_descr_get, tab_descr_get);
2057 ADD(type->tp_descr_set, tab_descr_set);
2058 ADD(type->tp_init, tab_init);
2059
Guido van Rossumf040ede2001-08-07 16:40:56 +00002060 if (type->tp_new != NULL) {
2061 if (add_tp_new_wrapper(type) < 0)
2062 return -1;
2063 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064
2065 return 0;
2066}
2067
Guido van Rossumf040ede2001-08-07 16:40:56 +00002068/* Slot wrappers that call the corresponding __foo__ slot. See comments
2069 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070
Guido van Rossumdc91b992001-08-08 22:26:22 +00002071#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002072static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002073FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002074{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002075 return PyObject_CallMethod(self, OPSTR, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002076}
2077
Guido van Rossumdc91b992001-08-08 22:26:22 +00002078#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002080FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002081{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002082 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083}
2084
Guido van Rossumdc91b992001-08-08 22:26:22 +00002085
2086#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002087static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002088FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002090 if (self->ob_type->tp_as_number != NULL && \
2091 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2092 PyObject *r; \
2093 r = PyObject_CallMethod( \
2094 self, OPSTR, "O", other); \
2095 if (r != Py_NotImplemented || \
2096 other->ob_type == self->ob_type) \
2097 return r; \
2098 Py_DECREF(r); \
2099 } \
2100 if (other->ob_type->tp_as_number != NULL && \
2101 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2102 return PyObject_CallMethod( \
2103 other, ROPSTR, "O", self); \
2104 } \
2105 Py_INCREF(Py_NotImplemented); \
2106 return Py_NotImplemented; \
2107}
2108
2109#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2110 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2111
2112#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2113static PyObject * \
2114FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2115{ \
2116 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002117}
2118
2119static int
2120slot_sq_length(PyObject *self)
2121{
2122 PyObject *res = PyObject_CallMethod(self, "__len__", "");
2123
2124 if (res == NULL)
2125 return -1;
2126 return (int)PyInt_AsLong(res);
2127}
2128
Guido van Rossumdc91b992001-08-08 22:26:22 +00002129SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2130SLOT1(slot_sq_repeat, "__mul__", int, "i")
2131SLOT1(slot_sq_item, "__getitem__", int, "i")
2132SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002133
2134static int
2135slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2136{
2137 PyObject *res;
2138
2139 if (value == NULL)
2140 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2141 else
2142 res = PyObject_CallMethod(self, "__setitem__",
2143 "iO", index, value);
2144 if (res == NULL)
2145 return -1;
2146 Py_DECREF(res);
2147 return 0;
2148}
2149
2150static int
2151slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2152{
2153 PyObject *res;
2154
2155 if (value == NULL)
2156 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2157 else
2158 res = PyObject_CallMethod(self, "__setslice__",
2159 "iiO", i, j, value);
2160 if (res == NULL)
2161 return -1;
2162 Py_DECREF(res);
2163 return 0;
2164}
2165
2166static int
2167slot_sq_contains(PyObject *self, PyObject *value)
2168{
2169 PyObject *res = PyObject_CallMethod(self, "__contains__", "O", value);
2170 int r;
2171
2172 if (res == NULL)
2173 return -1;
2174 r = PyInt_AsLong(res);
2175 Py_DECREF(res);
2176 return r;
2177}
2178
Guido van Rossumdc91b992001-08-08 22:26:22 +00002179SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2180SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002181
2182#define slot_mp_length slot_sq_length
2183
Guido van Rossumdc91b992001-08-08 22:26:22 +00002184SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185
2186static int
2187slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2188{
2189 PyObject *res;
2190
2191 if (value == NULL)
2192 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2193 else
2194 res = PyObject_CallMethod(self, "__setitem__",
2195 "OO", key, value);
2196 if (res == NULL)
2197 return -1;
2198 Py_DECREF(res);
2199 return 0;
2200}
2201
Guido van Rossumdc91b992001-08-08 22:26:22 +00002202SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2203SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2204SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2205SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2206SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2207SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2208
2209staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2210
2211SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2212 nb_power, "__pow__", "__rpow__")
2213
2214static PyObject *
2215slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2216{
2217 if (modulus == Py_None)
2218 return slot_nb_power_binary(self, other);
2219 /* Three-arg power doesn't use __rpow__ */
2220 return PyObject_CallMethod(self, "__pow__", "OO", other, modulus);
2221}
2222
2223SLOT0(slot_nb_negative, "__neg__")
2224SLOT0(slot_nb_positive, "__pos__")
2225SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002226
2227static int
2228slot_nb_nonzero(PyObject *self)
2229{
2230 PyObject *res = PyObject_CallMethod(self, "__nonzero__", "");
2231
2232 if (res == NULL)
2233 return -1;
2234 return (int)PyInt_AsLong(res);
2235}
2236
Guido van Rossumdc91b992001-08-08 22:26:22 +00002237SLOT0(slot_nb_invert, "__invert__")
2238SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2239SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2240SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2241SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2242SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002243/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002244SLOT0(slot_nb_int, "__int__")
2245SLOT0(slot_nb_long, "__long__")
2246SLOT0(slot_nb_float, "__float__")
2247SLOT0(slot_nb_oct, "__oct__")
2248SLOT0(slot_nb_hex, "__hex__")
2249SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2250SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2251SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2252SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2253SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2254SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2255SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2256SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2257SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2258SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2259SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2260SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2261 "__floordiv__", "__rfloordiv__")
2262SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2263SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2264SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002265
2266static int
2267slot_tp_compare(PyObject *self, PyObject *other)
2268{
2269 PyObject *res = PyObject_CallMethod(self, "__cmp__", "O", other);
2270 long r;
2271
2272 if (res == NULL)
2273 return -1;
2274 r = PyInt_AsLong(res);
2275 Py_DECREF(res);
2276 return (int)r;
2277}
2278
Guido van Rossumdc91b992001-08-08 22:26:22 +00002279SLOT0(slot_tp_repr, "__repr__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280
2281static long
2282slot_tp_hash(PyObject *self)
2283{
2284 PyObject *res = PyObject_CallMethod(self, "__hash__", "");
2285 long h;
2286
2287 if (res == NULL)
2288 return -1;
2289 h = PyInt_AsLong(res);
2290 if (h == -1 && !PyErr_Occurred())
2291 h = -2;
2292 return h;
2293}
2294
2295static PyObject *
2296slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2297{
2298 PyObject *meth = PyObject_GetAttrString(self, "__call__");
2299 PyObject *res;
2300
2301 if (meth == NULL)
2302 return NULL;
2303 res = PyObject_Call(meth, args, kwds);
2304 Py_DECREF(meth);
2305 return res;
2306}
2307
Guido van Rossumdc91b992001-08-08 22:26:22 +00002308SLOT0(slot_tp_str, "__str__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002309
2310static PyObject *
2311slot_tp_getattro(PyObject *self, PyObject *name)
2312{
2313 PyTypeObject *tp = self->ob_type;
2314 PyObject *dict = NULL;
2315 PyObject *getattr;
2316
2317 if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE)
2318 dict = tp->tp_dict;
2319 if (dict == NULL) {
2320 PyErr_Format(PyExc_SystemError,
2321 "'%.100s' type object has no __dict__???",
2322 tp->tp_name);
2323 return NULL;
2324 }
2325 getattr = PyDict_GetItemString(dict, "__getattr__");
2326 if (getattr == NULL) {
2327 PyErr_SetString(PyExc_AttributeError, "__getattr__");
2328 return NULL;
2329 }
2330 return PyObject_CallFunction(getattr, "OO", self, name);
2331}
2332
2333static int
2334slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2335{
2336 PyObject *res;
2337
2338 if (value == NULL)
2339 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2340 else
2341 res = PyObject_CallMethod(self, "__setattr__",
2342 "OO", name, value);
2343 if (res == NULL)
2344 return -1;
2345 Py_DECREF(res);
2346 return 0;
2347}
2348
2349/* Map rich comparison operators to their __xx__ namesakes */
2350static char *name_op[] = {
2351 "__lt__",
2352 "__le__",
2353 "__eq__",
2354 "__ne__",
2355 "__gt__",
2356 "__ge__",
2357};
2358
2359static PyObject *
2360slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2361{
2362 PyObject *meth = PyObject_GetAttrString(self, name_op[op]);
2363 PyObject *res;
2364
2365 if (meth == NULL)
2366 return NULL;
2367 res = PyObject_CallFunction(meth, "O", other);
2368 Py_DECREF(meth);
2369 return res;
2370}
2371
Guido van Rossumdc91b992001-08-08 22:26:22 +00002372SLOT0(slot_tp_iter, "__iter__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373
2374static PyObject *
2375slot_tp_iternext(PyObject *self)
2376{
2377 return PyObject_CallMethod(self, "next", "");
2378}
2379
Guido van Rossumdc91b992001-08-08 22:26:22 +00002380SLOT2(slot_tp_descr_get, "__get__", PyObject *, PyObject *, "OO")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381
2382static int
2383slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2384{
2385 PyObject *res = PyObject_CallMethod(self, "__set__",
2386 "OO", target, value);
2387 if (res == NULL)
2388 return -1;
2389 Py_DECREF(res);
2390 return 0;
2391}
2392
2393static int
2394slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2395{
2396 PyObject *meth = PyObject_GetAttrString(self, "__init__");
2397 PyObject *res;
2398
2399 if (meth == NULL)
2400 return -1;
2401 res = PyObject_Call(meth, args, kwds);
2402 Py_DECREF(meth);
2403 if (res == NULL)
2404 return -1;
2405 Py_DECREF(res);
2406 return 0;
2407}
2408
2409static PyObject *
2410slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2411{
2412 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2413 PyObject *newargs, *x;
2414 int i, n;
2415
2416 if (func == NULL)
2417 return NULL;
2418 assert(PyTuple_Check(args));
2419 n = PyTuple_GET_SIZE(args);
2420 newargs = PyTuple_New(n+1);
2421 if (newargs == NULL)
2422 return NULL;
2423 Py_INCREF(type);
2424 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2425 for (i = 0; i < n; i++) {
2426 x = PyTuple_GET_ITEM(args, i);
2427 Py_INCREF(x);
2428 PyTuple_SET_ITEM(newargs, i+1, x);
2429 }
2430 x = PyObject_Call(func, newargs, kwds);
2431 Py_DECREF(func);
2432 return x;
2433}
2434
Guido van Rossumf040ede2001-08-07 16:40:56 +00002435/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002436 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002437 The dict argument is the dictionary argument passed to type_new(),
2438 which is the local namespace of the class statement, in other
2439 words, it contains the methods. For each special method (like
2440 __repr__) defined in the dictionary, the corresponding function
2441 slot in the type object (like tp_repr) is set to a special function
2442 whose name is 'slot_' followed by the slot name and whose signature
2443 is whatever is required for that slot. These slot functions look
2444 up the corresponding method in the type's dictionary and call it.
2445 The slot functions have to take care of the various peculiarities
2446 of the mapping between slots and special methods, such as mapping
2447 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2448 etc.) or mapping multiple slots to a single method (sq_item,
2449 mp_subscript <--> __getitem__). */
2450
Tim Peters6d6c1a32001-08-02 04:15:00 +00002451static void
2452override_slots(PyTypeObject *type, PyObject *dict)
2453{
2454 PySequenceMethods *sq = type->tp_as_sequence;
2455 PyMappingMethods *mp = type->tp_as_mapping;
2456 PyNumberMethods *nb = type->tp_as_number;
2457
Guido van Rossumdc91b992001-08-08 22:26:22 +00002458#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002460 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461 }
2462
Guido van Rossumdc91b992001-08-08 22:26:22 +00002463#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002464 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002465 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002466 }
2467
Guido van Rossumdc91b992001-08-08 22:26:22 +00002468#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002469 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002470 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002471 }
2472
Guido van Rossumdc91b992001-08-08 22:26:22 +00002473#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002474 if (PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002475 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476 }
2477
Guido van Rossumdc91b992001-08-08 22:26:22 +00002478 SQSLOT("__len__", sq_length, slot_sq_length);
2479 SQSLOT("__add__", sq_concat, slot_sq_concat);
2480 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
2481 SQSLOT("__getitem__", sq_item, slot_sq_item);
2482 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
2483 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
2484 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
2485 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
2486 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
2487 SQSLOT("__contains__", sq_contains, slot_sq_contains);
2488 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
2489 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002490
Guido van Rossumdc91b992001-08-08 22:26:22 +00002491 MPSLOT("__len__", mp_length, slot_mp_length);
2492 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
2493 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
2494 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002495
Guido van Rossumdc91b992001-08-08 22:26:22 +00002496 NBSLOT("__add__", nb_add, slot_nb_add);
2497 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
2498 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
2499 NBSLOT("__div__", nb_divide, slot_nb_divide);
2500 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
2501 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
2502 NBSLOT("__pow__", nb_power, slot_nb_power);
2503 NBSLOT("__neg__", nb_negative, slot_nb_negative);
2504 NBSLOT("__pos__", nb_positive, slot_nb_positive);
2505 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
2506 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
2507 NBSLOT("__invert__", nb_invert, slot_nb_invert);
2508 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
2509 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
2510 NBSLOT("__and__", nb_and, slot_nb_and);
2511 NBSLOT("__xor__", nb_xor, slot_nb_xor);
2512 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002514 NBSLOT("__int__", nb_int, slot_nb_int);
2515 NBSLOT("__long__", nb_long, slot_nb_long);
2516 NBSLOT("__float__", nb_float, slot_nb_float);
2517 NBSLOT("__oct__", nb_oct, slot_nb_oct);
2518 NBSLOT("__hex__", nb_hex, slot_nb_hex);
2519 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
2520 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
2521 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
2522 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
2523 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
2524 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
2525 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
2526 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
2527 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
2528 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
2529 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
2530 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
2531 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
2532 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
2533 slot_nb_inplace_floor_divide);
2534 NBSLOT("__itruediv__", nb_inplace_true_divide,
2535 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002536
2537 if (PyDict_GetItemString(dict, "__str__") ||
2538 PyDict_GetItemString(dict, "__repr__"))
2539 type->tp_print = NULL;
2540
Guido van Rossumdc91b992001-08-08 22:26:22 +00002541 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
2542 TPSLOT("__repr__", tp_repr, slot_tp_repr);
2543 TPSLOT("__hash__", tp_hash, slot_tp_hash);
2544 TPSLOT("__call__", tp_call, slot_tp_call);
2545 TPSLOT("__str__", tp_str, slot_tp_str);
2546 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
2547 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
2548 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
2549 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
2550 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
2551 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
2552 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
2553 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
2554 TPSLOT("__iter__", tp_iter, slot_tp_iter);
2555 TPSLOT("next", tp_iternext, slot_tp_iternext);
2556 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
2557 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
2558 TPSLOT("__init__", tp_init, slot_tp_init);
2559 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002560}