blob: 30e693ab91a50c4f11f2773d1969ab2f0f368e49 [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 */
Guido van Rossum8e248182001-08-12 05:17:56 +0000670 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
671 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000672
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673 return (PyObject *)type;
674}
675
676/* Internal API to look for a name through the MRO.
677 This returns a borrowed reference, and doesn't set an exception! */
678PyObject *
679_PyType_Lookup(PyTypeObject *type, PyObject *name)
680{
681 int i, n;
682 PyObject *mro, *res, *dict;
683
684 /* For static types, look in tp_dict */
685 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
686 dict = type->tp_dict;
687 assert(dict && PyDict_Check(dict));
688 return PyDict_GetItem(dict, name);
689 }
690
691 /* For dynamic types, look in tp_defined of types in MRO */
692 mro = type->tp_mro;
693 assert(PyTuple_Check(mro));
694 n = PyTuple_GET_SIZE(mro);
695 for (i = 0; i < n; i++) {
696 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
697 assert(PyType_Check(type));
698 dict = type->tp_defined;
699 assert(dict && PyDict_Check(dict));
700 res = PyDict_GetItem(dict, name);
701 if (res != NULL)
702 return res;
703 }
704 return NULL;
705}
706
707/* This is similar to PyObject_GenericGetAttr(),
708 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
709static PyObject *
710type_getattro(PyTypeObject *type, PyObject *name)
711{
712 PyTypeObject *metatype = type->ob_type;
713 PyObject *descr, *res;
714 descrgetfunc f;
715
716 /* Initialize this type (we'll assume the metatype is initialized) */
717 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000718 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719 return NULL;
720 }
721
722 /* Get a descriptor from the metatype */
723 descr = _PyType_Lookup(metatype, name);
724 f = NULL;
725 if (descr != NULL) {
726 f = descr->ob_type->tp_descr_get;
727 if (f != NULL && PyDescr_IsData(descr))
728 return f(descr,
729 (PyObject *)type, (PyObject *)metatype);
730 }
731
732 /* Look in tp_defined of this type and its bases */
733 res = _PyType_Lookup(type, name);
734 if (res != NULL) {
735 f = res->ob_type->tp_descr_get;
736 if (f != NULL)
737 return f(res, (PyObject *)NULL, (PyObject *)type);
738 Py_INCREF(res);
739 return res;
740 }
741
742 /* Use the descriptor from the metatype */
743 if (f != NULL) {
744 res = f(descr, (PyObject *)type, (PyObject *)metatype);
745 return res;
746 }
747 if (descr != NULL) {
748 Py_INCREF(descr);
749 return descr;
750 }
751
752 /* Give up */
753 PyErr_Format(PyExc_AttributeError,
754 "type object '%.50s' has no attribute '%.400s'",
755 type->tp_name, PyString_AS_STRING(name));
756 return NULL;
757}
758
759static int
760type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
761{
762 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
763 return PyObject_GenericSetAttr((PyObject *)type, name, value);
764 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
765 return -1;
766}
767
768static void
769type_dealloc(PyTypeObject *type)
770{
771 etype *et;
772
773 /* Assert this is a heap-allocated type object */
774 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
775 et = (etype *)type;
776 Py_XDECREF(type->tp_base);
777 Py_XDECREF(type->tp_dict);
778 Py_XDECREF(type->tp_bases);
779 Py_XDECREF(type->tp_mro);
780 Py_XDECREF(type->tp_defined);
781 /* XXX more? */
782 Py_XDECREF(et->name);
783 Py_XDECREF(et->slots);
784 type->ob_type->tp_free((PyObject *)type);
785}
786
787static PyMethodDef type_methods[] = {
788 {"mro", mro_external, METH_VARARGS,
789 "mro() -> list\nreturn a type's method resolution order"},
790 {0}
791};
792
793static char type_doc[] =
794"type(object) -> the object's type\n"
795"type(name, bases, dict) -> a new type";
796
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000797PyTypeObject PyType_Type = {
798 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000799 0, /* ob_size */
800 "type", /* tp_name */
801 sizeof(etype), /* tp_basicsize */
802 sizeof(struct memberlist), /* tp_itemsize */
803 (destructor)type_dealloc, /* tp_dealloc */
804 0, /* tp_print */
805 0, /* tp_getattr */
806 0, /* tp_setattr */
807 type_compare, /* tp_compare */
808 (reprfunc)type_repr, /* tp_repr */
809 0, /* tp_as_number */
810 0, /* tp_as_sequence */
811 0, /* tp_as_mapping */
812 (hashfunc)_Py_HashPointer, /* tp_hash */
813 (ternaryfunc)type_call, /* tp_call */
814 0, /* tp_str */
815 (getattrofunc)type_getattro, /* tp_getattro */
816 (setattrofunc)type_setattro, /* tp_setattro */
817 0, /* tp_as_buffer */
818 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
819 type_doc, /* tp_doc */
820 0, /* tp_traverse */
821 0, /* tp_clear */
822 0, /* tp_richcompare */
823 0, /* tp_weaklistoffset */
824 0, /* tp_iter */
825 0, /* tp_iternext */
826 type_methods, /* tp_methods */
827 type_members, /* tp_members */
828 type_getsets, /* tp_getset */
829 0, /* tp_base */
830 0, /* tp_dict */
831 0, /* tp_descr_get */
832 0, /* tp_descr_set */
833 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
834 0, /* tp_init */
835 0, /* tp_alloc */
836 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000838
839
840/* The base type of all types (eventually)... except itself. */
841
842static int
843object_init(PyObject *self, PyObject *args, PyObject *kwds)
844{
845 return 0;
846}
847
848static void
849object_dealloc(PyObject *self)
850{
851 self->ob_type->tp_free(self);
852}
853
Guido van Rossum8e248182001-08-12 05:17:56 +0000854static PyObject *
855object_repr(PyObject *self)
856{
857 char buf[120];
858
859 sprintf(buf, "<%.80s object at %p>", self->ob_type->tp_name, self);
860 return PyString_FromString(buf);
861}
862
Guido van Rossumb8f63662001-08-15 23:57:02 +0000863static PyObject *
864object_str(PyObject *self)
865{
866 unaryfunc f;
867
868 f = self->ob_type->tp_repr;
869 if (f == NULL)
870 f = object_repr;
871 return f(self);
872}
873
Guido van Rossum8e248182001-08-12 05:17:56 +0000874static long
875object_hash(PyObject *self)
876{
877 return _Py_HashPointer(self);
878}
Guido van Rossum8e248182001-08-12 05:17:56 +0000879
Tim Peters6d6c1a32001-08-02 04:15:00 +0000880static void
881object_free(PyObject *self)
882{
883 PyObject_Del(self);
884}
885
886static struct memberlist object_members[] = {
887 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
888 {0}
889};
890
891PyTypeObject PyBaseObject_Type = {
892 PyObject_HEAD_INIT(&PyType_Type)
893 0, /* ob_size */
894 "object", /* tp_name */
895 sizeof(PyObject), /* tp_basicsize */
896 0, /* tp_itemsize */
897 (destructor)object_dealloc, /* tp_dealloc */
898 0, /* tp_print */
899 0, /* tp_getattr */
900 0, /* tp_setattr */
901 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +0000902 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000903 0, /* tp_as_number */
904 0, /* tp_as_sequence */
905 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +0000906 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000907 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +0000908 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000909 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +0000910 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000911 0, /* tp_as_buffer */
912 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
913 "The most base type", /* tp_doc */
914 0, /* tp_traverse */
915 0, /* tp_clear */
916 0, /* tp_richcompare */
917 0, /* tp_weaklistoffset */
918 0, /* tp_iter */
919 0, /* tp_iternext */
920 0, /* tp_methods */
921 object_members, /* tp_members */
922 0, /* tp_getset */
923 0, /* tp_base */
924 0, /* tp_dict */
925 0, /* tp_descr_get */
926 0, /* tp_descr_set */
927 0, /* tp_dictoffset */
928 object_init, /* tp_init */
929 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +0000930 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000931 object_free, /* tp_free */
932};
933
934
935/* Initialize the __dict__ in a type object */
936
937static int
938add_methods(PyTypeObject *type, PyMethodDef *meth)
939{
940 PyObject *dict = type->tp_defined;
941
942 for (; meth->ml_name != NULL; meth++) {
943 PyObject *descr;
944 if (PyDict_GetItemString(dict, meth->ml_name))
945 continue;
946 descr = PyDescr_NewMethod(type, meth);
947 if (descr == NULL)
948 return -1;
949 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
950 return -1;
951 Py_DECREF(descr);
952 }
953 return 0;
954}
955
956static int
Tim Peters6d6c1a32001-08-02 04:15:00 +0000957add_members(PyTypeObject *type, struct memberlist *memb)
958{
959 PyObject *dict = type->tp_defined;
960
961 for (; memb->name != NULL; memb++) {
962 PyObject *descr;
963 if (PyDict_GetItemString(dict, memb->name))
964 continue;
965 descr = PyDescr_NewMember(type, memb);
966 if (descr == NULL)
967 return -1;
968 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
969 return -1;
970 Py_DECREF(descr);
971 }
972 return 0;
973}
974
975static int
976add_getset(PyTypeObject *type, struct getsetlist *gsp)
977{
978 PyObject *dict = type->tp_defined;
979
980 for (; gsp->name != NULL; gsp++) {
981 PyObject *descr;
982 if (PyDict_GetItemString(dict, gsp->name))
983 continue;
984 descr = PyDescr_NewGetSet(type, gsp);
985
986 if (descr == NULL)
987 return -1;
988 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
989 return -1;
990 Py_DECREF(descr);
991 }
992 return 0;
993}
994
Guido van Rossum13d52f02001-08-10 21:24:08 +0000995static void
996inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997{
998 int oldsize, newsize;
999
Guido van Rossum13d52f02001-08-10 21:24:08 +00001000 /* Special flag magic */
1001 if (!type->tp_as_buffer && base->tp_as_buffer) {
1002 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1003 type->tp_flags |=
1004 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1005 }
1006 if (!type->tp_as_sequence && base->tp_as_sequence) {
1007 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1008 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1009 }
1010 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1011 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1012 if ((!type->tp_as_number && base->tp_as_number) ||
1013 (!type->tp_as_sequence && base->tp_as_sequence)) {
1014 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1015 if (!type->tp_as_number && !type->tp_as_sequence) {
1016 type->tp_flags |= base->tp_flags &
1017 Py_TPFLAGS_HAVE_INPLACEOPS;
1018 }
1019 }
1020 /* Wow */
1021 }
1022 if (!type->tp_as_number && base->tp_as_number) {
1023 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1024 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1025 }
1026
1027 /* Copying basicsize is connected to the GC flags */
1028 oldsize = PyType_BASICSIZE(base);
1029 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1030 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1031 (base->tp_flags & Py_TPFLAGS_GC) &&
1032 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1033 (!type->tp_traverse && !type->tp_clear)) {
1034 type->tp_flags |= Py_TPFLAGS_GC;
1035 if (type->tp_traverse == NULL)
1036 type->tp_traverse = base->tp_traverse;
1037 if (type->tp_clear == NULL)
1038 type->tp_clear = base->tp_clear;
1039 }
1040 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1041 if (base != &PyBaseObject_Type ||
1042 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1043 if (type->tp_new == NULL)
1044 type->tp_new = base->tp_new;
1045 }
1046 }
1047 PyType_SET_BASICSIZE(type, newsize);
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001048
1049 /* Copy other non-function slots */
1050
1051#undef COPYVAL
1052#define COPYVAL(SLOT) \
1053 if (type->SLOT == 0) type->SLOT = base->SLOT
1054
1055 COPYVAL(tp_itemsize);
1056 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1057 COPYVAL(tp_weaklistoffset);
1058 }
1059 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1060 COPYVAL(tp_dictoffset);
1061 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001062}
1063
1064static void
1065inherit_slots(PyTypeObject *type, PyTypeObject *base)
1066{
1067 PyTypeObject *basebase;
1068
1069#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070#undef COPYSLOT
1071#undef COPYNUM
1072#undef COPYSEQ
1073#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001074
1075#define SLOTDEFINED(SLOT) \
1076 (base->SLOT != 0 && \
1077 (basebase == NULL || base->SLOT != basebase->SLOT))
1078
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001080 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081
1082#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1083#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1084#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1085
Guido van Rossum13d52f02001-08-10 21:24:08 +00001086 /* This won't inherit indirect slots (from tp_as_number etc.)
1087 if type doesn't provide the space. */
1088
1089 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1090 basebase = base->tp_base;
1091 if (basebase->tp_as_number == NULL)
1092 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 COPYNUM(nb_add);
1094 COPYNUM(nb_subtract);
1095 COPYNUM(nb_multiply);
1096 COPYNUM(nb_divide);
1097 COPYNUM(nb_remainder);
1098 COPYNUM(nb_divmod);
1099 COPYNUM(nb_power);
1100 COPYNUM(nb_negative);
1101 COPYNUM(nb_positive);
1102 COPYNUM(nb_absolute);
1103 COPYNUM(nb_nonzero);
1104 COPYNUM(nb_invert);
1105 COPYNUM(nb_lshift);
1106 COPYNUM(nb_rshift);
1107 COPYNUM(nb_and);
1108 COPYNUM(nb_xor);
1109 COPYNUM(nb_or);
1110 COPYNUM(nb_coerce);
1111 COPYNUM(nb_int);
1112 COPYNUM(nb_long);
1113 COPYNUM(nb_float);
1114 COPYNUM(nb_oct);
1115 COPYNUM(nb_hex);
1116 COPYNUM(nb_inplace_add);
1117 COPYNUM(nb_inplace_subtract);
1118 COPYNUM(nb_inplace_multiply);
1119 COPYNUM(nb_inplace_divide);
1120 COPYNUM(nb_inplace_remainder);
1121 COPYNUM(nb_inplace_power);
1122 COPYNUM(nb_inplace_lshift);
1123 COPYNUM(nb_inplace_rshift);
1124 COPYNUM(nb_inplace_and);
1125 COPYNUM(nb_inplace_xor);
1126 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001127 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1128 COPYNUM(nb_true_divide);
1129 COPYNUM(nb_floor_divide);
1130 COPYNUM(nb_inplace_true_divide);
1131 COPYNUM(nb_inplace_floor_divide);
1132 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133 }
1134
Guido van Rossum13d52f02001-08-10 21:24:08 +00001135 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1136 basebase = base->tp_base;
1137 if (basebase->tp_as_sequence == NULL)
1138 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 COPYSEQ(sq_length);
1140 COPYSEQ(sq_concat);
1141 COPYSEQ(sq_repeat);
1142 COPYSEQ(sq_item);
1143 COPYSEQ(sq_slice);
1144 COPYSEQ(sq_ass_item);
1145 COPYSEQ(sq_ass_slice);
1146 COPYSEQ(sq_contains);
1147 COPYSEQ(sq_inplace_concat);
1148 COPYSEQ(sq_inplace_repeat);
1149 }
1150
Guido van Rossum13d52f02001-08-10 21:24:08 +00001151 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1152 basebase = base->tp_base;
1153 if (basebase->tp_as_mapping == NULL)
1154 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 COPYMAP(mp_length);
1156 COPYMAP(mp_subscript);
1157 COPYMAP(mp_ass_subscript);
1158 }
1159
Guido van Rossum13d52f02001-08-10 21:24:08 +00001160 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162 COPYSLOT(tp_dealloc);
1163 COPYSLOT(tp_print);
1164 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1165 type->tp_getattr = base->tp_getattr;
1166 type->tp_getattro = base->tp_getattro;
1167 }
1168 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1169 type->tp_setattr = base->tp_setattr;
1170 type->tp_setattro = base->tp_setattro;
1171 }
1172 /* tp_compare see tp_richcompare */
1173 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001174 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175 COPYSLOT(tp_call);
1176 COPYSLOT(tp_str);
1177 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001179 if (type->tp_compare == NULL &&
1180 type->tp_richcompare == NULL &&
1181 type->tp_hash == NULL)
1182 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 type->tp_compare = base->tp_compare;
1184 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001185 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001186 }
1187 }
1188 else {
1189 COPYSLOT(tp_compare);
1190 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1192 COPYSLOT(tp_iter);
1193 COPYSLOT(tp_iternext);
1194 }
1195 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1196 COPYSLOT(tp_descr_get);
1197 COPYSLOT(tp_descr_set);
1198 COPYSLOT(tp_dictoffset);
1199 COPYSLOT(tp_init);
1200 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201 COPYSLOT(tp_free);
1202 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203}
1204
Guido van Rossum13d52f02001-08-10 21:24:08 +00001205staticforward int add_operators(PyTypeObject *);
1206
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001208PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209{
1210 PyObject *dict, *bases, *x;
1211 PyTypeObject *base;
1212 int i, n;
1213
Guido van Rossumd614f972001-08-10 17:39:49 +00001214 if (type->tp_flags & Py_TPFLAGS_READY) {
1215 assert(type->tp_dict != NULL);
1216 return 0;
1217 }
1218 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1219 assert(type->tp_dict == NULL);
1220
1221 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001222
1223 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1224 base = type->tp_base;
1225 if (base == NULL && type != &PyBaseObject_Type)
1226 base = type->tp_base = &PyBaseObject_Type;
1227
1228 /* Initialize tp_bases */
1229 bases = type->tp_bases;
1230 if (bases == NULL) {
1231 if (base == NULL)
1232 bases = PyTuple_New(0);
1233 else
1234 bases = Py_BuildValue("(O)", base);
1235 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001236 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 type->tp_bases = bases;
1238 }
1239
1240 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001241 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001242 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001243 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 }
1245
1246 /* Initialize tp_defined */
1247 dict = type->tp_defined;
1248 if (dict == NULL) {
1249 dict = PyDict_New();
1250 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001251 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 type->tp_defined = dict;
1253 }
1254
1255 /* Add type-specific descriptors to tp_defined */
1256 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001257 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258 if (type->tp_methods != NULL) {
1259 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001260 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001261 }
1262 if (type->tp_members != NULL) {
1263 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001264 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 }
1266 if (type->tp_getset != NULL) {
1267 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001268 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001269 }
1270
1271 /* Temporarily make tp_dict the same object as tp_defined.
1272 (This is needed to call mro(), and can stay this way for
1273 dynamic types). */
1274 Py_INCREF(type->tp_defined);
1275 type->tp_dict = type->tp_defined;
1276
1277 /* Calculate method resolution order */
1278 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001279 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001280 }
1281
Guido van Rossum13d52f02001-08-10 21:24:08 +00001282 /* Inherit special flags from dominant base */
1283 if (type->tp_base != NULL)
1284 inherit_special(type, type->tp_base);
1285
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001287 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001288 /* For a dynamic type, all slots are overridden */
1289 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001290 }
1291 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001293 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001295 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001297 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298 bases = type->tp_mro;
1299 assert(bases != NULL);
1300 assert(PyTuple_Check(bases));
1301 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001302 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1304 assert(PyType_Check(base));
1305 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001306 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001307 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001308 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309 }
1310 }
1311
Guido van Rossum13d52f02001-08-10 21:24:08 +00001312 /* Some more special stuff */
1313 base = type->tp_base;
1314 if (base != NULL) {
1315 if (type->tp_as_number == NULL)
1316 type->tp_as_number = base->tp_as_number;
1317 if (type->tp_as_sequence == NULL)
1318 type->tp_as_sequence = base->tp_as_sequence;
1319 if (type->tp_as_mapping == NULL)
1320 type->tp_as_mapping = base->tp_as_mapping;
1321 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322
Guido van Rossum13d52f02001-08-10 21:24:08 +00001323 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001324 assert(type->tp_dict != NULL);
1325 type->tp_flags =
1326 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001328
1329 error:
1330 type->tp_flags &= ~Py_TPFLAGS_READYING;
1331 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332}
1333
1334
1335/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1336
1337/* There's a wrapper *function* for each distinct function typedef used
1338 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1339 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1340 Most tables have only one entry; the tables for binary operators have two
1341 entries, one regular and one with reversed arguments. */
1342
1343static PyObject *
1344wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1345{
1346 inquiry func = (inquiry)wrapped;
1347 int res;
1348
1349 if (!PyArg_ParseTuple(args, ""))
1350 return NULL;
1351 res = (*func)(self);
1352 if (res == -1 && PyErr_Occurred())
1353 return NULL;
1354 return PyInt_FromLong((long)res);
1355}
1356
1357static struct wrapperbase tab_len[] = {
1358 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1359 {0}
1360};
1361
1362static PyObject *
1363wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1364{
1365 binaryfunc func = (binaryfunc)wrapped;
1366 PyObject *other;
1367
1368 if (!PyArg_ParseTuple(args, "O", &other))
1369 return NULL;
1370 return (*func)(self, other);
1371}
1372
1373static PyObject *
1374wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1375{
1376 binaryfunc func = (binaryfunc)wrapped;
1377 PyObject *other;
1378
1379 if (!PyArg_ParseTuple(args, "O", &other))
1380 return NULL;
1381 return (*func)(other, self);
1382}
1383
1384#undef BINARY
1385#define BINARY(NAME, OP) \
1386static struct wrapperbase tab_##NAME[] = { \
1387 {"__" #NAME "__", \
1388 (wrapperfunc)wrap_binaryfunc, \
1389 "x.__" #NAME "__(y) <==> " #OP}, \
1390 {"__r" #NAME "__", \
1391 (wrapperfunc)wrap_binaryfunc_r, \
1392 "y.__r" #NAME "__(x) <==> " #OP}, \
1393 {0} \
1394}
1395
1396BINARY(add, "x+y");
1397BINARY(sub, "x-y");
1398BINARY(mul, "x*y");
1399BINARY(div, "x/y");
1400BINARY(mod, "x%y");
1401BINARY(divmod, "divmod(x,y)");
1402BINARY(lshift, "x<<y");
1403BINARY(rshift, "x>>y");
1404BINARY(and, "x&y");
1405BINARY(xor, "x^y");
1406BINARY(or, "x|y");
1407
1408static PyObject *
1409wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1410{
1411 ternaryfunc func = (ternaryfunc)wrapped;
1412 PyObject *other;
1413 PyObject *third = Py_None;
1414
1415 /* Note: This wrapper only works for __pow__() */
1416
1417 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1418 return NULL;
1419 return (*func)(self, other, third);
1420}
1421
1422#undef TERNARY
1423#define TERNARY(NAME, OP) \
1424static struct wrapperbase tab_##NAME[] = { \
1425 {"__" #NAME "__", \
1426 (wrapperfunc)wrap_ternaryfunc, \
1427 "x.__" #NAME "__(y, z) <==> " #OP}, \
1428 {"__r" #NAME "__", \
1429 (wrapperfunc)wrap_ternaryfunc, \
1430 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1431 {0} \
1432}
1433
1434TERNARY(pow, "(x**y) % z");
1435
1436#undef UNARY
1437#define UNARY(NAME, OP) \
1438static struct wrapperbase tab_##NAME[] = { \
1439 {"__" #NAME "__", \
1440 (wrapperfunc)wrap_unaryfunc, \
1441 "x.__" #NAME "__() <==> " #OP}, \
1442 {0} \
1443}
1444
1445static PyObject *
1446wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1447{
1448 unaryfunc func = (unaryfunc)wrapped;
1449
1450 if (!PyArg_ParseTuple(args, ""))
1451 return NULL;
1452 return (*func)(self);
1453}
1454
1455UNARY(neg, "-x");
1456UNARY(pos, "+x");
1457UNARY(abs, "abs(x)");
1458UNARY(nonzero, "x != 0");
1459UNARY(invert, "~x");
1460UNARY(int, "int(x)");
1461UNARY(long, "long(x)");
1462UNARY(float, "float(x)");
1463UNARY(oct, "oct(x)");
1464UNARY(hex, "hex(x)");
1465
1466#undef IBINARY
1467#define IBINARY(NAME, OP) \
1468static struct wrapperbase tab_##NAME[] = { \
1469 {"__" #NAME "__", \
1470 (wrapperfunc)wrap_binaryfunc, \
1471 "x.__" #NAME "__(y) <==> " #OP}, \
1472 {0} \
1473}
1474
1475IBINARY(iadd, "x+=y");
1476IBINARY(isub, "x-=y");
1477IBINARY(imul, "x*=y");
1478IBINARY(idiv, "x/=y");
1479IBINARY(imod, "x%=y");
1480IBINARY(ilshift, "x<<=y");
1481IBINARY(irshift, "x>>=y");
1482IBINARY(iand, "x&=y");
1483IBINARY(ixor, "x^=y");
1484IBINARY(ior, "x|=y");
1485
1486#undef ITERNARY
1487#define ITERNARY(NAME, OP) \
1488static struct wrapperbase tab_##NAME[] = { \
1489 {"__" #NAME "__", \
1490 (wrapperfunc)wrap_ternaryfunc, \
1491 "x.__" #NAME "__(y) <==> " #OP}, \
1492 {0} \
1493}
1494
1495ITERNARY(ipow, "x = (x**y) % z");
1496
1497static struct wrapperbase tab_getitem[] = {
1498 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1499 "x.__getitem__(y) <==> x[y]"},
1500 {0}
1501};
1502
1503static PyObject *
1504wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1505{
1506 intargfunc func = (intargfunc)wrapped;
1507 int i;
1508
1509 if (!PyArg_ParseTuple(args, "i", &i))
1510 return NULL;
1511 return (*func)(self, i);
1512}
1513
1514static struct wrapperbase tab_mul_int[] = {
1515 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1516 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1517 {0}
1518};
1519
1520static struct wrapperbase tab_concat[] = {
1521 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1522 {0}
1523};
1524
1525static struct wrapperbase tab_imul_int[] = {
1526 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1527 {0}
1528};
1529
1530static struct wrapperbase tab_getitem_int[] = {
1531 {"__getitem__", (wrapperfunc)wrap_intargfunc,
1532 "x.__getitem__(i) <==> x[i]"},
1533 {0}
1534};
1535
1536static PyObject *
1537wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1538{
1539 intintargfunc func = (intintargfunc)wrapped;
1540 int i, j;
1541
1542 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1543 return NULL;
1544 return (*func)(self, i, j);
1545}
1546
1547static struct wrapperbase tab_getslice[] = {
1548 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1549 "x.__getslice__(i, j) <==> x[i:j]"},
1550 {0}
1551};
1552
1553static PyObject *
1554wrap_intobjargproc(PyObject *self, PyObject *args, void *wrapped)
1555{
1556 intobjargproc func = (intobjargproc)wrapped;
1557 int i, res;
1558 PyObject *value;
1559
1560 if (!PyArg_ParseTuple(args, "iO", &i, &value))
1561 return NULL;
1562 res = (*func)(self, i, value);
1563 if (res == -1 && PyErr_Occurred())
1564 return NULL;
1565 Py_INCREF(Py_None);
1566 return Py_None;
1567}
1568
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001569static PyObject *
1570wrap_delitem_int(PyObject *self, PyObject *args, void *wrapped)
1571{
1572 intobjargproc func = (intobjargproc)wrapped;
1573 int i, res;
1574
1575 if (!PyArg_ParseTuple(args, "i", &i))
1576 return NULL;
1577 res = (*func)(self, i, NULL);
1578 if (res == -1 && PyErr_Occurred())
1579 return NULL;
1580 Py_INCREF(Py_None);
1581 return Py_None;
1582}
1583
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584static struct wrapperbase tab_setitem_int[] = {
1585 {"__setitem__", (wrapperfunc)wrap_intobjargproc,
1586 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001587 {"__delitem__", (wrapperfunc)wrap_delitem_int,
1588 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 {0}
1590};
1591
1592static PyObject *
1593wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1594{
1595 intintobjargproc func = (intintobjargproc)wrapped;
1596 int i, j, res;
1597 PyObject *value;
1598
1599 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1600 return NULL;
1601 res = (*func)(self, i, j, value);
1602 if (res == -1 && PyErr_Occurred())
1603 return NULL;
1604 Py_INCREF(Py_None);
1605 return Py_None;
1606}
1607
1608static struct wrapperbase tab_setslice[] = {
1609 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1610 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1611 {0}
1612};
1613
1614/* XXX objobjproc is a misnomer; should be objargpred */
1615static PyObject *
1616wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1617{
1618 objobjproc func = (objobjproc)wrapped;
1619 int res;
1620 PyObject *value;
1621
1622 if (!PyArg_ParseTuple(args, "O", &value))
1623 return NULL;
1624 res = (*func)(self, value);
1625 if (res == -1 && PyErr_Occurred())
1626 return NULL;
1627 return PyInt_FromLong((long)res);
1628}
1629
1630static struct wrapperbase tab_contains[] = {
1631 {"__contains__", (wrapperfunc)wrap_objobjproc,
1632 "x.__contains__(y) <==> y in x"},
1633 {0}
1634};
1635
1636static PyObject *
1637wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1638{
1639 objobjargproc func = (objobjargproc)wrapped;
1640 int res;
1641 PyObject *key, *value;
1642
1643 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1644 return NULL;
1645 res = (*func)(self, key, value);
1646 if (res == -1 && PyErr_Occurred())
1647 return NULL;
1648 Py_INCREF(Py_None);
1649 return Py_None;
1650}
1651
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001652static PyObject *
1653wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1654{
1655 objobjargproc func = (objobjargproc)wrapped;
1656 int res;
1657 PyObject *key;
1658
1659 if (!PyArg_ParseTuple(args, "O", &key))
1660 return NULL;
1661 res = (*func)(self, key, NULL);
1662 if (res == -1 && PyErr_Occurred())
1663 return NULL;
1664 Py_INCREF(Py_None);
1665 return Py_None;
1666}
1667
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668static struct wrapperbase tab_setitem[] = {
1669 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1670 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001671 {"__delitem__", (wrapperfunc)wrap_delitem,
1672 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673 {0}
1674};
1675
1676static PyObject *
1677wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1678{
1679 cmpfunc func = (cmpfunc)wrapped;
1680 int res;
1681 PyObject *other;
1682
1683 if (!PyArg_ParseTuple(args, "O", &other))
1684 return NULL;
1685 res = (*func)(self, other);
1686 if (PyErr_Occurred())
1687 return NULL;
1688 return PyInt_FromLong((long)res);
1689}
1690
1691static struct wrapperbase tab_cmp[] = {
1692 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1693 "x.__cmp__(y) <==> cmp(x,y)"},
1694 {0}
1695};
1696
1697static struct wrapperbase tab_repr[] = {
1698 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1699 "x.__repr__() <==> repr(x)"},
1700 {0}
1701};
1702
1703static struct wrapperbase tab_getattr[] = {
1704 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1705 "x.__getattr__('name') <==> x.name"},
1706 {0}
1707};
1708
1709static PyObject *
1710wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1711{
1712 setattrofunc func = (setattrofunc)wrapped;
1713 int res;
1714 PyObject *name, *value;
1715
1716 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1717 return NULL;
1718 res = (*func)(self, name, value);
1719 if (res < 0)
1720 return NULL;
1721 Py_INCREF(Py_None);
1722 return Py_None;
1723}
1724
1725static PyObject *
1726wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1727{
1728 setattrofunc func = (setattrofunc)wrapped;
1729 int res;
1730 PyObject *name;
1731
1732 if (!PyArg_ParseTuple(args, "O", &name))
1733 return NULL;
1734 res = (*func)(self, name, NULL);
1735 if (res < 0)
1736 return NULL;
1737 Py_INCREF(Py_None);
1738 return Py_None;
1739}
1740
1741static struct wrapperbase tab_setattr[] = {
1742 {"__setattr__", (wrapperfunc)wrap_setattr,
1743 "x.__setattr__('name', value) <==> x.name = value"},
1744 {"__delattr__", (wrapperfunc)wrap_delattr,
1745 "x.__delattr__('name') <==> del x.name"},
1746 {0}
1747};
1748
1749static PyObject *
1750wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1751{
1752 hashfunc func = (hashfunc)wrapped;
1753 long res;
1754
1755 if (!PyArg_ParseTuple(args, ""))
1756 return NULL;
1757 res = (*func)(self);
1758 if (res == -1 && PyErr_Occurred())
1759 return NULL;
1760 return PyInt_FromLong(res);
1761}
1762
1763static struct wrapperbase tab_hash[] = {
1764 {"__hash__", (wrapperfunc)wrap_hashfunc,
1765 "x.__hash__() <==> hash(x)"},
1766 {0}
1767};
1768
1769static PyObject *
1770wrap_call(PyObject *self, PyObject *args, void *wrapped)
1771{
1772 ternaryfunc func = (ternaryfunc)wrapped;
1773
1774 /* XXX What about keyword arguments? */
1775 return (*func)(self, args, NULL);
1776}
1777
1778static struct wrapperbase tab_call[] = {
1779 {"__call__", (wrapperfunc)wrap_call,
1780 "x.__call__(...) <==> x(...)"},
1781 {0}
1782};
1783
1784static struct wrapperbase tab_str[] = {
1785 {"__str__", (wrapperfunc)wrap_unaryfunc,
1786 "x.__str__() <==> str(x)"},
1787 {0}
1788};
1789
1790static PyObject *
1791wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1792{
1793 richcmpfunc func = (richcmpfunc)wrapped;
1794 PyObject *other;
1795
1796 if (!PyArg_ParseTuple(args, "O", &other))
1797 return NULL;
1798 return (*func)(self, other, op);
1799}
1800
1801#undef RICHCMP_WRAPPER
1802#define RICHCMP_WRAPPER(NAME, OP) \
1803static PyObject * \
1804richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1805{ \
1806 return wrap_richcmpfunc(self, args, wrapped, OP); \
1807}
1808
Jack Jansen8e938b42001-08-08 15:29:49 +00001809RICHCMP_WRAPPER(lt, Py_LT)
1810RICHCMP_WRAPPER(le, Py_LE)
1811RICHCMP_WRAPPER(eq, Py_EQ)
1812RICHCMP_WRAPPER(ne, Py_NE)
1813RICHCMP_WRAPPER(gt, Py_GT)
1814RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815
1816#undef RICHCMP_ENTRY
1817#define RICHCMP_ENTRY(NAME, EXPR) \
1818 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1819 "x.__" #NAME "__(y) <==> " EXPR}
1820
1821static struct wrapperbase tab_richcmp[] = {
1822 RICHCMP_ENTRY(lt, "x<y"),
1823 RICHCMP_ENTRY(le, "x<=y"),
1824 RICHCMP_ENTRY(eq, "x==y"),
1825 RICHCMP_ENTRY(ne, "x!=y"),
1826 RICHCMP_ENTRY(gt, "x>y"),
1827 RICHCMP_ENTRY(ge, "x>=y"),
1828 {0}
1829};
1830
1831static struct wrapperbase tab_iter[] = {
1832 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
1833 {0}
1834};
1835
1836static PyObject *
1837wrap_next(PyObject *self, PyObject *args, void *wrapped)
1838{
1839 unaryfunc func = (unaryfunc)wrapped;
1840 PyObject *res;
1841
1842 if (!PyArg_ParseTuple(args, ""))
1843 return NULL;
1844 res = (*func)(self);
1845 if (res == NULL && !PyErr_Occurred())
1846 PyErr_SetNone(PyExc_StopIteration);
1847 return res;
1848}
1849
1850static struct wrapperbase tab_next[] = {
1851 {"next", (wrapperfunc)wrap_next,
1852 "x.next() -> the next value, or raise StopIteration"},
1853 {0}
1854};
1855
1856static PyObject *
1857wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
1858{
1859 descrgetfunc func = (descrgetfunc)wrapped;
1860 PyObject *obj;
1861 PyObject *type = NULL;
1862
1863 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
1864 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 return (*func)(self, obj, type);
1866}
1867
1868static struct wrapperbase tab_descr_get[] = {
1869 {"__get__", (wrapperfunc)wrap_descr_get,
1870 "descr.__get__(obj, type) -> value"},
1871 {0}
1872};
1873
1874static PyObject *
1875wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
1876{
1877 descrsetfunc func = (descrsetfunc)wrapped;
1878 PyObject *obj, *value;
1879 int ret;
1880
1881 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
1882 return NULL;
1883 ret = (*func)(self, obj, value);
1884 if (ret < 0)
1885 return NULL;
1886 Py_INCREF(Py_None);
1887 return Py_None;
1888}
1889
1890static struct wrapperbase tab_descr_set[] = {
1891 {"__set__", (wrapperfunc)wrap_descrsetfunc,
1892 "descr.__set__(obj, value)"},
1893 {0}
1894};
1895
1896static PyObject *
1897wrap_init(PyObject *self, PyObject *args, void *wrapped)
1898{
1899 initproc func = (initproc)wrapped;
1900
1901 /* XXX What about keyword arguments? */
1902 if (func(self, args, NULL) < 0)
1903 return NULL;
1904 Py_INCREF(Py_None);
1905 return Py_None;
1906}
1907
1908static struct wrapperbase tab_init[] = {
1909 {"__init__", (wrapperfunc)wrap_init,
1910 "x.__init__(...) initializes x; "
1911 "see x.__type__.__doc__ for signature"},
1912 {0}
1913};
1914
1915static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001916tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917{
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001918 PyTypeObject *type, *subtype;
1919 PyObject *arg0, *res;
1920
1921 if (self == NULL || !PyType_Check(self))
1922 Py_FatalError("__new__() called with non-type 'self'");
1923 type = (PyTypeObject *)self;
1924 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
1925 PyErr_SetString(PyExc_TypeError,
1926 "T.__new__(): not enough arguments");
1927 return NULL;
1928 }
1929 arg0 = PyTuple_GET_ITEM(args, 0);
1930 if (!PyType_Check(arg0)) {
1931 PyErr_SetString(PyExc_TypeError,
1932 "T.__new__(S): S is not a type object");
1933 return NULL;
1934 }
1935 subtype = (PyTypeObject *)arg0;
1936 if (!PyType_IsSubtype(subtype, type)) {
1937 PyErr_SetString(PyExc_TypeError,
1938 "T.__new__(S): S is not a subtype of T");
1939 return NULL;
1940 }
1941 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
1942 if (args == NULL)
1943 return NULL;
1944 res = type->tp_new(subtype, args, kwds);
1945 Py_DECREF(args);
1946 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001947}
1948
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001949static struct PyMethodDef tp_new_methoddef[] = {
1950 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
1951 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 {0}
1953};
1954
1955static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001956add_tp_new_wrapper(PyTypeObject *type)
1957{
Guido van Rossumf040ede2001-08-07 16:40:56 +00001958 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001959
Guido van Rossumf040ede2001-08-07 16:40:56 +00001960 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
1961 return 0;
1962 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001963 if (func == NULL)
1964 return -1;
1965 return PyDict_SetItemString(type->tp_defined, "__new__", func);
1966}
1967
Guido van Rossum13d52f02001-08-10 21:24:08 +00001968static int
1969add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
1970{
1971 PyObject *dict = type->tp_defined;
1972
1973 for (; wraps->name != NULL; wraps++) {
1974 PyObject *descr;
1975 if (PyDict_GetItemString(dict, wraps->name))
1976 continue;
1977 descr = PyDescr_NewWrapper(type, wraps, wrapped);
1978 if (descr == NULL)
1979 return -1;
1980 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
1981 return -1;
1982 Py_DECREF(descr);
1983 }
1984 return 0;
1985}
1986
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001987/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00001988 dictionary with method descriptors for function slots. For each
1989 function slot (like tp_repr) that's defined in the type, one or
1990 more corresponding descriptors are added in the type's tp_defined
1991 dictionary under the appropriate name (like __repr__). Some
1992 function slots cause more than one descriptor to be added (for
1993 example, the nb_add slot adds both __add__ and __radd__
1994 descriptors) and some function slots compete for the same
1995 descriptor (for example both sq_item and mp_subscript generate a
1996 __getitem__ descriptor). This only adds new descriptors and
1997 doesn't overwrite entries in tp_defined that were previously
1998 defined. The descriptors contain a reference to the C function
1999 they must call, so that it's safe if they are copied into a
2000 subtype's __dict__ and the subtype has a different C function in
2001 its slot -- calling the method defined by the descriptor will call
2002 the C function that was used to create it, rather than the C
2003 function present in the slot when it is called. (This is important
2004 because a subtype may have a C function in the slot that calls the
2005 method from the dictionary, and we want to avoid infinite recursion
2006 here.) */
2007
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002008static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009add_operators(PyTypeObject *type)
2010{
2011 PySequenceMethods *sq;
2012 PyMappingMethods *mp;
2013 PyNumberMethods *nb;
2014
2015#undef ADD
2016#define ADD(SLOT, TABLE) \
2017 if (SLOT) { \
2018 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2019 return -1; \
2020 }
2021
2022 if ((sq = type->tp_as_sequence) != NULL) {
2023 ADD(sq->sq_length, tab_len);
2024 ADD(sq->sq_concat, tab_concat);
2025 ADD(sq->sq_repeat, tab_mul_int);
2026 ADD(sq->sq_item, tab_getitem_int);
2027 ADD(sq->sq_slice, tab_getslice);
2028 ADD(sq->sq_ass_item, tab_setitem_int);
2029 ADD(sq->sq_ass_slice, tab_setslice);
2030 ADD(sq->sq_contains, tab_contains);
2031 ADD(sq->sq_inplace_concat, tab_iadd);
2032 ADD(sq->sq_inplace_repeat, tab_imul_int);
2033 }
2034
2035 if ((mp = type->tp_as_mapping) != NULL) {
2036 if (sq->sq_length == NULL)
2037 ADD(mp->mp_length, tab_len);
2038 ADD(mp->mp_subscript, tab_getitem);
2039 ADD(mp->mp_ass_subscript, tab_setitem);
2040 }
2041
2042 /* We don't support "old-style numbers" because their binary
2043 operators require that both arguments have the same type;
2044 the wrappers here only work for new-style numbers. */
2045 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2046 (nb = type->tp_as_number) != NULL) {
2047 ADD(nb->nb_add, tab_add);
2048 ADD(nb->nb_subtract, tab_sub);
2049 ADD(nb->nb_multiply, tab_mul);
2050 ADD(nb->nb_divide, tab_div);
2051 ADD(nb->nb_remainder, tab_mod);
2052 ADD(nb->nb_divmod, tab_divmod);
2053 ADD(nb->nb_power, tab_pow);
2054 ADD(nb->nb_negative, tab_neg);
2055 ADD(nb->nb_positive, tab_pos);
2056 ADD(nb->nb_absolute, tab_abs);
2057 ADD(nb->nb_nonzero, tab_nonzero);
2058 ADD(nb->nb_invert, tab_invert);
2059 ADD(nb->nb_lshift, tab_lshift);
2060 ADD(nb->nb_rshift, tab_rshift);
2061 ADD(nb->nb_and, tab_and);
2062 ADD(nb->nb_xor, tab_xor);
2063 ADD(nb->nb_or, tab_or);
2064 /* We don't support coerce() -- see above comment */
2065 ADD(nb->nb_int, tab_int);
2066 ADD(nb->nb_long, tab_long);
2067 ADD(nb->nb_float, tab_float);
2068 ADD(nb->nb_oct, tab_oct);
2069 ADD(nb->nb_hex, tab_hex);
2070 ADD(nb->nb_inplace_add, tab_iadd);
2071 ADD(nb->nb_inplace_subtract, tab_isub);
2072 ADD(nb->nb_inplace_multiply, tab_imul);
2073 ADD(nb->nb_inplace_divide, tab_idiv);
2074 ADD(nb->nb_inplace_remainder, tab_imod);
2075 ADD(nb->nb_inplace_power, tab_ipow);
2076 ADD(nb->nb_inplace_lshift, tab_ilshift);
2077 ADD(nb->nb_inplace_rshift, tab_irshift);
2078 ADD(nb->nb_inplace_and, tab_iand);
2079 ADD(nb->nb_inplace_xor, tab_ixor);
2080 ADD(nb->nb_inplace_or, tab_ior);
2081 }
2082
2083 ADD(type->tp_getattro, tab_getattr);
2084 ADD(type->tp_setattro, tab_setattr);
2085 ADD(type->tp_compare, tab_cmp);
2086 ADD(type->tp_repr, tab_repr);
2087 ADD(type->tp_hash, tab_hash);
2088 ADD(type->tp_call, tab_call);
2089 ADD(type->tp_str, tab_str);
2090 ADD(type->tp_richcompare, tab_richcmp);
2091 ADD(type->tp_iter, tab_iter);
2092 ADD(type->tp_iternext, tab_next);
2093 ADD(type->tp_descr_get, tab_descr_get);
2094 ADD(type->tp_descr_set, tab_descr_set);
2095 ADD(type->tp_init, tab_init);
2096
Guido van Rossumf040ede2001-08-07 16:40:56 +00002097 if (type->tp_new != NULL) {
2098 if (add_tp_new_wrapper(type) < 0)
2099 return -1;
2100 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101
2102 return 0;
2103}
2104
Guido van Rossumf040ede2001-08-07 16:40:56 +00002105/* Slot wrappers that call the corresponding __foo__ slot. See comments
2106 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107
Guido van Rossumdc91b992001-08-08 22:26:22 +00002108#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002109static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002110FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002112 return PyObject_CallMethod(self, OPSTR, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113}
2114
Guido van Rossumdc91b992001-08-08 22:26:22 +00002115#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002117FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002119 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002120}
2121
Guido van Rossumdc91b992001-08-08 22:26:22 +00002122
2123#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002125FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002127 if (self->ob_type->tp_as_number != NULL && \
2128 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2129 PyObject *r; \
2130 r = PyObject_CallMethod( \
2131 self, OPSTR, "O", other); \
2132 if (r != Py_NotImplemented || \
2133 other->ob_type == self->ob_type) \
2134 return r; \
2135 Py_DECREF(r); \
2136 } \
2137 if (other->ob_type->tp_as_number != NULL && \
2138 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2139 return PyObject_CallMethod( \
2140 other, ROPSTR, "O", self); \
2141 } \
2142 Py_INCREF(Py_NotImplemented); \
2143 return Py_NotImplemented; \
2144}
2145
2146#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2147 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2148
2149#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2150static PyObject * \
2151FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2152{ \
2153 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154}
2155
2156static int
2157slot_sq_length(PyObject *self)
2158{
2159 PyObject *res = PyObject_CallMethod(self, "__len__", "");
2160
2161 if (res == NULL)
2162 return -1;
2163 return (int)PyInt_AsLong(res);
2164}
2165
Guido van Rossumdc91b992001-08-08 22:26:22 +00002166SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2167SLOT1(slot_sq_repeat, "__mul__", int, "i")
2168SLOT1(slot_sq_item, "__getitem__", int, "i")
2169SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002170
2171static int
2172slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2173{
2174 PyObject *res;
2175
2176 if (value == NULL)
2177 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2178 else
2179 res = PyObject_CallMethod(self, "__setitem__",
2180 "iO", index, value);
2181 if (res == NULL)
2182 return -1;
2183 Py_DECREF(res);
2184 return 0;
2185}
2186
2187static int
2188slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2189{
2190 PyObject *res;
2191
2192 if (value == NULL)
2193 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2194 else
2195 res = PyObject_CallMethod(self, "__setslice__",
2196 "iiO", i, j, value);
2197 if (res == NULL)
2198 return -1;
2199 Py_DECREF(res);
2200 return 0;
2201}
2202
2203static int
2204slot_sq_contains(PyObject *self, PyObject *value)
2205{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002206 PyObject *func, *res, *args;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207
Guido van Rossumb8f63662001-08-15 23:57:02 +00002208 func = PyObject_GetAttrString(self, "__contains__");
2209
2210 if (func != NULL) {
2211 args = Py_BuildValue("(O)", value);
2212 if (args == NULL)
2213 res = NULL;
2214 else {
2215 res = PyEval_CallObject(func, args);
2216 Py_DECREF(args);
2217 }
2218 Py_DECREF(func);
2219 if (res == NULL)
2220 return -1;
2221 return PyObject_IsTrue(res);
2222 }
2223 else {
2224 PyErr_Clear();
2225 return _PySequence_IterContains(self, value);
2226 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227}
2228
Guido van Rossumdc91b992001-08-08 22:26:22 +00002229SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2230SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231
2232#define slot_mp_length slot_sq_length
2233
Guido van Rossumdc91b992001-08-08 22:26:22 +00002234SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235
2236static int
2237slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2238{
2239 PyObject *res;
2240
2241 if (value == NULL)
2242 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2243 else
2244 res = PyObject_CallMethod(self, "__setitem__",
2245 "OO", key, value);
2246 if (res == NULL)
2247 return -1;
2248 Py_DECREF(res);
2249 return 0;
2250}
2251
Guido van Rossumdc91b992001-08-08 22:26:22 +00002252SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2253SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2254SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2255SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2256SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2257SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2258
2259staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2260
2261SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2262 nb_power, "__pow__", "__rpow__")
2263
2264static PyObject *
2265slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2266{
2267 if (modulus == Py_None)
2268 return slot_nb_power_binary(self, other);
2269 /* Three-arg power doesn't use __rpow__ */
2270 return PyObject_CallMethod(self, "__pow__", "OO", other, modulus);
2271}
2272
2273SLOT0(slot_nb_negative, "__neg__")
2274SLOT0(slot_nb_positive, "__pos__")
2275SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002276
2277static int
2278slot_nb_nonzero(PyObject *self)
2279{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002280 PyObject *func, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281
Guido van Rossumb8f63662001-08-15 23:57:02 +00002282 func = PyObject_GetAttrString(self, "__nonzero__");
2283 if (func == NULL) {
2284 PyErr_Clear();
2285 func = PyObject_GetAttrString(self, "__len__");
2286 }
2287
2288 if (func != NULL) {
2289 res = PyEval_CallObject(func, NULL);
2290 Py_DECREF(func);
2291 if (res == NULL)
2292 return -1;
2293 return PyObject_IsTrue(res);
2294 }
2295 else {
2296 PyErr_Clear();
2297 return 1;
2298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002299}
2300
Guido van Rossumdc91b992001-08-08 22:26:22 +00002301SLOT0(slot_nb_invert, "__invert__")
2302SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2303SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2304SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2305SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2306SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002307/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002308SLOT0(slot_nb_int, "__int__")
2309SLOT0(slot_nb_long, "__long__")
2310SLOT0(slot_nb_float, "__float__")
2311SLOT0(slot_nb_oct, "__oct__")
2312SLOT0(slot_nb_hex, "__hex__")
2313SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2314SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2315SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2316SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2317SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2318SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2319SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2320SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2321SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2322SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2323SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2324SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2325 "__floordiv__", "__rfloordiv__")
2326SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2327SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2328SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002329
2330static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002331half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002333 PyObject *func, *args, *res;
2334 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335
Guido van Rossumb8f63662001-08-15 23:57:02 +00002336 func = PyObject_GetAttrString(self, "__cmp__");
2337 if (func == NULL) {
2338 PyErr_Clear();
2339 }
2340 else {
2341 args = Py_BuildValue("(O)", other);
2342 if (args == NULL)
2343 res = NULL;
2344 else {
2345 res = PyObject_CallObject(func, args);
2346 Py_DECREF(args);
2347 }
2348 if (res != Py_NotImplemented) {
2349 if (res == NULL)
2350 return -2;
2351 c = PyInt_AsLong(res);
2352 Py_DECREF(res);
2353 if (c == -1 && PyErr_Occurred())
2354 return -2;
2355 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2356 }
2357 Py_DECREF(res);
2358 }
2359 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002360}
2361
Guido van Rossumb8f63662001-08-15 23:57:02 +00002362static int
2363slot_tp_compare(PyObject *self, PyObject *other)
2364{
2365 int c;
2366
2367 if (self->ob_type->tp_compare == slot_tp_compare) {
2368 c = half_compare(self, other);
2369 if (c <= 1)
2370 return c;
2371 }
2372 if (other->ob_type->tp_compare == slot_tp_compare) {
2373 c = half_compare(other, self);
2374 if (c < -1)
2375 return -2;
2376 if (c <= 1)
2377 return -c;
2378 }
2379 return (void *)self < (void *)other ? -1 :
2380 (void *)self > (void *)other ? 1 : 0;
2381}
2382
2383static PyObject *
2384slot_tp_repr(PyObject *self)
2385{
2386 PyObject *func, *res;
2387
2388 func = PyObject_GetAttrString(self, "__repr__");
2389 if (func != NULL) {
2390 res = PyEval_CallObject(func, NULL);
2391 Py_DECREF(func);
2392 return res;
2393 }
2394 else {
2395 char buf[120];
2396 PyErr_Clear();
2397 sprintf(buf, "<%.80s object at %p>",
2398 self->ob_type->tp_name, self);
2399 return PyString_FromString(buf);
2400 }
2401}
2402
2403static PyObject *
2404slot_tp_str(PyObject *self)
2405{
2406 PyObject *func, *res;
2407
2408 func = PyObject_GetAttrString(self, "__str__");
2409 if (func != NULL) {
2410 res = PyEval_CallObject(func, NULL);
2411 Py_DECREF(func);
2412 return res;
2413 }
2414 else {
2415 PyErr_Clear();
2416 return slot_tp_repr(self);
2417 }
2418}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002419
2420static long
2421slot_tp_hash(PyObject *self)
2422{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002423 PyObject *func, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002424 long h;
2425
Guido van Rossumb8f63662001-08-15 23:57:02 +00002426 func = PyObject_GetAttrString(self, "__hash__");
2427
2428 if (func != NULL) {
2429 res = PyEval_CallObject(func, NULL);
2430 Py_DECREF(func);
2431 if (res == NULL)
2432 return -1;
2433 h = PyInt_AsLong(res);
2434 }
2435 else {
2436 PyErr_Clear();
2437 func = PyObject_GetAttrString(self, "__eq__");
2438 if (func == NULL) {
2439 PyErr_Clear();
2440 func = PyObject_GetAttrString(self, "__cmp__");
2441 }
2442 if (func != NULL) {
2443 Py_DECREF(func);
2444 PyErr_SetString(PyExc_TypeError, "unhashable type");
2445 return -1;
2446 }
2447 PyErr_Clear();
2448 h = _Py_HashPointer((void *)self);
2449 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450 if (h == -1 && !PyErr_Occurred())
2451 h = -2;
2452 return h;
2453}
2454
2455static PyObject *
2456slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2457{
2458 PyObject *meth = PyObject_GetAttrString(self, "__call__");
2459 PyObject *res;
2460
2461 if (meth == NULL)
2462 return NULL;
2463 res = PyObject_Call(meth, args, kwds);
2464 Py_DECREF(meth);
2465 return res;
2466}
2467
Tim Peters6d6c1a32001-08-02 04:15:00 +00002468static PyObject *
2469slot_tp_getattro(PyObject *self, PyObject *name)
2470{
2471 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002472 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002473 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002474
Guido van Rossum8e248182001-08-12 05:17:56 +00002475 if (getattr_str == NULL) {
2476 getattr_str = PyString_InternFromString("__getattr__");
2477 if (getattr_str == NULL)
2478 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002479 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002480 getattr = _PyType_Lookup(tp, getattr_str);
2481 if (getattr == NULL)
2482 return PyObject_GenericGetAttr(self, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002483 return PyObject_CallFunction(getattr, "OO", self, name);
2484}
2485
2486static int
2487slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2488{
2489 PyObject *res;
2490
2491 if (value == NULL)
2492 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2493 else
2494 res = PyObject_CallMethod(self, "__setattr__",
2495 "OO", name, value);
2496 if (res == NULL)
2497 return -1;
2498 Py_DECREF(res);
2499 return 0;
2500}
2501
2502/* Map rich comparison operators to their __xx__ namesakes */
2503static char *name_op[] = {
2504 "__lt__",
2505 "__le__",
2506 "__eq__",
2507 "__ne__",
2508 "__gt__",
2509 "__ge__",
2510};
2511
2512static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002513half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002515 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002516
Guido van Rossumb8f63662001-08-15 23:57:02 +00002517 func = PyObject_GetAttrString(self, name_op[op]);
2518 if (func == NULL) {
2519 PyErr_Clear();
2520 Py_INCREF(Py_NotImplemented);
2521 return Py_NotImplemented;
2522 }
2523 args = Py_BuildValue("(O)", other);
2524 if (args == NULL)
2525 res = NULL;
2526 else {
2527 res = PyObject_CallObject(func, args);
2528 Py_DECREF(args);
2529 }
2530 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531 return res;
2532}
2533
Guido van Rossumb8f63662001-08-15 23:57:02 +00002534/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2535static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2536
2537static PyObject *
2538slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2539{
2540 PyObject *res;
2541
2542 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2543 res = half_richcompare(self, other, op);
2544 if (res != Py_NotImplemented)
2545 return res;
2546 Py_DECREF(res);
2547 }
2548 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2549 res = half_richcompare(other, self, swapped_op[op]);
2550 if (res != Py_NotImplemented) {
2551 return res;
2552 }
2553 Py_DECREF(res);
2554 }
2555 Py_INCREF(Py_NotImplemented);
2556 return Py_NotImplemented;
2557}
2558
2559static PyObject *
2560slot_tp_iter(PyObject *self)
2561{
2562 PyObject *func, *res;
2563
2564 func = PyObject_GetAttrString(self, "__iter__");
2565 if (func != NULL) {
2566 res = PyObject_CallObject(func, NULL);
2567 Py_DECREF(func);
2568 return res;
2569 }
2570 PyErr_Clear();
2571 func = PyObject_GetAttrString(self, "__getitem__");
2572 if (func == NULL) {
2573 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2574 return NULL;
2575 }
2576 Py_DECREF(func);
2577 return PySeqIter_New(self);
2578}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579
2580static PyObject *
2581slot_tp_iternext(PyObject *self)
2582{
2583 return PyObject_CallMethod(self, "next", "");
2584}
2585
Guido van Rossumdc91b992001-08-08 22:26:22 +00002586SLOT2(slot_tp_descr_get, "__get__", PyObject *, PyObject *, "OO")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002587
2588static int
2589slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2590{
2591 PyObject *res = PyObject_CallMethod(self, "__set__",
2592 "OO", target, value);
2593 if (res == NULL)
2594 return -1;
2595 Py_DECREF(res);
2596 return 0;
2597}
2598
2599static int
2600slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2601{
2602 PyObject *meth = PyObject_GetAttrString(self, "__init__");
2603 PyObject *res;
2604
2605 if (meth == NULL)
2606 return -1;
2607 res = PyObject_Call(meth, args, kwds);
2608 Py_DECREF(meth);
2609 if (res == NULL)
2610 return -1;
2611 Py_DECREF(res);
2612 return 0;
2613}
2614
2615static PyObject *
2616slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2617{
2618 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2619 PyObject *newargs, *x;
2620 int i, n;
2621
2622 if (func == NULL)
2623 return NULL;
2624 assert(PyTuple_Check(args));
2625 n = PyTuple_GET_SIZE(args);
2626 newargs = PyTuple_New(n+1);
2627 if (newargs == NULL)
2628 return NULL;
2629 Py_INCREF(type);
2630 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2631 for (i = 0; i < n; i++) {
2632 x = PyTuple_GET_ITEM(args, i);
2633 Py_INCREF(x);
2634 PyTuple_SET_ITEM(newargs, i+1, x);
2635 }
2636 x = PyObject_Call(func, newargs, kwds);
2637 Py_DECREF(func);
2638 return x;
2639}
2640
Guido van Rossumf040ede2001-08-07 16:40:56 +00002641/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002642 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002643 The dict argument is the dictionary argument passed to type_new(),
2644 which is the local namespace of the class statement, in other
2645 words, it contains the methods. For each special method (like
2646 __repr__) defined in the dictionary, the corresponding function
2647 slot in the type object (like tp_repr) is set to a special function
2648 whose name is 'slot_' followed by the slot name and whose signature
2649 is whatever is required for that slot. These slot functions look
2650 up the corresponding method in the type's dictionary and call it.
2651 The slot functions have to take care of the various peculiarities
2652 of the mapping between slots and special methods, such as mapping
2653 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2654 etc.) or mapping multiple slots to a single method (sq_item,
2655 mp_subscript <--> __getitem__). */
2656
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657static void
2658override_slots(PyTypeObject *type, PyObject *dict)
2659{
2660 PySequenceMethods *sq = type->tp_as_sequence;
2661 PyMappingMethods *mp = type->tp_as_mapping;
2662 PyNumberMethods *nb = type->tp_as_number;
2663
Guido van Rossumdc91b992001-08-08 22:26:22 +00002664#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002665 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002666 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667 }
2668
Guido van Rossumdc91b992001-08-08 22:26:22 +00002669#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002670 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002671 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672 }
2673
Guido van Rossumdc91b992001-08-08 22:26:22 +00002674#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002675 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002676 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677 }
2678
Guido van Rossumdc91b992001-08-08 22:26:22 +00002679#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002680 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002681 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682 }
2683
Guido van Rossumdc91b992001-08-08 22:26:22 +00002684 SQSLOT("__len__", sq_length, slot_sq_length);
2685 SQSLOT("__add__", sq_concat, slot_sq_concat);
2686 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
2687 SQSLOT("__getitem__", sq_item, slot_sq_item);
2688 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
2689 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
2690 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
2691 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
2692 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
2693 SQSLOT("__contains__", sq_contains, slot_sq_contains);
2694 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
2695 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696
Guido van Rossumdc91b992001-08-08 22:26:22 +00002697 MPSLOT("__len__", mp_length, slot_mp_length);
2698 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
2699 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
2700 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002701
Guido van Rossumdc91b992001-08-08 22:26:22 +00002702 NBSLOT("__add__", nb_add, slot_nb_add);
2703 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
2704 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
2705 NBSLOT("__div__", nb_divide, slot_nb_divide);
2706 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
2707 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
2708 NBSLOT("__pow__", nb_power, slot_nb_power);
2709 NBSLOT("__neg__", nb_negative, slot_nb_negative);
2710 NBSLOT("__pos__", nb_positive, slot_nb_positive);
2711 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
2712 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
2713 NBSLOT("__invert__", nb_invert, slot_nb_invert);
2714 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
2715 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
2716 NBSLOT("__and__", nb_and, slot_nb_and);
2717 NBSLOT("__xor__", nb_xor, slot_nb_xor);
2718 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002719 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002720 NBSLOT("__int__", nb_int, slot_nb_int);
2721 NBSLOT("__long__", nb_long, slot_nb_long);
2722 NBSLOT("__float__", nb_float, slot_nb_float);
2723 NBSLOT("__oct__", nb_oct, slot_nb_oct);
2724 NBSLOT("__hex__", nb_hex, slot_nb_hex);
2725 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
2726 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
2727 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
2728 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
2729 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
2730 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
2731 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
2732 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
2733 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
2734 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
2735 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
2736 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
2737 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
2738 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
2739 slot_nb_inplace_floor_divide);
2740 NBSLOT("__itruediv__", nb_inplace_true_divide,
2741 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742
Guido van Rossum8e248182001-08-12 05:17:56 +00002743 if (dict == NULL ||
2744 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745 PyDict_GetItemString(dict, "__repr__"))
2746 type->tp_print = NULL;
2747
Guido van Rossumdc91b992001-08-08 22:26:22 +00002748 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
2749 TPSLOT("__repr__", tp_repr, slot_tp_repr);
2750 TPSLOT("__hash__", tp_hash, slot_tp_hash);
2751 TPSLOT("__call__", tp_call, slot_tp_call);
2752 TPSLOT("__str__", tp_str, slot_tp_str);
2753 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
2754 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
2755 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
2756 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
2757 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
2758 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
2759 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
2760 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
2761 TPSLOT("__iter__", tp_iter, slot_tp_iter);
2762 TPSLOT("next", tp_iternext, slot_tp_iternext);
2763 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
2764 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
2765 TPSLOT("__init__", tp_init, slot_tp_init);
2766 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767}