This commit was manufactured by cvs2svn to create tag 'r221'.
[python/dscho.git] / Objects / typeobject.c
blob158c0ed1f6487ab34d7fb4ac70e13899548d25c9
2 /* Type object implementation */
4 #include "Python.h"
5 #include "structmember.h"
7 static PyMemberDef type_members[] = {
8 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__weakrefoffset__", T_LONG,
12 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
13 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
14 {"__dictoffset__", T_LONG,
15 offsetof(PyTypeObject, tp_dictoffset), READONLY},
16 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
17 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
21 static PyObject *
22 type_name(PyTypeObject *type, void *context)
24 char *s;
26 s = strrchr(type->tp_name, '.');
27 if (s == NULL)
28 s = type->tp_name;
29 else
30 s++;
31 return PyString_FromString(s);
34 static PyObject *
35 type_module(PyTypeObject *type, void *context)
37 PyObject *mod;
38 char *s;
40 s = strrchr(type->tp_name, '.');
41 if (s != NULL)
42 return PyString_FromStringAndSize(type->tp_name,
43 (int)(s - type->tp_name));
44 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
45 return PyString_FromString("__builtin__");
46 mod = PyDict_GetItemString(type->tp_dict, "__module__");
47 if (mod != NULL && PyString_Check(mod)) {
48 Py_INCREF(mod);
49 return mod;
51 PyErr_SetString(PyExc_AttributeError, "__module__");
52 return NULL;
55 static int
56 type_set_module(PyTypeObject *type, PyObject *value, void *context)
58 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
59 strrchr(type->tp_name, '.')) {
60 PyErr_Format(PyExc_TypeError,
61 "can't set %s.__module__", type->tp_name);
62 return -1;
64 if (!value) {
65 PyErr_Format(PyExc_TypeError,
66 "can't delete %s.__module__", type->tp_name);
67 return -1;
69 return PyDict_SetItemString(type->tp_dict, "__module__", value);
72 static PyObject *
73 type_dict(PyTypeObject *type, void *context)
75 if (type->tp_dict == NULL) {
76 Py_INCREF(Py_None);
77 return Py_None;
79 return PyDictProxy_New(type->tp_dict);
82 static PyObject *
83 type_get_doc(PyTypeObject *type, void *context)
85 PyObject *result;
86 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
87 if (type->tp_doc == NULL) {
88 Py_INCREF(Py_None);
89 return Py_None;
91 return PyString_FromString(type->tp_doc);
93 result = PyDict_GetItemString(type->tp_dict, "__doc__");
94 Py_INCREF(result);
95 return result;
98 static PyGetSetDef type_getsets[] = {
99 {"__name__", (getter)type_name, NULL, NULL},
100 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
101 {"__dict__", (getter)type_dict, NULL, NULL},
102 {"__doc__", (getter)type_get_doc, NULL, NULL},
106 static int
107 type_compare(PyObject *v, PyObject *w)
109 /* This is called with type objects only. So we
110 can just compare the addresses. */
111 Py_uintptr_t vv = (Py_uintptr_t)v;
112 Py_uintptr_t ww = (Py_uintptr_t)w;
113 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
116 static PyObject *
117 type_repr(PyTypeObject *type)
119 PyObject *mod, *name, *rtn;
120 char *kind;
122 mod = type_module(type, NULL);
123 if (mod == NULL)
124 PyErr_Clear();
125 else if (!PyString_Check(mod)) {
126 Py_DECREF(mod);
127 mod = NULL;
129 name = type_name(type, NULL);
130 if (name == NULL)
131 return NULL;
133 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
134 kind = "class";
135 else
136 kind = "type";
138 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
139 rtn = PyString_FromFormat("<%s '%s.%s'>",
140 kind,
141 PyString_AS_STRING(mod),
142 PyString_AS_STRING(name));
144 else
145 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
147 Py_XDECREF(mod);
148 Py_DECREF(name);
149 return rtn;
152 static PyObject *
153 type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
155 PyObject *obj;
157 if (type->tp_new == NULL) {
158 PyErr_Format(PyExc_TypeError,
159 "cannot create '%.100s' instances",
160 type->tp_name);
161 return NULL;
164 obj = type->tp_new(type, args, kwds);
165 if (obj != NULL) {
166 /* Ugly exception: when the call was type(something),
167 don't call tp_init on the result. */
168 if (type == &PyType_Type &&
169 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
170 (kwds == NULL ||
171 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
172 return obj;
173 type = obj->ob_type;
174 if (type->tp_init != NULL &&
175 type->tp_init(obj, args, kwds) < 0) {
176 Py_DECREF(obj);
177 obj = NULL;
180 return obj;
183 PyObject *
184 PyType_GenericAlloc(PyTypeObject *type, int nitems)
186 PyObject *obj;
187 const size_t size = _PyObject_VAR_SIZE(type, nitems);
189 if (PyType_IS_GC(type))
190 obj = _PyObject_GC_Malloc(type, nitems);
191 else
192 obj = PyObject_MALLOC(size);
194 if (obj == NULL)
195 return PyErr_NoMemory();
197 memset(obj, '\0', size);
199 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
200 Py_INCREF(type);
202 if (type->tp_itemsize == 0)
203 PyObject_INIT(obj, type);
204 else
205 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
207 if (PyType_IS_GC(type))
208 _PyObject_GC_TRACK(obj);
209 return obj;
212 PyObject *
213 PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
215 return type->tp_alloc(type, 0);
218 /* Helpers for subtyping */
220 static int
221 subtype_traverse(PyObject *self, visitproc visit, void *arg)
223 PyTypeObject *type, *base;
224 traverseproc f;
225 int err;
227 /* Find the nearest base with a different tp_traverse */
228 type = self->ob_type;
229 base = type->tp_base;
230 while ((f = base->tp_traverse) == subtype_traverse) {
231 base = base->tp_base;
232 assert(base);
235 if (type->tp_dictoffset != base->tp_dictoffset) {
236 PyObject **dictptr = _PyObject_GetDictPtr(self);
237 if (dictptr && *dictptr) {
238 err = visit(*dictptr, arg);
239 if (err)
240 return err;
244 if (f)
245 return f(self, visit, arg);
246 return 0;
249 staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
251 static int
252 call_finalizer(PyObject *self)
254 static PyObject *del_str = NULL;
255 PyObject *del, *res;
256 PyObject *error_type, *error_value, *error_traceback;
258 /* Temporarily resurrect the object. */
259 #ifdef Py_TRACE_REFS
260 #ifndef Py_REF_DEBUG
261 # error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
262 #endif
263 /* much too complicated if Py_TRACE_REFS defined */
264 _Py_NewReference((PyObject *)self);
265 #ifdef COUNT_ALLOCS
266 /* compensate for boost in _Py_NewReference; note that
267 * _Py_RefTotal was also boosted; we'll knock that down later.
269 self->ob_type->tp_allocs--;
270 #endif
271 #else /* !Py_TRACE_REFS */
272 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
273 Py_INCREF(self);
274 #endif /* !Py_TRACE_REFS */
276 /* Save the current exception, if any. */
277 PyErr_Fetch(&error_type, &error_value, &error_traceback);
279 /* Execute __del__ method, if any. */
280 del = lookup_maybe(self, "__del__", &del_str);
281 if (del != NULL) {
282 res = PyEval_CallObject(del, NULL);
283 if (res == NULL)
284 PyErr_WriteUnraisable(del);
285 else
286 Py_DECREF(res);
287 Py_DECREF(del);
290 /* Restore the saved exception. */
291 PyErr_Restore(error_type, error_value, error_traceback);
293 /* Undo the temporary resurrection; can't use DECREF here, it would
294 * cause a recursive call.
296 #ifdef Py_REF_DEBUG
297 /* _Py_RefTotal was boosted either by _Py_NewReference or
298 * Py_INCREF above.
300 _Py_RefTotal--;
301 #endif
302 if (--self->ob_refcnt > 0) {
303 #ifdef COUNT_ALLOCS
304 self->ob_type->tp_frees--;
305 #endif
306 _PyObject_GC_TRACK(self);
307 return -1; /* __del__ added a reference; don't delete now */
309 #ifdef Py_TRACE_REFS
310 _Py_ForgetReference((PyObject *)self);
311 #ifdef COUNT_ALLOCS
312 /* compensate for increment in _Py_ForgetReference */
313 self->ob_type->tp_frees--;
314 #endif
315 #endif
317 return 0;
320 static void
321 subtype_dealloc(PyObject *self)
323 PyTypeObject *type, *base;
324 destructor f;
326 /* This exists so we can DECREF self->ob_type */
328 if (call_finalizer(self) < 0)
329 return;
331 /* Find the nearest base with a different tp_dealloc */
332 type = self->ob_type;
333 base = type->tp_base;
334 while ((f = base->tp_dealloc) == subtype_dealloc) {
335 base = base->tp_base;
336 assert(base);
339 /* Clear __slots__ variables */
340 if (type->tp_basicsize != base->tp_basicsize &&
341 type->tp_itemsize == 0)
343 char *addr = ((char *)self);
344 char *p = addr + base->tp_basicsize;
345 char *q = addr + type->tp_basicsize;
346 for (; p < q; p += sizeof(PyObject *)) {
347 PyObject **pp;
348 if (p == addr + type->tp_dictoffset ||
349 p == addr + type->tp_weaklistoffset)
350 continue;
351 pp = (PyObject **)p;
352 if (*pp != NULL) {
353 Py_DECREF(*pp);
354 *pp = NULL;
359 /* If we added a dict, DECREF it */
360 if (type->tp_dictoffset && !base->tp_dictoffset) {
361 PyObject **dictptr = _PyObject_GetDictPtr(self);
362 if (dictptr != NULL) {
363 PyObject *dict = *dictptr;
364 if (dict != NULL) {
365 Py_DECREF(dict);
366 *dictptr = NULL;
371 /* If we added weaklist, we clear it */
372 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
373 PyObject_ClearWeakRefs(self);
375 /* Finalize GC if the base doesn't do GC and we do */
376 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
377 _PyObject_GC_UNTRACK(self);
379 /* Call the base tp_dealloc() */
380 assert(f);
381 f(self);
383 /* Can't reference self beyond this point */
384 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
385 Py_DECREF(type);
389 staticforward PyTypeObject *solid_base(PyTypeObject *type);
391 typedef struct {
392 PyTypeObject type;
393 PyNumberMethods as_number;
394 PySequenceMethods as_sequence;
395 PyMappingMethods as_mapping;
396 PyBufferProcs as_buffer;
397 PyObject *name, *slots;
398 PyMemberDef members[1];
399 } etype;
401 /* type test with subclassing support */
404 PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
406 PyObject *mro;
408 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
409 return b == a || b == &PyBaseObject_Type;
411 mro = a->tp_mro;
412 if (mro != NULL) {
413 /* Deal with multiple inheritance without recursion
414 by walking the MRO tuple */
415 int i, n;
416 assert(PyTuple_Check(mro));
417 n = PyTuple_GET_SIZE(mro);
418 for (i = 0; i < n; i++) {
419 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
420 return 1;
422 return 0;
424 else {
425 /* a is not completely initilized yet; follow tp_base */
426 do {
427 if (a == b)
428 return 1;
429 a = a->tp_base;
430 } while (a != NULL);
431 return b == &PyBaseObject_Type;
435 /* Internal routines to do a method lookup in the type
436 without looking in the instance dictionary
437 (so we can't use PyObject_GetAttr) but still binding
438 it to the instance. The arguments are the object,
439 the method name as a C string, and the address of a
440 static variable used to cache the interned Python string.
442 Two variants:
444 - lookup_maybe() returns NULL without raising an exception
445 when the _PyType_Lookup() call fails;
447 - lookup_method() always raises an exception upon errors.
450 static PyObject *
451 lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
453 PyObject *res;
455 if (*attrobj == NULL) {
456 *attrobj = PyString_InternFromString(attrstr);
457 if (*attrobj == NULL)
458 return NULL;
460 res = _PyType_Lookup(self->ob_type, *attrobj);
461 if (res != NULL) {
462 descrgetfunc f;
463 if ((f = res->ob_type->tp_descr_get) == NULL)
464 Py_INCREF(res);
465 else
466 res = f(res, self, (PyObject *)(self->ob_type));
468 return res;
471 static PyObject *
472 lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
474 PyObject *res = lookup_maybe(self, attrstr, attrobj);
475 if (res == NULL && !PyErr_Occurred())
476 PyErr_SetObject(PyExc_AttributeError, *attrobj);
477 return res;
480 /* A variation of PyObject_CallMethod that uses lookup_method()
481 instead of PyObject_GetAttrString(). This uses the same convention
482 as lookup_method to cache the interned name string object. */
484 static PyObject *
485 call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
487 va_list va;
488 PyObject *args, *func = 0, *retval;
489 va_start(va, format);
491 func = lookup_maybe(o, name, nameobj);
492 if (func == NULL) {
493 va_end(va);
494 if (!PyErr_Occurred())
495 PyErr_SetObject(PyExc_AttributeError, *nameobj);
496 return NULL;
499 if (format && *format)
500 args = Py_VaBuildValue(format, va);
501 else
502 args = PyTuple_New(0);
504 va_end(va);
506 if (args == NULL)
507 return NULL;
509 assert(PyTuple_Check(args));
510 retval = PyObject_Call(func, args, NULL);
512 Py_DECREF(args);
513 Py_DECREF(func);
515 return retval;
518 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
520 static PyObject *
521 call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
523 va_list va;
524 PyObject *args, *func = 0, *retval;
525 va_start(va, format);
527 func = lookup_maybe(o, name, nameobj);
528 if (func == NULL) {
529 va_end(va);
530 if (!PyErr_Occurred()) {
531 Py_INCREF(Py_NotImplemented);
532 return Py_NotImplemented;
534 return NULL;
537 if (format && *format)
538 args = Py_VaBuildValue(format, va);
539 else
540 args = PyTuple_New(0);
542 va_end(va);
544 if (args == NULL)
545 return NULL;
547 assert(PyTuple_Check(args));
548 retval = PyObject_Call(func, args, NULL);
550 Py_DECREF(args);
551 Py_DECREF(func);
553 return retval;
556 /* Method resolution order algorithm from "Putting Metaclasses to Work"
557 by Forman and Danforth (Addison-Wesley 1999). */
559 static int
560 conservative_merge(PyObject *left, PyObject *right)
562 int left_size;
563 int right_size;
564 int i, j, r, ok;
565 PyObject *temp, *rr;
567 assert(PyList_Check(left));
568 assert(PyList_Check(right));
570 again:
571 left_size = PyList_GET_SIZE(left);
572 right_size = PyList_GET_SIZE(right);
573 for (i = 0; i < left_size; i++) {
574 for (j = 0; j < right_size; j++) {
575 if (PyList_GET_ITEM(left, i) ==
576 PyList_GET_ITEM(right, j)) {
577 /* found a merge point */
578 temp = PyList_New(0);
579 if (temp == NULL)
580 return -1;
581 for (r = 0; r < j; r++) {
582 rr = PyList_GET_ITEM(right, r);
583 ok = PySequence_Contains(left, rr);
584 if (ok < 0) {
585 Py_DECREF(temp);
586 return -1;
588 if (!ok) {
589 ok = PyList_Append(temp, rr);
590 if (ok < 0) {
591 Py_DECREF(temp);
592 return -1;
596 ok = PyList_SetSlice(left, i, i, temp);
597 Py_DECREF(temp);
598 if (ok < 0)
599 return -1;
600 ok = PyList_SetSlice(right, 0, j+1, NULL);
601 if (ok < 0)
602 return -1;
603 goto again;
607 return PyList_SetSlice(left, left_size, left_size, right);
610 static int
611 serious_order_disagreements(PyObject *left, PyObject *right)
613 return 0; /* XXX later -- for now, we cheat: "don't do that" */
616 static int
617 fill_classic_mro(PyObject *mro, PyObject *cls)
619 PyObject *bases, *base;
620 int i, n;
622 assert(PyList_Check(mro));
623 assert(PyClass_Check(cls));
624 i = PySequence_Contains(mro, cls);
625 if (i < 0)
626 return -1;
627 if (!i) {
628 if (PyList_Append(mro, cls) < 0)
629 return -1;
631 bases = ((PyClassObject *)cls)->cl_bases;
632 assert(bases && PyTuple_Check(bases));
633 n = PyTuple_GET_SIZE(bases);
634 for (i = 0; i < n; i++) {
635 base = PyTuple_GET_ITEM(bases, i);
636 if (fill_classic_mro(mro, base) < 0)
637 return -1;
639 return 0;
642 static PyObject *
643 classic_mro(PyObject *cls)
645 PyObject *mro;
647 assert(PyClass_Check(cls));
648 mro = PyList_New(0);
649 if (mro != NULL) {
650 if (fill_classic_mro(mro, cls) == 0)
651 return mro;
652 Py_DECREF(mro);
654 return NULL;
657 static PyObject *
658 mro_implementation(PyTypeObject *type)
660 int i, n, ok;
661 PyObject *bases, *result;
663 bases = type->tp_bases;
664 n = PyTuple_GET_SIZE(bases);
665 result = Py_BuildValue("[O]", (PyObject *)type);
666 if (result == NULL)
667 return NULL;
668 for (i = 0; i < n; i++) {
669 PyObject *base = PyTuple_GET_ITEM(bases, i);
670 PyObject *parentMRO;
671 if (PyType_Check(base))
672 parentMRO = PySequence_List(
673 ((PyTypeObject*)base)->tp_mro);
674 else
675 parentMRO = classic_mro(base);
676 if (parentMRO == NULL) {
677 Py_DECREF(result);
678 return NULL;
680 if (serious_order_disagreements(result, parentMRO)) {
681 Py_DECREF(result);
682 return NULL;
684 ok = conservative_merge(result, parentMRO);
685 Py_DECREF(parentMRO);
686 if (ok < 0) {
687 Py_DECREF(result);
688 return NULL;
691 return result;
694 static PyObject *
695 mro_external(PyObject *self)
697 PyTypeObject *type = (PyTypeObject *)self;
699 return mro_implementation(type);
702 static int
703 mro_internal(PyTypeObject *type)
705 PyObject *mro, *result, *tuple;
707 if (type->ob_type == &PyType_Type) {
708 result = mro_implementation(type);
710 else {
711 static PyObject *mro_str;
712 mro = lookup_method((PyObject *)type, "mro", &mro_str);
713 if (mro == NULL)
714 return -1;
715 result = PyObject_CallObject(mro, NULL);
716 Py_DECREF(mro);
718 if (result == NULL)
719 return -1;
720 tuple = PySequence_Tuple(result);
721 Py_DECREF(result);
722 type->tp_mro = tuple;
723 return 0;
727 /* Calculate the best base amongst multiple base classes.
728 This is the first one that's on the path to the "solid base". */
730 static PyTypeObject *
731 best_base(PyObject *bases)
733 int i, n;
734 PyTypeObject *base, *winner, *candidate, *base_i;
735 PyObject *base_proto;
737 assert(PyTuple_Check(bases));
738 n = PyTuple_GET_SIZE(bases);
739 assert(n > 0);
740 base = NULL;
741 winner = NULL;
742 for (i = 0; i < n; i++) {
743 base_proto = PyTuple_GET_ITEM(bases, i);
744 if (PyClass_Check(base_proto))
745 continue;
746 if (!PyType_Check(base_proto)) {
747 PyErr_SetString(
748 PyExc_TypeError,
749 "bases must be types");
750 return NULL;
752 base_i = (PyTypeObject *)base_proto;
753 if (base_i->tp_dict == NULL) {
754 if (PyType_Ready(base_i) < 0)
755 return NULL;
757 candidate = solid_base(base_i);
758 if (winner == NULL) {
759 winner = candidate;
760 base = base_i;
762 else if (PyType_IsSubtype(winner, candidate))
764 else if (PyType_IsSubtype(candidate, winner)) {
765 winner = candidate;
766 base = base_i;
768 else {
769 PyErr_SetString(
770 PyExc_TypeError,
771 "multiple bases have "
772 "instance lay-out conflict");
773 return NULL;
776 if (base == NULL)
777 PyErr_SetString(PyExc_TypeError,
778 "a new-style class can't have only classic bases");
779 return base;
782 static int
783 extra_ivars(PyTypeObject *type, PyTypeObject *base)
785 size_t t_size = type->tp_basicsize;
786 size_t b_size = base->tp_basicsize;
788 assert(t_size >= b_size); /* Else type smaller than base! */
789 if (type->tp_itemsize || base->tp_itemsize) {
790 /* If itemsize is involved, stricter rules */
791 return t_size != b_size ||
792 type->tp_itemsize != base->tp_itemsize;
794 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
795 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
796 t_size -= sizeof(PyObject *);
797 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
798 type->tp_dictoffset + sizeof(PyObject *) == t_size)
799 t_size -= sizeof(PyObject *);
801 return t_size != b_size;
804 static PyTypeObject *
805 solid_base(PyTypeObject *type)
807 PyTypeObject *base;
809 if (type->tp_base)
810 base = solid_base(type->tp_base);
811 else
812 base = &PyBaseObject_Type;
813 if (extra_ivars(type, base))
814 return type;
815 else
816 return base;
819 staticforward void object_dealloc(PyObject *);
820 staticforward int object_init(PyObject *, PyObject *, PyObject *);
821 staticforward int update_slot(PyTypeObject *, PyObject *);
822 staticforward void fixup_slot_dispatchers(PyTypeObject *);
824 static PyObject *
825 subtype_dict(PyObject *obj, void *context)
827 PyObject **dictptr = _PyObject_GetDictPtr(obj);
828 PyObject *dict;
830 if (dictptr == NULL) {
831 PyErr_SetString(PyExc_AttributeError,
832 "This object has no __dict__");
833 return NULL;
835 dict = *dictptr;
836 if (dict == NULL)
837 *dictptr = dict = PyDict_New();
838 Py_XINCREF(dict);
839 return dict;
842 static int
843 subtype_setdict(PyObject *obj, PyObject *value, void *context)
845 PyObject **dictptr = _PyObject_GetDictPtr(obj);
846 PyObject *dict;
848 if (dictptr == NULL) {
849 PyErr_SetString(PyExc_AttributeError,
850 "This object has no __dict__");
851 return -1;
853 if (value != NULL && !PyDict_Check(value)) {
854 PyErr_SetString(PyExc_TypeError,
855 "__dict__ must be set to a dictionary");
856 return -1;
858 dict = *dictptr;
859 Py_XINCREF(value);
860 *dictptr = value;
861 Py_XDECREF(dict);
862 return 0;
865 static PyGetSetDef subtype_getsets[] = {
866 {"__dict__", subtype_dict, subtype_setdict, NULL},
867 {0},
870 /* bozo: __getstate__ that raises TypeError */
872 static PyObject *
873 bozo_func(PyObject *self, PyObject *args)
875 PyErr_SetString(PyExc_TypeError,
876 "a class that defines __slots__ without "
877 "defining __getstate__ cannot be pickled");
878 return NULL;
881 static PyMethodDef bozo_ml = {"__getstate__", bozo_func};
883 static PyObject *bozo_obj = NULL;
885 static PyObject *
886 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
888 PyObject *name, *bases, *dict;
889 static char *kwlist[] = {"name", "bases", "dict", 0};
890 PyObject *slots, *tmp;
891 PyTypeObject *type, *base, *tmptype, *winner;
892 etype *et;
893 PyMemberDef *mp;
894 int i, nbases, nslots, slotoffset, add_dict, add_weak;
896 assert(args != NULL && PyTuple_Check(args));
897 assert(kwds == NULL || PyDict_Check(kwds));
899 /* Special case: type(x) should return x->ob_type */
901 const int nargs = PyTuple_GET_SIZE(args);
902 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
904 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
905 PyObject *x = PyTuple_GET_ITEM(args, 0);
906 Py_INCREF(x->ob_type);
907 return (PyObject *) x->ob_type;
910 /* SF bug 475327 -- if that didn't trigger, we need 3
911 arguments. but PyArg_ParseTupleAndKeywords below may give
912 a msg saying type() needs exactly 3. */
913 if (nargs + nkwds != 3) {
914 PyErr_SetString(PyExc_TypeError,
915 "type() takes 1 or 3 arguments");
916 return NULL;
920 /* Check arguments: (name, bases, dict) */
921 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
922 &name,
923 &PyTuple_Type, &bases,
924 &PyDict_Type, &dict))
925 return NULL;
927 /* Determine the proper metatype to deal with this,
928 and check for metatype conflicts while we're at it.
929 Note that if some other metatype wins to contract,
930 it's possible that its instances are not types. */
931 nbases = PyTuple_GET_SIZE(bases);
932 winner = metatype;
933 for (i = 0; i < nbases; i++) {
934 tmp = PyTuple_GET_ITEM(bases, i);
935 tmptype = tmp->ob_type;
936 if (tmptype == &PyClass_Type)
937 continue; /* Special case classic classes */
938 if (PyType_IsSubtype(winner, tmptype))
939 continue;
940 if (PyType_IsSubtype(tmptype, winner)) {
941 winner = tmptype;
942 continue;
944 PyErr_SetString(PyExc_TypeError,
945 "metatype conflict among bases");
946 return NULL;
948 if (winner != metatype) {
949 if (winner->tp_new != type_new) /* Pass it to the winner */
950 return winner->tp_new(winner, args, kwds);
951 metatype = winner;
954 /* Adjust for empty tuple bases */
955 if (nbases == 0) {
956 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
957 if (bases == NULL)
958 return NULL;
959 nbases = 1;
961 else
962 Py_INCREF(bases);
964 /* XXX From here until type is allocated, "return NULL" leaks bases! */
966 /* Calculate best base, and check that all bases are type objects */
967 base = best_base(bases);
968 if (base == NULL)
969 return NULL;
970 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
971 PyErr_Format(PyExc_TypeError,
972 "type '%.100s' is not an acceptable base type",
973 base->tp_name);
974 return NULL;
977 /* Check for a __slots__ sequence variable in dict, and count it */
978 slots = PyDict_GetItemString(dict, "__slots__");
979 nslots = 0;
980 add_dict = 0;
981 add_weak = 0;
982 if (slots != NULL) {
983 /* Make it into a tuple */
984 if (PyString_Check(slots))
985 slots = Py_BuildValue("(O)", slots);
986 else
987 slots = PySequence_Tuple(slots);
988 if (slots == NULL)
989 return NULL;
990 nslots = PyTuple_GET_SIZE(slots);
991 if (nslots > 0 && base->tp_itemsize != 0) {
992 PyErr_Format(PyExc_TypeError,
993 "nonempty __slots__ "
994 "not supported for subtype of '%s'",
995 base->tp_name);
996 return NULL;
998 for (i = 0; i < nslots; i++) {
999 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
1000 PyErr_SetString(PyExc_TypeError,
1001 "__slots__ must be a sequence of strings");
1002 Py_DECREF(slots);
1003 return NULL;
1005 /* XXX Check against null bytes in name */
1008 if (slots != NULL) {
1009 /* See if *this* class defines __getstate__ */
1010 PyObject *getstate = PyDict_GetItemString(dict,
1011 "__getstate__");
1012 if (getstate == NULL) {
1013 /* If not, provide a bozo that raises TypeError */
1014 if (bozo_obj == NULL) {
1015 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1016 if (bozo_obj == NULL) {
1017 /* XXX decref various things */
1018 return NULL;
1021 if (PyDict_SetItemString(dict,
1022 "__getstate__",
1023 bozo_obj) < 0) {
1024 /* XXX decref various things */
1025 return NULL;
1029 if (slots == NULL && base->tp_dictoffset == 0 &&
1030 (base->tp_setattro == PyObject_GenericSetAttr ||
1031 base->tp_setattro == NULL)) {
1032 add_dict++;
1034 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1035 base->tp_itemsize == 0) {
1036 nslots++;
1037 add_weak++;
1040 /* XXX From here until type is safely allocated,
1041 "return NULL" may leak slots! */
1043 /* Allocate the type object */
1044 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1045 if (type == NULL)
1046 return NULL;
1048 /* Keep name and slots alive in the extended type object */
1049 et = (etype *)type;
1050 Py_INCREF(name);
1051 et->name = name;
1052 et->slots = slots;
1054 /* Initialize tp_flags */
1055 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1056 Py_TPFLAGS_BASETYPE;
1057 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1058 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1060 /* It's a new-style number unless it specifically inherits any
1061 old-style numeric behavior */
1062 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1063 (base->tp_as_number == NULL))
1064 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1066 /* Initialize essential fields */
1067 type->tp_as_number = &et->as_number;
1068 type->tp_as_sequence = &et->as_sequence;
1069 type->tp_as_mapping = &et->as_mapping;
1070 type->tp_as_buffer = &et->as_buffer;
1071 type->tp_name = PyString_AS_STRING(name);
1073 /* Set tp_base and tp_bases */
1074 type->tp_bases = bases;
1075 Py_INCREF(base);
1076 type->tp_base = base;
1078 /* Initialize tp_dict from passed-in dict */
1079 type->tp_dict = dict = PyDict_Copy(dict);
1080 if (dict == NULL) {
1081 Py_DECREF(type);
1082 return NULL;
1085 /* Set __module__ in the dict */
1086 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1087 tmp = PyEval_GetGlobals();
1088 if (tmp != NULL) {
1089 tmp = PyDict_GetItemString(tmp, "__name__");
1090 if (tmp != NULL) {
1091 if (PyDict_SetItemString(dict, "__module__",
1092 tmp) < 0)
1093 return NULL;
1098 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1099 and is a string. The __doc__ accessor will first look for tp_doc;
1100 if that fails, it will still look into __dict__.
1103 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1104 if (doc != NULL && PyString_Check(doc)) {
1105 const size_t n = (size_t)PyString_GET_SIZE(doc);
1106 type->tp_doc = (char *)PyObject_MALLOC(n+1);
1107 if (type->tp_doc == NULL) {
1108 Py_DECREF(type);
1109 return NULL;
1111 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1115 /* Special-case __new__: if it's a plain function,
1116 make it a static function */
1117 tmp = PyDict_GetItemString(dict, "__new__");
1118 if (tmp != NULL && PyFunction_Check(tmp)) {
1119 tmp = PyStaticMethod_New(tmp);
1120 if (tmp == NULL) {
1121 Py_DECREF(type);
1122 return NULL;
1124 PyDict_SetItemString(dict, "__new__", tmp);
1125 Py_DECREF(tmp);
1128 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1129 mp = et->members;
1130 slotoffset = base->tp_basicsize;
1131 if (slots != NULL) {
1132 for (i = 0; i < nslots; i++, mp++) {
1133 mp->name = PyString_AS_STRING(
1134 PyTuple_GET_ITEM(slots, i));
1135 mp->type = T_OBJECT_EX;
1136 mp->offset = slotoffset;
1137 if (base->tp_weaklistoffset == 0 &&
1138 strcmp(mp->name, "__weakref__") == 0) {
1139 mp->type = T_OBJECT;
1140 type->tp_weaklistoffset = slotoffset;
1142 slotoffset += sizeof(PyObject *);
1145 else {
1146 if (add_dict) {
1147 if (base->tp_itemsize)
1148 type->tp_dictoffset =
1149 -(long)sizeof(PyObject *);
1150 else
1151 type->tp_dictoffset = slotoffset;
1152 slotoffset += sizeof(PyObject *);
1153 type->tp_getset = subtype_getsets;
1155 if (add_weak) {
1156 assert(!base->tp_itemsize);
1157 type->tp_weaklistoffset = slotoffset;
1158 mp->name = "__weakref__";
1159 mp->type = T_OBJECT;
1160 mp->offset = slotoffset;
1161 mp->flags = READONLY;
1162 mp++;
1163 slotoffset += sizeof(PyObject *);
1166 type->tp_basicsize = slotoffset;
1167 type->tp_itemsize = base->tp_itemsize;
1168 type->tp_members = et->members;
1170 /* Special case some slots */
1171 if (type->tp_dictoffset != 0 || nslots > 0) {
1172 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1173 type->tp_getattro = PyObject_GenericGetAttr;
1174 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1175 type->tp_setattro = PyObject_GenericSetAttr;
1177 type->tp_dealloc = subtype_dealloc;
1179 /* Enable GC unless there are really no instance variables possible */
1180 if (!(type->tp_basicsize == sizeof(PyObject) &&
1181 type->tp_itemsize == 0))
1182 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1184 /* Always override allocation strategy to use regular heap */
1185 type->tp_alloc = PyType_GenericAlloc;
1186 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1187 type->tp_free = _PyObject_GC_Del;
1188 type->tp_traverse = subtype_traverse;
1189 type->tp_clear = base->tp_clear;
1191 else
1192 type->tp_free = _PyObject_Del;
1194 /* Initialize the rest */
1195 if (PyType_Ready(type) < 0) {
1196 Py_DECREF(type);
1197 return NULL;
1200 /* Put the proper slots in place */
1201 fixup_slot_dispatchers(type);
1203 return (PyObject *)type;
1206 /* Internal API to look for a name through the MRO.
1207 This returns a borrowed reference, and doesn't set an exception! */
1208 PyObject *
1209 _PyType_Lookup(PyTypeObject *type, PyObject *name)
1211 int i, n;
1212 PyObject *mro, *res, *base, *dict;
1214 /* Look in tp_dict of types in MRO */
1215 mro = type->tp_mro;
1216 assert(PyTuple_Check(mro));
1217 n = PyTuple_GET_SIZE(mro);
1218 for (i = 0; i < n; i++) {
1219 base = PyTuple_GET_ITEM(mro, i);
1220 if (PyClass_Check(base))
1221 dict = ((PyClassObject *)base)->cl_dict;
1222 else {
1223 assert(PyType_Check(base));
1224 dict = ((PyTypeObject *)base)->tp_dict;
1226 assert(dict && PyDict_Check(dict));
1227 res = PyDict_GetItem(dict, name);
1228 if (res != NULL)
1229 return res;
1231 return NULL;
1234 /* This is similar to PyObject_GenericGetAttr(),
1235 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1236 static PyObject *
1237 type_getattro(PyTypeObject *type, PyObject *name)
1239 PyTypeObject *metatype = type->ob_type;
1240 PyObject *descr, *res;
1241 descrgetfunc f;
1243 /* Initialize this type (we'll assume the metatype is initialized) */
1244 if (type->tp_dict == NULL) {
1245 if (PyType_Ready(type) < 0)
1246 return NULL;
1249 /* Get a descriptor from the metatype */
1250 descr = _PyType_Lookup(metatype, name);
1251 f = NULL;
1252 if (descr != NULL) {
1253 f = descr->ob_type->tp_descr_get;
1254 if (f != NULL && PyDescr_IsData(descr))
1255 return f(descr,
1256 (PyObject *)type, (PyObject *)metatype);
1259 /* Look in tp_dict of this type and its bases */
1260 res = _PyType_Lookup(type, name);
1261 if (res != NULL) {
1262 f = res->ob_type->tp_descr_get;
1263 if (f != NULL)
1264 return f(res, (PyObject *)NULL, (PyObject *)type);
1265 Py_INCREF(res);
1266 return res;
1269 /* Use the descriptor from the metatype */
1270 if (f != NULL) {
1271 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1272 return res;
1274 if (descr != NULL) {
1275 Py_INCREF(descr);
1276 return descr;
1279 /* Give up */
1280 PyErr_Format(PyExc_AttributeError,
1281 "type object '%.50s' has no attribute '%.400s'",
1282 type->tp_name, PyString_AS_STRING(name));
1283 return NULL;
1286 static int
1287 type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1289 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1290 PyErr_Format(
1291 PyExc_TypeError,
1292 "can't set attributes of built-in/extension type '%s'",
1293 type->tp_name);
1294 return -1;
1296 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1297 return -1;
1298 return update_slot(type, name);
1301 static void
1302 type_dealloc(PyTypeObject *type)
1304 etype *et;
1306 /* Assert this is a heap-allocated type object */
1307 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1308 _PyObject_GC_UNTRACK(type);
1309 PyObject_ClearWeakRefs((PyObject *)type);
1310 et = (etype *)type;
1311 Py_XDECREF(type->tp_base);
1312 Py_XDECREF(type->tp_dict);
1313 Py_XDECREF(type->tp_bases);
1314 Py_XDECREF(type->tp_mro);
1315 Py_XDECREF(type->tp_cache);
1316 Py_XDECREF(type->tp_subclasses);
1317 Py_XDECREF(et->name);
1318 Py_XDECREF(et->slots);
1319 type->ob_type->tp_free((PyObject *)type);
1322 static PyObject *
1323 type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1325 PyObject *list, *raw, *ref;
1326 int i, n;
1328 list = PyList_New(0);
1329 if (list == NULL)
1330 return NULL;
1331 raw = type->tp_subclasses;
1332 if (raw == NULL)
1333 return list;
1334 assert(PyList_Check(raw));
1335 n = PyList_GET_SIZE(raw);
1336 for (i = 0; i < n; i++) {
1337 ref = PyList_GET_ITEM(raw, i);
1338 assert(PyWeakref_CheckRef(ref));
1339 ref = PyWeakref_GET_OBJECT(ref);
1340 if (ref != Py_None) {
1341 if (PyList_Append(list, ref) < 0) {
1342 Py_DECREF(list);
1343 return NULL;
1347 return list;
1350 static PyMethodDef type_methods[] = {
1351 {"mro", (PyCFunction)mro_external, METH_NOARGS,
1352 "mro() -> list\nreturn a type's method resolution order"},
1353 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1354 "__subclasses__() -> list of immediate subclasses"},
1358 static char type_doc[] =
1359 "type(object) -> the object's type\n"
1360 "type(name, bases, dict) -> a new type";
1362 static int
1363 type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1365 etype *et;
1366 int err;
1368 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1369 return 0;
1371 et = (etype *)type;
1373 #define VISIT(SLOT) \
1374 if (SLOT) { \
1375 err = visit((PyObject *)(SLOT), arg); \
1376 if (err) \
1377 return err; \
1380 VISIT(type->tp_dict);
1381 VISIT(type->tp_cache);
1382 VISIT(type->tp_mro);
1383 VISIT(type->tp_bases);
1384 VISIT(type->tp_base);
1385 VISIT(type->tp_subclasses);
1386 VISIT(et->slots);
1388 #undef VISIT
1390 return 0;
1393 static int
1394 type_clear(PyTypeObject *type)
1396 etype *et;
1397 PyObject *tmp;
1399 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1400 return 0;
1402 et = (etype *)type;
1404 #define CLEAR(SLOT) \
1405 if (SLOT) { \
1406 tmp = (PyObject *)(SLOT); \
1407 SLOT = NULL; \
1408 Py_DECREF(tmp); \
1411 CLEAR(type->tp_dict);
1412 CLEAR(type->tp_cache);
1413 CLEAR(type->tp_mro);
1414 CLEAR(type->tp_bases);
1415 CLEAR(type->tp_base);
1416 CLEAR(type->tp_subclasses);
1417 CLEAR(et->slots);
1419 if (type->tp_doc != NULL) {
1420 PyObject_FREE(type->tp_doc);
1421 type->tp_doc = NULL;
1424 #undef CLEAR
1426 return 0;
1429 static int
1430 type_is_gc(PyTypeObject *type)
1432 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1435 PyTypeObject PyType_Type = {
1436 PyObject_HEAD_INIT(&PyType_Type)
1437 0, /* ob_size */
1438 "type", /* tp_name */
1439 sizeof(etype), /* tp_basicsize */
1440 sizeof(PyMemberDef), /* tp_itemsize */
1441 (destructor)type_dealloc, /* tp_dealloc */
1442 0, /* tp_print */
1443 0, /* tp_getattr */
1444 0, /* tp_setattr */
1445 type_compare, /* tp_compare */
1446 (reprfunc)type_repr, /* tp_repr */
1447 0, /* tp_as_number */
1448 0, /* tp_as_sequence */
1449 0, /* tp_as_mapping */
1450 (hashfunc)_Py_HashPointer, /* tp_hash */
1451 (ternaryfunc)type_call, /* tp_call */
1452 0, /* tp_str */
1453 (getattrofunc)type_getattro, /* tp_getattro */
1454 (setattrofunc)type_setattro, /* tp_setattro */
1455 0, /* tp_as_buffer */
1456 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1457 Py_TPFLAGS_BASETYPE, /* tp_flags */
1458 type_doc, /* tp_doc */
1459 (traverseproc)type_traverse, /* tp_traverse */
1460 (inquiry)type_clear, /* tp_clear */
1461 0, /* tp_richcompare */
1462 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
1463 0, /* tp_iter */
1464 0, /* tp_iternext */
1465 type_methods, /* tp_methods */
1466 type_members, /* tp_members */
1467 type_getsets, /* tp_getset */
1468 0, /* tp_base */
1469 0, /* tp_dict */
1470 0, /* tp_descr_get */
1471 0, /* tp_descr_set */
1472 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1473 0, /* tp_init */
1474 0, /* tp_alloc */
1475 type_new, /* tp_new */
1476 _PyObject_GC_Del, /* tp_free */
1477 (inquiry)type_is_gc, /* tp_is_gc */
1481 /* The base type of all types (eventually)... except itself. */
1483 static int
1484 object_init(PyObject *self, PyObject *args, PyObject *kwds)
1486 return 0;
1489 static void
1490 object_dealloc(PyObject *self)
1492 self->ob_type->tp_free(self);
1495 static PyObject *
1496 object_repr(PyObject *self)
1498 PyTypeObject *type;
1499 PyObject *mod, *name, *rtn;
1501 type = self->ob_type;
1502 mod = type_module(type, NULL);
1503 if (mod == NULL)
1504 PyErr_Clear();
1505 else if (!PyString_Check(mod)) {
1506 Py_DECREF(mod);
1507 mod = NULL;
1509 name = type_name(type, NULL);
1510 if (name == NULL)
1511 return NULL;
1512 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
1513 rtn = PyString_FromFormat("<%s.%s object at %p>",
1514 PyString_AS_STRING(mod),
1515 PyString_AS_STRING(name),
1516 self);
1517 else
1518 rtn = PyString_FromFormat("<%s object at %p>",
1519 type->tp_name, self);
1520 Py_XDECREF(mod);
1521 Py_DECREF(name);
1522 return rtn;
1525 static PyObject *
1526 object_str(PyObject *self)
1528 unaryfunc f;
1530 f = self->ob_type->tp_repr;
1531 if (f == NULL)
1532 f = object_repr;
1533 return f(self);
1536 static long
1537 object_hash(PyObject *self)
1539 return _Py_HashPointer(self);
1542 static PyObject *
1543 object_get_class(PyObject *self, void *closure)
1545 Py_INCREF(self->ob_type);
1546 return (PyObject *)(self->ob_type);
1549 static int
1550 equiv_structs(PyTypeObject *a, PyTypeObject *b)
1552 return a == b ||
1553 (a != NULL &&
1554 b != NULL &&
1555 a->tp_basicsize == b->tp_basicsize &&
1556 a->tp_itemsize == b->tp_itemsize &&
1557 a->tp_dictoffset == b->tp_dictoffset &&
1558 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1559 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1560 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1563 static int
1564 same_slots_added(PyTypeObject *a, PyTypeObject *b)
1566 PyTypeObject *base = a->tp_base;
1567 int size;
1569 if (base != b->tp_base)
1570 return 0;
1571 if (equiv_structs(a, base) && equiv_structs(b, base))
1572 return 1;
1573 size = base->tp_basicsize;
1574 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1575 size += sizeof(PyObject *);
1576 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1577 size += sizeof(PyObject *);
1578 return size == a->tp_basicsize && size == b->tp_basicsize;
1581 static int
1582 object_set_class(PyObject *self, PyObject *value, void *closure)
1584 PyTypeObject *old = self->ob_type;
1585 PyTypeObject *new, *newbase, *oldbase;
1587 if (!PyType_Check(value)) {
1588 PyErr_Format(PyExc_TypeError,
1589 "__class__ must be set to new-style class, not '%s' object",
1590 value->ob_type->tp_name);
1591 return -1;
1593 new = (PyTypeObject *)value;
1594 newbase = new;
1595 oldbase = old;
1596 while (equiv_structs(newbase, newbase->tp_base))
1597 newbase = newbase->tp_base;
1598 while (equiv_structs(oldbase, oldbase->tp_base))
1599 oldbase = oldbase->tp_base;
1600 if (newbase != oldbase &&
1601 (newbase->tp_base != oldbase->tp_base ||
1602 !same_slots_added(newbase, oldbase))) {
1603 PyErr_Format(PyExc_TypeError,
1604 "__class__ assignment: "
1605 "'%s' object layout differs from '%s'",
1606 new->tp_name,
1607 old->tp_name);
1608 return -1;
1610 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1611 Py_INCREF(new);
1613 self->ob_type = new;
1614 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1615 Py_DECREF(old);
1617 return 0;
1620 static PyGetSetDef object_getsets[] = {
1621 {"__class__", object_get_class, object_set_class,
1622 "the object's class"},
1626 static PyObject *
1627 object_reduce(PyObject *self, PyObject *args)
1629 /* Call copy_reg._reduce(self) */
1630 static PyObject *copy_reg_str;
1631 PyObject *copy_reg, *res;
1633 if (!copy_reg_str) {
1634 copy_reg_str = PyString_InternFromString("copy_reg");
1635 if (copy_reg_str == NULL)
1636 return NULL;
1638 copy_reg = PyImport_Import(copy_reg_str);
1639 if (!copy_reg)
1640 return NULL;
1641 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1642 Py_DECREF(copy_reg);
1643 return res;
1646 static PyMethodDef object_methods[] = {
1647 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1651 PyTypeObject PyBaseObject_Type = {
1652 PyObject_HEAD_INIT(&PyType_Type)
1653 0, /* ob_size */
1654 "object", /* tp_name */
1655 sizeof(PyObject), /* tp_basicsize */
1656 0, /* tp_itemsize */
1657 (destructor)object_dealloc, /* tp_dealloc */
1658 0, /* tp_print */
1659 0, /* tp_getattr */
1660 0, /* tp_setattr */
1661 0, /* tp_compare */
1662 object_repr, /* tp_repr */
1663 0, /* tp_as_number */
1664 0, /* tp_as_sequence */
1665 0, /* tp_as_mapping */
1666 object_hash, /* tp_hash */
1667 0, /* tp_call */
1668 object_str, /* tp_str */
1669 PyObject_GenericGetAttr, /* tp_getattro */
1670 PyObject_GenericSetAttr, /* tp_setattro */
1671 0, /* tp_as_buffer */
1672 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1673 "The most base type", /* tp_doc */
1674 0, /* tp_traverse */
1675 0, /* tp_clear */
1676 0, /* tp_richcompare */
1677 0, /* tp_weaklistoffset */
1678 0, /* tp_iter */
1679 0, /* tp_iternext */
1680 object_methods, /* tp_methods */
1681 0, /* tp_members */
1682 object_getsets, /* tp_getset */
1683 0, /* tp_base */
1684 0, /* tp_dict */
1685 0, /* tp_descr_get */
1686 0, /* tp_descr_set */
1687 0, /* tp_dictoffset */
1688 object_init, /* tp_init */
1689 PyType_GenericAlloc, /* tp_alloc */
1690 PyType_GenericNew, /* tp_new */
1691 _PyObject_Del, /* tp_free */
1695 /* Initialize the __dict__ in a type object */
1697 static int
1698 add_methods(PyTypeObject *type, PyMethodDef *meth)
1700 PyObject *dict = type->tp_dict;
1702 for (; meth->ml_name != NULL; meth++) {
1703 PyObject *descr;
1704 if (PyDict_GetItemString(dict, meth->ml_name))
1705 continue;
1706 descr = PyDescr_NewMethod(type, meth);
1707 if (descr == NULL)
1708 return -1;
1709 if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
1710 return -1;
1711 Py_DECREF(descr);
1713 return 0;
1716 static int
1717 add_members(PyTypeObject *type, PyMemberDef *memb)
1719 PyObject *dict = type->tp_dict;
1721 for (; memb->name != NULL; memb++) {
1722 PyObject *descr;
1723 if (PyDict_GetItemString(dict, memb->name))
1724 continue;
1725 descr = PyDescr_NewMember(type, memb);
1726 if (descr == NULL)
1727 return -1;
1728 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1729 return -1;
1730 Py_DECREF(descr);
1732 return 0;
1735 static int
1736 add_getset(PyTypeObject *type, PyGetSetDef *gsp)
1738 PyObject *dict = type->tp_dict;
1740 for (; gsp->name != NULL; gsp++) {
1741 PyObject *descr;
1742 if (PyDict_GetItemString(dict, gsp->name))
1743 continue;
1744 descr = PyDescr_NewGetSet(type, gsp);
1746 if (descr == NULL)
1747 return -1;
1748 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1749 return -1;
1750 Py_DECREF(descr);
1752 return 0;
1755 static void
1756 inherit_special(PyTypeObject *type, PyTypeObject *base)
1758 int oldsize, newsize;
1760 /* Special flag magic */
1761 if (!type->tp_as_buffer && base->tp_as_buffer) {
1762 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1763 type->tp_flags |=
1764 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1766 if (!type->tp_as_sequence && base->tp_as_sequence) {
1767 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1768 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1770 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1771 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1772 if ((!type->tp_as_number && base->tp_as_number) ||
1773 (!type->tp_as_sequence && base->tp_as_sequence)) {
1774 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1775 if (!type->tp_as_number && !type->tp_as_sequence) {
1776 type->tp_flags |= base->tp_flags &
1777 Py_TPFLAGS_HAVE_INPLACEOPS;
1780 /* Wow */
1782 if (!type->tp_as_number && base->tp_as_number) {
1783 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1784 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1787 /* Copying basicsize is connected to the GC flags */
1788 oldsize = base->tp_basicsize;
1789 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1790 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1791 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1792 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1793 (!type->tp_traverse && !type->tp_clear)) {
1794 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1795 if (type->tp_traverse == NULL)
1796 type->tp_traverse = base->tp_traverse;
1797 if (type->tp_clear == NULL)
1798 type->tp_clear = base->tp_clear;
1800 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1801 /* The condition below could use some explanation.
1802 It appears that tp_new is not inherited for static types
1803 whose base class is 'object'; this seems to be a precaution
1804 so that old extension types don't suddenly become
1805 callable (object.__new__ wouldn't insure the invariants
1806 that the extension type's own factory function ensures).
1807 Heap types, of course, are under our control, so they do
1808 inherit tp_new; static extension types that specify some
1809 other built-in type as the default are considered
1810 new-style-aware so they also inherit object.__new__. */
1811 if (base != &PyBaseObject_Type ||
1812 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1813 if (type->tp_new == NULL)
1814 type->tp_new = base->tp_new;
1817 type->tp_basicsize = newsize;
1819 /* Copy other non-function slots */
1821 #undef COPYVAL
1822 #define COPYVAL(SLOT) \
1823 if (type->SLOT == 0) type->SLOT = base->SLOT
1825 COPYVAL(tp_itemsize);
1826 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1827 COPYVAL(tp_weaklistoffset);
1829 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1830 COPYVAL(tp_dictoffset);
1834 static void
1835 inherit_slots(PyTypeObject *type, PyTypeObject *base)
1837 PyTypeObject *basebase;
1839 #undef SLOTDEFINED
1840 #undef COPYSLOT
1841 #undef COPYNUM
1842 #undef COPYSEQ
1843 #undef COPYMAP
1844 #undef COPYBUF
1846 #define SLOTDEFINED(SLOT) \
1847 (base->SLOT != 0 && \
1848 (basebase == NULL || base->SLOT != basebase->SLOT))
1850 #define COPYSLOT(SLOT) \
1851 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
1853 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1854 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1855 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1856 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
1858 /* This won't inherit indirect slots (from tp_as_number etc.)
1859 if type doesn't provide the space. */
1861 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1862 basebase = base->tp_base;
1863 if (basebase->tp_as_number == NULL)
1864 basebase = NULL;
1865 COPYNUM(nb_add);
1866 COPYNUM(nb_subtract);
1867 COPYNUM(nb_multiply);
1868 COPYNUM(nb_divide);
1869 COPYNUM(nb_remainder);
1870 COPYNUM(nb_divmod);
1871 COPYNUM(nb_power);
1872 COPYNUM(nb_negative);
1873 COPYNUM(nb_positive);
1874 COPYNUM(nb_absolute);
1875 COPYNUM(nb_nonzero);
1876 COPYNUM(nb_invert);
1877 COPYNUM(nb_lshift);
1878 COPYNUM(nb_rshift);
1879 COPYNUM(nb_and);
1880 COPYNUM(nb_xor);
1881 COPYNUM(nb_or);
1882 COPYNUM(nb_coerce);
1883 COPYNUM(nb_int);
1884 COPYNUM(nb_long);
1885 COPYNUM(nb_float);
1886 COPYNUM(nb_oct);
1887 COPYNUM(nb_hex);
1888 COPYNUM(nb_inplace_add);
1889 COPYNUM(nb_inplace_subtract);
1890 COPYNUM(nb_inplace_multiply);
1891 COPYNUM(nb_inplace_divide);
1892 COPYNUM(nb_inplace_remainder);
1893 COPYNUM(nb_inplace_power);
1894 COPYNUM(nb_inplace_lshift);
1895 COPYNUM(nb_inplace_rshift);
1896 COPYNUM(nb_inplace_and);
1897 COPYNUM(nb_inplace_xor);
1898 COPYNUM(nb_inplace_or);
1899 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1900 COPYNUM(nb_true_divide);
1901 COPYNUM(nb_floor_divide);
1902 COPYNUM(nb_inplace_true_divide);
1903 COPYNUM(nb_inplace_floor_divide);
1907 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1908 basebase = base->tp_base;
1909 if (basebase->tp_as_sequence == NULL)
1910 basebase = NULL;
1911 COPYSEQ(sq_length);
1912 COPYSEQ(sq_concat);
1913 COPYSEQ(sq_repeat);
1914 COPYSEQ(sq_item);
1915 COPYSEQ(sq_slice);
1916 COPYSEQ(sq_ass_item);
1917 COPYSEQ(sq_ass_slice);
1918 COPYSEQ(sq_contains);
1919 COPYSEQ(sq_inplace_concat);
1920 COPYSEQ(sq_inplace_repeat);
1923 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1924 basebase = base->tp_base;
1925 if (basebase->tp_as_mapping == NULL)
1926 basebase = NULL;
1927 COPYMAP(mp_length);
1928 COPYMAP(mp_subscript);
1929 COPYMAP(mp_ass_subscript);
1932 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1933 basebase = base->tp_base;
1934 if (basebase->tp_as_buffer == NULL)
1935 basebase = NULL;
1936 COPYBUF(bf_getreadbuffer);
1937 COPYBUF(bf_getwritebuffer);
1938 COPYBUF(bf_getsegcount);
1939 COPYBUF(bf_getcharbuffer);
1942 basebase = base->tp_base;
1944 COPYSLOT(tp_dealloc);
1945 COPYSLOT(tp_print);
1946 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1947 type->tp_getattr = base->tp_getattr;
1948 type->tp_getattro = base->tp_getattro;
1950 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1951 type->tp_setattr = base->tp_setattr;
1952 type->tp_setattro = base->tp_setattro;
1954 /* tp_compare see tp_richcompare */
1955 COPYSLOT(tp_repr);
1956 /* tp_hash see tp_richcompare */
1957 COPYSLOT(tp_call);
1958 COPYSLOT(tp_str);
1959 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
1960 if (type->tp_compare == NULL &&
1961 type->tp_richcompare == NULL &&
1962 type->tp_hash == NULL)
1964 type->tp_compare = base->tp_compare;
1965 type->tp_richcompare = base->tp_richcompare;
1966 type->tp_hash = base->tp_hash;
1969 else {
1970 COPYSLOT(tp_compare);
1972 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1973 COPYSLOT(tp_iter);
1974 COPYSLOT(tp_iternext);
1976 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1977 COPYSLOT(tp_descr_get);
1978 COPYSLOT(tp_descr_set);
1979 COPYSLOT(tp_dictoffset);
1980 COPYSLOT(tp_init);
1981 COPYSLOT(tp_alloc);
1982 COPYSLOT(tp_free);
1983 COPYSLOT(tp_is_gc);
1987 staticforward int add_operators(PyTypeObject *);
1988 staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
1991 PyType_Ready(PyTypeObject *type)
1993 PyObject *dict, *bases;
1994 PyTypeObject *base;
1995 int i, n;
1997 if (type->tp_flags & Py_TPFLAGS_READY) {
1998 assert(type->tp_dict != NULL);
1999 return 0;
2001 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
2003 type->tp_flags |= Py_TPFLAGS_READYING;
2005 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2006 base = type->tp_base;
2007 if (base == NULL && type != &PyBaseObject_Type)
2008 base = type->tp_base = &PyBaseObject_Type;
2010 /* Initialize ob_type if NULL. This means extensions that want to be
2011 compilable separately on Windows can call PyType_Ready() instead of
2012 initializing the ob_type field of their type objects. */
2013 if (type->ob_type == NULL)
2014 type->ob_type = base->ob_type;
2016 /* Initialize tp_bases */
2017 bases = type->tp_bases;
2018 if (bases == NULL) {
2019 if (base == NULL)
2020 bases = PyTuple_New(0);
2021 else
2022 bases = Py_BuildValue("(O)", base);
2023 if (bases == NULL)
2024 goto error;
2025 type->tp_bases = bases;
2028 /* Initialize the base class */
2029 if (base && base->tp_dict == NULL) {
2030 if (PyType_Ready(base) < 0)
2031 goto error;
2034 /* Initialize tp_dict */
2035 dict = type->tp_dict;
2036 if (dict == NULL) {
2037 dict = PyDict_New();
2038 if (dict == NULL)
2039 goto error;
2040 type->tp_dict = dict;
2043 /* Add type-specific descriptors to tp_dict */
2044 if (add_operators(type) < 0)
2045 goto error;
2046 if (type->tp_methods != NULL) {
2047 if (add_methods(type, type->tp_methods) < 0)
2048 goto error;
2050 if (type->tp_members != NULL) {
2051 if (add_members(type, type->tp_members) < 0)
2052 goto error;
2054 if (type->tp_getset != NULL) {
2055 if (add_getset(type, type->tp_getset) < 0)
2056 goto error;
2059 /* Calculate method resolution order */
2060 if (mro_internal(type) < 0) {
2061 goto error;
2064 /* Inherit special flags from dominant base */
2065 if (type->tp_base != NULL)
2066 inherit_special(type, type->tp_base);
2068 /* Initialize tp_dict properly */
2069 bases = type->tp_mro;
2070 assert(bases != NULL);
2071 assert(PyTuple_Check(bases));
2072 n = PyTuple_GET_SIZE(bases);
2073 for (i = 1; i < n; i++) {
2074 PyObject *b = PyTuple_GET_ITEM(bases, i);
2075 if (PyType_Check(b))
2076 inherit_slots(type, (PyTypeObject *)b);
2079 /* if the type dictionary doesn't contain a __doc__, set it from
2080 the tp_doc slot.
2082 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2083 if (type->tp_doc != NULL) {
2084 PyObject *doc = PyString_FromString(type->tp_doc);
2085 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2086 Py_DECREF(doc);
2087 } else {
2088 PyDict_SetItemString(type->tp_dict, "__doc__", Py_None);
2092 /* Some more special stuff */
2093 base = type->tp_base;
2094 if (base != NULL) {
2095 if (type->tp_as_number == NULL)
2096 type->tp_as_number = base->tp_as_number;
2097 if (type->tp_as_sequence == NULL)
2098 type->tp_as_sequence = base->tp_as_sequence;
2099 if (type->tp_as_mapping == NULL)
2100 type->tp_as_mapping = base->tp_as_mapping;
2103 /* Link into each base class's list of subclasses */
2104 bases = type->tp_bases;
2105 n = PyTuple_GET_SIZE(bases);
2106 for (i = 0; i < n; i++) {
2107 PyObject *b = PyTuple_GET_ITEM(bases, i);
2108 if (PyType_Check(b) &&
2109 add_subclass((PyTypeObject *)b, type) < 0)
2110 goto error;
2113 /* All done -- set the ready flag */
2114 assert(type->tp_dict != NULL);
2115 type->tp_flags =
2116 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
2117 return 0;
2119 error:
2120 type->tp_flags &= ~Py_TPFLAGS_READYING;
2121 return -1;
2124 static int
2125 add_subclass(PyTypeObject *base, PyTypeObject *type)
2127 int i;
2128 PyObject *list, *ref, *new;
2130 list = base->tp_subclasses;
2131 if (list == NULL) {
2132 base->tp_subclasses = list = PyList_New(0);
2133 if (list == NULL)
2134 return -1;
2136 assert(PyList_Check(list));
2137 new = PyWeakref_NewRef((PyObject *)type, NULL);
2138 i = PyList_GET_SIZE(list);
2139 while (--i >= 0) {
2140 ref = PyList_GET_ITEM(list, i);
2141 assert(PyWeakref_CheckRef(ref));
2142 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2143 return PyList_SetItem(list, i, new);
2145 i = PyList_Append(list, new);
2146 Py_DECREF(new);
2147 return i;
2151 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
2153 /* There's a wrapper *function* for each distinct function typedef used
2154 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2155 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2156 Most tables have only one entry; the tables for binary operators have two
2157 entries, one regular and one with reversed arguments. */
2159 static PyObject *
2160 wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2162 inquiry func = (inquiry)wrapped;
2163 int res;
2165 if (!PyArg_ParseTuple(args, ""))
2166 return NULL;
2167 res = (*func)(self);
2168 if (res == -1 && PyErr_Occurred())
2169 return NULL;
2170 return PyInt_FromLong((long)res);
2173 static PyObject *
2174 wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2176 binaryfunc func = (binaryfunc)wrapped;
2177 PyObject *other;
2179 if (!PyArg_ParseTuple(args, "O", &other))
2180 return NULL;
2181 return (*func)(self, other);
2184 static PyObject *
2185 wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2187 binaryfunc func = (binaryfunc)wrapped;
2188 PyObject *other;
2190 if (!PyArg_ParseTuple(args, "O", &other))
2191 return NULL;
2192 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2193 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2194 Py_INCREF(Py_NotImplemented);
2195 return Py_NotImplemented;
2197 return (*func)(self, other);
2200 static PyObject *
2201 wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2203 binaryfunc func = (binaryfunc)wrapped;
2204 PyObject *other;
2206 if (!PyArg_ParseTuple(args, "O", &other))
2207 return NULL;
2208 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2209 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2210 Py_INCREF(Py_NotImplemented);
2211 return Py_NotImplemented;
2213 return (*func)(other, self);
2216 static PyObject *
2217 wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2219 coercion func = (coercion)wrapped;
2220 PyObject *other, *res;
2221 int ok;
2223 if (!PyArg_ParseTuple(args, "O", &other))
2224 return NULL;
2225 ok = func(&self, &other);
2226 if (ok < 0)
2227 return NULL;
2228 if (ok > 0) {
2229 Py_INCREF(Py_NotImplemented);
2230 return Py_NotImplemented;
2232 res = PyTuple_New(2);
2233 if (res == NULL) {
2234 Py_DECREF(self);
2235 Py_DECREF(other);
2236 return NULL;
2238 PyTuple_SET_ITEM(res, 0, self);
2239 PyTuple_SET_ITEM(res, 1, other);
2240 return res;
2243 static PyObject *
2244 wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2246 ternaryfunc func = (ternaryfunc)wrapped;
2247 PyObject *other;
2248 PyObject *third = Py_None;
2250 /* Note: This wrapper only works for __pow__() */
2252 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2253 return NULL;
2254 return (*func)(self, other, third);
2257 static PyObject *
2258 wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2260 ternaryfunc func = (ternaryfunc)wrapped;
2261 PyObject *other;
2262 PyObject *third = Py_None;
2264 /* Note: This wrapper only works for __pow__() */
2266 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2267 return NULL;
2268 return (*func)(other, self, third);
2271 static PyObject *
2272 wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2274 unaryfunc func = (unaryfunc)wrapped;
2276 if (!PyArg_ParseTuple(args, ""))
2277 return NULL;
2278 return (*func)(self);
2281 static PyObject *
2282 wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2284 intargfunc func = (intargfunc)wrapped;
2285 int i;
2287 if (!PyArg_ParseTuple(args, "i", &i))
2288 return NULL;
2289 return (*func)(self, i);
2292 static int
2293 getindex(PyObject *self, PyObject *arg)
2295 int i;
2297 i = PyInt_AsLong(arg);
2298 if (i == -1 && PyErr_Occurred())
2299 return -1;
2300 if (i < 0) {
2301 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2302 if (sq && sq->sq_length) {
2303 int n = (*sq->sq_length)(self);
2304 if (n < 0)
2305 return -1;
2306 i += n;
2309 return i;
2312 static PyObject *
2313 wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2315 intargfunc func = (intargfunc)wrapped;
2316 PyObject *arg;
2317 int i;
2319 if (PyTuple_GET_SIZE(args) == 1) {
2320 arg = PyTuple_GET_ITEM(args, 0);
2321 i = getindex(self, arg);
2322 if (i == -1 && PyErr_Occurred())
2323 return NULL;
2324 return (*func)(self, i);
2326 PyArg_ParseTuple(args, "O", &arg);
2327 assert(PyErr_Occurred());
2328 return NULL;
2331 static PyObject *
2332 wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2334 intintargfunc func = (intintargfunc)wrapped;
2335 int i, j;
2337 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2338 return NULL;
2339 return (*func)(self, i, j);
2342 static PyObject *
2343 wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
2345 intobjargproc func = (intobjargproc)wrapped;
2346 int i, res;
2347 PyObject *arg, *value;
2349 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2350 return NULL;
2351 i = getindex(self, arg);
2352 if (i == -1 && PyErr_Occurred())
2353 return NULL;
2354 res = (*func)(self, i, value);
2355 if (res == -1 && PyErr_Occurred())
2356 return NULL;
2357 Py_INCREF(Py_None);
2358 return Py_None;
2361 static PyObject *
2362 wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
2364 intobjargproc func = (intobjargproc)wrapped;
2365 int i, res;
2366 PyObject *arg;
2368 if (!PyArg_ParseTuple(args, "O", &arg))
2369 return NULL;
2370 i = getindex(self, arg);
2371 if (i == -1 && PyErr_Occurred())
2372 return NULL;
2373 res = (*func)(self, i, NULL);
2374 if (res == -1 && PyErr_Occurred())
2375 return NULL;
2376 Py_INCREF(Py_None);
2377 return Py_None;
2380 static PyObject *
2381 wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2383 intintobjargproc func = (intintobjargproc)wrapped;
2384 int i, j, res;
2385 PyObject *value;
2387 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2388 return NULL;
2389 res = (*func)(self, i, j, value);
2390 if (res == -1 && PyErr_Occurred())
2391 return NULL;
2392 Py_INCREF(Py_None);
2393 return Py_None;
2396 static PyObject *
2397 wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2399 intintobjargproc func = (intintobjargproc)wrapped;
2400 int i, j, res;
2402 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2403 return NULL;
2404 res = (*func)(self, i, j, NULL);
2405 if (res == -1 && PyErr_Occurred())
2406 return NULL;
2407 Py_INCREF(Py_None);
2408 return Py_None;
2411 /* XXX objobjproc is a misnomer; should be objargpred */
2412 static PyObject *
2413 wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2415 objobjproc func = (objobjproc)wrapped;
2416 int res;
2417 PyObject *value;
2419 if (!PyArg_ParseTuple(args, "O", &value))
2420 return NULL;
2421 res = (*func)(self, value);
2422 if (res == -1 && PyErr_Occurred())
2423 return NULL;
2424 return PyInt_FromLong((long)res);
2427 static PyObject *
2428 wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2430 objobjargproc func = (objobjargproc)wrapped;
2431 int res;
2432 PyObject *key, *value;
2434 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2435 return NULL;
2436 res = (*func)(self, key, value);
2437 if (res == -1 && PyErr_Occurred())
2438 return NULL;
2439 Py_INCREF(Py_None);
2440 return Py_None;
2443 static PyObject *
2444 wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2446 objobjargproc func = (objobjargproc)wrapped;
2447 int res;
2448 PyObject *key;
2450 if (!PyArg_ParseTuple(args, "O", &key))
2451 return NULL;
2452 res = (*func)(self, key, NULL);
2453 if (res == -1 && PyErr_Occurred())
2454 return NULL;
2455 Py_INCREF(Py_None);
2456 return Py_None;
2459 static PyObject *
2460 wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2462 cmpfunc func = (cmpfunc)wrapped;
2463 int res;
2464 PyObject *other;
2466 if (!PyArg_ParseTuple(args, "O", &other))
2467 return NULL;
2468 if (other->ob_type->tp_compare != func &&
2469 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2470 PyErr_Format(
2471 PyExc_TypeError,
2472 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2473 self->ob_type->tp_name,
2474 self->ob_type->tp_name,
2475 other->ob_type->tp_name);
2476 return NULL;
2478 res = (*func)(self, other);
2479 if (PyErr_Occurred())
2480 return NULL;
2481 return PyInt_FromLong((long)res);
2484 static PyObject *
2485 wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2487 setattrofunc func = (setattrofunc)wrapped;
2488 int res;
2489 PyObject *name, *value;
2491 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2492 return NULL;
2493 res = (*func)(self, name, value);
2494 if (res < 0)
2495 return NULL;
2496 Py_INCREF(Py_None);
2497 return Py_None;
2500 static PyObject *
2501 wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2503 setattrofunc func = (setattrofunc)wrapped;
2504 int res;
2505 PyObject *name;
2507 if (!PyArg_ParseTuple(args, "O", &name))
2508 return NULL;
2509 res = (*func)(self, name, NULL);
2510 if (res < 0)
2511 return NULL;
2512 Py_INCREF(Py_None);
2513 return Py_None;
2516 static PyObject *
2517 wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2519 hashfunc func = (hashfunc)wrapped;
2520 long res;
2522 if (!PyArg_ParseTuple(args, ""))
2523 return NULL;
2524 res = (*func)(self);
2525 if (res == -1 && PyErr_Occurred())
2526 return NULL;
2527 return PyInt_FromLong(res);
2530 static PyObject *
2531 wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
2533 ternaryfunc func = (ternaryfunc)wrapped;
2535 return (*func)(self, args, kwds);
2538 static PyObject *
2539 wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2541 richcmpfunc func = (richcmpfunc)wrapped;
2542 PyObject *other;
2544 if (!PyArg_ParseTuple(args, "O", &other))
2545 return NULL;
2546 return (*func)(self, other, op);
2549 #undef RICHCMP_WRAPPER
2550 #define RICHCMP_WRAPPER(NAME, OP) \
2551 static PyObject * \
2552 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2554 return wrap_richcmpfunc(self, args, wrapped, OP); \
2557 RICHCMP_WRAPPER(lt, Py_LT)
2558 RICHCMP_WRAPPER(le, Py_LE)
2559 RICHCMP_WRAPPER(eq, Py_EQ)
2560 RICHCMP_WRAPPER(ne, Py_NE)
2561 RICHCMP_WRAPPER(gt, Py_GT)
2562 RICHCMP_WRAPPER(ge, Py_GE)
2564 static PyObject *
2565 wrap_next(PyObject *self, PyObject *args, void *wrapped)
2567 unaryfunc func = (unaryfunc)wrapped;
2568 PyObject *res;
2570 if (!PyArg_ParseTuple(args, ""))
2571 return NULL;
2572 res = (*func)(self);
2573 if (res == NULL && !PyErr_Occurred())
2574 PyErr_SetNone(PyExc_StopIteration);
2575 return res;
2578 static PyObject *
2579 wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2581 descrgetfunc func = (descrgetfunc)wrapped;
2582 PyObject *obj;
2583 PyObject *type = NULL;
2585 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2586 return NULL;
2587 return (*func)(self, obj, type);
2590 static PyObject *
2591 wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
2593 descrsetfunc func = (descrsetfunc)wrapped;
2594 PyObject *obj, *value;
2595 int ret;
2597 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2598 return NULL;
2599 ret = (*func)(self, obj, value);
2600 if (ret < 0)
2601 return NULL;
2602 Py_INCREF(Py_None);
2603 return Py_None;
2606 static PyObject *
2607 wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
2609 initproc func = (initproc)wrapped;
2611 if (func(self, args, kwds) < 0)
2612 return NULL;
2613 Py_INCREF(Py_None);
2614 return Py_None;
2617 static PyObject *
2618 tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
2620 PyTypeObject *type, *subtype, *staticbase;
2621 PyObject *arg0, *res;
2623 if (self == NULL || !PyType_Check(self))
2624 Py_FatalError("__new__() called with non-type 'self'");
2625 type = (PyTypeObject *)self;
2626 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
2627 PyErr_Format(PyExc_TypeError,
2628 "%s.__new__(): not enough arguments",
2629 type->tp_name);
2630 return NULL;
2632 arg0 = PyTuple_GET_ITEM(args, 0);
2633 if (!PyType_Check(arg0)) {
2634 PyErr_Format(PyExc_TypeError,
2635 "%s.__new__(X): X is not a type object (%s)",
2636 type->tp_name,
2637 arg0->ob_type->tp_name);
2638 return NULL;
2640 subtype = (PyTypeObject *)arg0;
2641 if (!PyType_IsSubtype(subtype, type)) {
2642 PyErr_Format(PyExc_TypeError,
2643 "%s.__new__(%s): %s is not a subtype of %s",
2644 type->tp_name,
2645 subtype->tp_name,
2646 subtype->tp_name,
2647 type->tp_name);
2648 return NULL;
2651 /* Check that the use doesn't do something silly and unsafe like
2652 object.__new__(dict). To do this, we check that the
2653 most derived base that's not a heap type is this type. */
2654 staticbase = subtype;
2655 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2656 staticbase = staticbase->tp_base;
2657 if (staticbase->tp_new != type->tp_new) {
2658 PyErr_Format(PyExc_TypeError,
2659 "%s.__new__(%s) is not safe, use %s.__new__()",
2660 type->tp_name,
2661 subtype->tp_name,
2662 staticbase == NULL ? "?" : staticbase->tp_name);
2663 return NULL;
2666 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2667 if (args == NULL)
2668 return NULL;
2669 res = type->tp_new(subtype, args, kwds);
2670 Py_DECREF(args);
2671 return res;
2674 static struct PyMethodDef tp_new_methoddef[] = {
2675 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2676 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
2680 static int
2681 add_tp_new_wrapper(PyTypeObject *type)
2683 PyObject *func;
2685 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
2686 return 0;
2687 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
2688 if (func == NULL)
2689 return -1;
2690 return PyDict_SetItemString(type->tp_dict, "__new__", func);
2693 /* Slot wrappers that call the corresponding __foo__ slot. See comments
2694 below at override_slots() for more explanation. */
2696 #define SLOT0(FUNCNAME, OPSTR) \
2697 static PyObject * \
2698 FUNCNAME(PyObject *self) \
2700 static PyObject *cache_str; \
2701 return call_method(self, OPSTR, &cache_str, "()"); \
2704 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
2705 static PyObject * \
2706 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
2708 static PyObject *cache_str; \
2709 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
2713 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
2714 static PyObject * \
2715 FUNCNAME(PyObject *self, PyObject *other) \
2717 static PyObject *cache_str, *rcache_str; \
2718 int do_other = self->ob_type != other->ob_type && \
2719 other->ob_type->tp_as_number != NULL && \
2720 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
2721 if (self->ob_type->tp_as_number != NULL && \
2722 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2723 PyObject *r; \
2724 if (do_other && \
2725 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2726 r = call_maybe( \
2727 other, ROPSTR, &rcache_str, "(O)", self); \
2728 if (r != Py_NotImplemented) \
2729 return r; \
2730 Py_DECREF(r); \
2731 do_other = 0; \
2733 r = call_maybe( \
2734 self, OPSTR, &cache_str, "(O)", other); \
2735 if (r != Py_NotImplemented || \
2736 other->ob_type == self->ob_type) \
2737 return r; \
2738 Py_DECREF(r); \
2740 if (do_other) { \
2741 return call_maybe( \
2742 other, ROPSTR, &rcache_str, "(O)", self); \
2744 Py_INCREF(Py_NotImplemented); \
2745 return Py_NotImplemented; \
2748 #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2749 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2751 #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2752 static PyObject * \
2753 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2755 static PyObject *cache_str; \
2756 return call_method(self, OPSTR, &cache_str, \
2757 "(" ARGCODES ")", arg1, arg2); \
2760 static int
2761 slot_sq_length(PyObject *self)
2763 static PyObject *len_str;
2764 PyObject *res = call_method(self, "__len__", &len_str, "()");
2765 int len;
2767 if (res == NULL)
2768 return -1;
2769 len = (int)PyInt_AsLong(res);
2770 Py_DECREF(res);
2771 return len;
2774 SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2775 SLOT1(slot_sq_repeat, "__mul__", int, "i")
2777 /* Super-optimized version of slot_sq_item.
2778 Other slots could do the same... */
2779 static PyObject *
2780 slot_sq_item(PyObject *self, int i)
2782 static PyObject *getitem_str;
2783 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2784 descrgetfunc f;
2786 if (getitem_str == NULL) {
2787 getitem_str = PyString_InternFromString("__getitem__");
2788 if (getitem_str == NULL)
2789 return NULL;
2791 func = _PyType_Lookup(self->ob_type, getitem_str);
2792 if (func != NULL) {
2793 if ((f = func->ob_type->tp_descr_get) == NULL)
2794 Py_INCREF(func);
2795 else
2796 func = f(func, self, (PyObject *)(self->ob_type));
2797 ival = PyInt_FromLong(i);
2798 if (ival != NULL) {
2799 args = PyTuple_New(1);
2800 if (args != NULL) {
2801 PyTuple_SET_ITEM(args, 0, ival);
2802 retval = PyObject_Call(func, args, NULL);
2803 Py_XDECREF(args);
2804 Py_XDECREF(func);
2805 return retval;
2809 else {
2810 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2812 Py_XDECREF(args);
2813 Py_XDECREF(ival);
2814 Py_XDECREF(func);
2815 return NULL;
2818 SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
2820 static int
2821 slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2823 PyObject *res;
2824 static PyObject *delitem_str, *setitem_str;
2826 if (value == NULL)
2827 res = call_method(self, "__delitem__", &delitem_str,
2828 "(i)", index);
2829 else
2830 res = call_method(self, "__setitem__", &setitem_str,
2831 "(iO)", index, value);
2832 if (res == NULL)
2833 return -1;
2834 Py_DECREF(res);
2835 return 0;
2838 static int
2839 slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2841 PyObject *res;
2842 static PyObject *delslice_str, *setslice_str;
2844 if (value == NULL)
2845 res = call_method(self, "__delslice__", &delslice_str,
2846 "(ii)", i, j);
2847 else
2848 res = call_method(self, "__setslice__", &setslice_str,
2849 "(iiO)", i, j, value);
2850 if (res == NULL)
2851 return -1;
2852 Py_DECREF(res);
2853 return 0;
2856 static int
2857 slot_sq_contains(PyObject *self, PyObject *value)
2859 PyObject *func, *res, *args;
2860 static PyObject *contains_str;
2862 func = lookup_maybe(self, "__contains__", &contains_str);
2864 if (func != NULL) {
2865 args = Py_BuildValue("(O)", value);
2866 if (args == NULL)
2867 res = NULL;
2868 else {
2869 res = PyObject_Call(func, args, NULL);
2870 Py_DECREF(args);
2872 Py_DECREF(func);
2873 if (res == NULL)
2874 return -1;
2875 return PyObject_IsTrue(res);
2877 else if (PyErr_Occurred())
2878 return -1;
2879 else {
2880 return _PySequence_IterSearch(self, value,
2881 PY_ITERSEARCH_CONTAINS);
2885 SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2886 SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
2888 #define slot_mp_length slot_sq_length
2890 SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
2892 static int
2893 slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2895 PyObject *res;
2896 static PyObject *delitem_str, *setitem_str;
2898 if (value == NULL)
2899 res = call_method(self, "__delitem__", &delitem_str,
2900 "(O)", key);
2901 else
2902 res = call_method(self, "__setitem__", &setitem_str,
2903 "(OO)", key, value);
2904 if (res == NULL)
2905 return -1;
2906 Py_DECREF(res);
2907 return 0;
2910 SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2911 SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2912 SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2913 SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2914 SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2915 SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2917 staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2919 SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2920 nb_power, "__pow__", "__rpow__")
2922 static PyObject *
2923 slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2925 static PyObject *pow_str;
2927 if (modulus == Py_None)
2928 return slot_nb_power_binary(self, other);
2929 /* Three-arg power doesn't use __rpow__ */
2930 return call_method(self, "__pow__", &pow_str,
2931 "(OO)", other, modulus);
2934 SLOT0(slot_nb_negative, "__neg__")
2935 SLOT0(slot_nb_positive, "__pos__")
2936 SLOT0(slot_nb_absolute, "__abs__")
2938 static int
2939 slot_nb_nonzero(PyObject *self)
2941 PyObject *func, *res;
2942 static PyObject *nonzero_str, *len_str;
2944 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
2945 if (func == NULL) {
2946 if (PyErr_Occurred())
2947 return -1;
2948 func = lookup_maybe(self, "__len__", &len_str);
2949 if (func == NULL) {
2950 if (PyErr_Occurred())
2951 return -1;
2952 else
2953 return 1;
2956 res = PyObject_CallObject(func, NULL);
2957 Py_DECREF(func);
2958 if (res == NULL)
2959 return -1;
2960 return PyObject_IsTrue(res);
2963 SLOT0(slot_nb_invert, "__invert__")
2964 SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2965 SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2966 SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2967 SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2968 SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
2970 static int
2971 slot_nb_coerce(PyObject **a, PyObject **b)
2973 static PyObject *coerce_str;
2974 PyObject *self = *a, *other = *b;
2976 if (self->ob_type->tp_as_number != NULL &&
2977 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2978 PyObject *r;
2979 r = call_maybe(
2980 self, "__coerce__", &coerce_str, "(O)", other);
2981 if (r == NULL)
2982 return -1;
2983 if (r == Py_NotImplemented) {
2984 Py_DECREF(r);
2986 else {
2987 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2988 PyErr_SetString(PyExc_TypeError,
2989 "__coerce__ didn't return a 2-tuple");
2990 Py_DECREF(r);
2991 return -1;
2993 *a = PyTuple_GET_ITEM(r, 0);
2994 Py_INCREF(*a);
2995 *b = PyTuple_GET_ITEM(r, 1);
2996 Py_INCREF(*b);
2997 Py_DECREF(r);
2998 return 0;
3001 if (other->ob_type->tp_as_number != NULL &&
3002 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3003 PyObject *r;
3004 r = call_maybe(
3005 other, "__coerce__", &coerce_str, "(O)", self);
3006 if (r == NULL)
3007 return -1;
3008 if (r == Py_NotImplemented) {
3009 Py_DECREF(r);
3010 return 1;
3012 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3013 PyErr_SetString(PyExc_TypeError,
3014 "__coerce__ didn't return a 2-tuple");
3015 Py_DECREF(r);
3016 return -1;
3018 *a = PyTuple_GET_ITEM(r, 1);
3019 Py_INCREF(*a);
3020 *b = PyTuple_GET_ITEM(r, 0);
3021 Py_INCREF(*b);
3022 Py_DECREF(r);
3023 return 0;
3025 return 1;
3028 SLOT0(slot_nb_int, "__int__")
3029 SLOT0(slot_nb_long, "__long__")
3030 SLOT0(slot_nb_float, "__float__")
3031 SLOT0(slot_nb_oct, "__oct__")
3032 SLOT0(slot_nb_hex, "__hex__")
3033 SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3034 SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3035 SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3036 SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3037 SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3038 SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3039 SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3040 SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3041 SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3042 SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3043 SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3044 SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3045 "__floordiv__", "__rfloordiv__")
3046 SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3047 SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3048 SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
3050 static int
3051 half_compare(PyObject *self, PyObject *other)
3053 PyObject *func, *args, *res;
3054 static PyObject *cmp_str;
3055 int c;
3057 func = lookup_method(self, "__cmp__", &cmp_str);
3058 if (func == NULL) {
3059 PyErr_Clear();
3061 else {
3062 args = Py_BuildValue("(O)", other);
3063 if (args == NULL)
3064 res = NULL;
3065 else {
3066 res = PyObject_Call(func, args, NULL);
3067 Py_DECREF(args);
3069 if (res != Py_NotImplemented) {
3070 if (res == NULL)
3071 return -2;
3072 c = PyInt_AsLong(res);
3073 Py_DECREF(res);
3074 if (c == -1 && PyErr_Occurred())
3075 return -2;
3076 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3078 Py_DECREF(res);
3080 return 2;
3083 /* This slot is published for the benefit of try_3way_compare in object.c */
3085 _PyObject_SlotCompare(PyObject *self, PyObject *other)
3087 int c;
3089 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
3090 c = half_compare(self, other);
3091 if (c <= 1)
3092 return c;
3094 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
3095 c = half_compare(other, self);
3096 if (c < -1)
3097 return -2;
3098 if (c <= 1)
3099 return -c;
3101 return (void *)self < (void *)other ? -1 :
3102 (void *)self > (void *)other ? 1 : 0;
3105 static PyObject *
3106 slot_tp_repr(PyObject *self)
3108 PyObject *func, *res;
3109 static PyObject *repr_str;
3111 func = lookup_method(self, "__repr__", &repr_str);
3112 if (func != NULL) {
3113 res = PyEval_CallObject(func, NULL);
3114 Py_DECREF(func);
3115 return res;
3117 PyErr_Clear();
3118 return PyString_FromFormat("<%s object at %p>",
3119 self->ob_type->tp_name, self);
3122 static PyObject *
3123 slot_tp_str(PyObject *self)
3125 PyObject *func, *res;
3126 static PyObject *str_str;
3128 func = lookup_method(self, "__str__", &str_str);
3129 if (func != NULL) {
3130 res = PyEval_CallObject(func, NULL);
3131 Py_DECREF(func);
3132 return res;
3134 else {
3135 PyErr_Clear();
3136 return slot_tp_repr(self);
3140 static long
3141 slot_tp_hash(PyObject *self)
3143 PyObject *func, *res;
3144 static PyObject *hash_str, *eq_str, *cmp_str;
3146 long h;
3148 func = lookup_method(self, "__hash__", &hash_str);
3150 if (func != NULL) {
3151 res = PyEval_CallObject(func, NULL);
3152 Py_DECREF(func);
3153 if (res == NULL)
3154 return -1;
3155 h = PyInt_AsLong(res);
3157 else {
3158 PyErr_Clear();
3159 func = lookup_method(self, "__eq__", &eq_str);
3160 if (func == NULL) {
3161 PyErr_Clear();
3162 func = lookup_method(self, "__cmp__", &cmp_str);
3164 if (func != NULL) {
3165 Py_DECREF(func);
3166 PyErr_SetString(PyExc_TypeError, "unhashable type");
3167 return -1;
3169 PyErr_Clear();
3170 h = _Py_HashPointer((void *)self);
3172 if (h == -1 && !PyErr_Occurred())
3173 h = -2;
3174 return h;
3177 static PyObject *
3178 slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3180 static PyObject *call_str;
3181 PyObject *meth = lookup_method(self, "__call__", &call_str);
3182 PyObject *res;
3184 if (meth == NULL)
3185 return NULL;
3186 res = PyObject_Call(meth, args, kwds);
3187 Py_DECREF(meth);
3188 return res;
3191 /* There are two slot dispatch functions for tp_getattro.
3193 - slot_tp_getattro() is used when __getattribute__ is overridden
3194 but no __getattr__ hook is present;
3196 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3198 The code in update_slot() and fixup_slot_dispatchers() always installs
3199 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3200 installs the simpler slot if necessary. */
3202 static PyObject *
3203 slot_tp_getattro(PyObject *self, PyObject *name)
3205 static PyObject *getattribute_str = NULL;
3206 return call_method(self, "__getattribute__", &getattribute_str,
3207 "(O)", name);
3210 static PyObject *
3211 slot_tp_getattr_hook(PyObject *self, PyObject *name)
3213 PyTypeObject *tp = self->ob_type;
3214 PyObject *getattr, *getattribute, *res;
3215 static PyObject *getattribute_str = NULL;
3216 static PyObject *getattr_str = NULL;
3218 if (getattr_str == NULL) {
3219 getattr_str = PyString_InternFromString("__getattr__");
3220 if (getattr_str == NULL)
3221 return NULL;
3223 if (getattribute_str == NULL) {
3224 getattribute_str =
3225 PyString_InternFromString("__getattribute__");
3226 if (getattribute_str == NULL)
3227 return NULL;
3229 getattr = _PyType_Lookup(tp, getattr_str);
3230 if (getattr == NULL) {
3231 /* No __getattr__ hook: use a simpler dispatcher */
3232 tp->tp_getattro = slot_tp_getattro;
3233 return slot_tp_getattro(self, name);
3235 getattribute = _PyType_Lookup(tp, getattribute_str);
3236 if (getattribute == NULL ||
3237 (getattribute->ob_type == &PyWrapperDescr_Type &&
3238 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3239 (void *)PyObject_GenericGetAttr))
3240 res = PyObject_GenericGetAttr(self, name);
3241 else
3242 res = PyObject_CallFunction(getattribute, "OO", self, name);
3243 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
3244 PyErr_Clear();
3245 res = PyObject_CallFunction(getattr, "OO", self, name);
3247 return res;
3250 static int
3251 slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3253 PyObject *res;
3254 static PyObject *delattr_str, *setattr_str;
3256 if (value == NULL)
3257 res = call_method(self, "__delattr__", &delattr_str,
3258 "(O)", name);
3259 else
3260 res = call_method(self, "__setattr__", &setattr_str,
3261 "(OO)", name, value);
3262 if (res == NULL)
3263 return -1;
3264 Py_DECREF(res);
3265 return 0;
3268 /* Map rich comparison operators to their __xx__ namesakes */
3269 static char *name_op[] = {
3270 "__lt__",
3271 "__le__",
3272 "__eq__",
3273 "__ne__",
3274 "__gt__",
3275 "__ge__",
3278 static PyObject *
3279 half_richcompare(PyObject *self, PyObject *other, int op)
3281 PyObject *func, *args, *res;
3282 static PyObject *op_str[6];
3284 func = lookup_method(self, name_op[op], &op_str[op]);
3285 if (func == NULL) {
3286 PyErr_Clear();
3287 Py_INCREF(Py_NotImplemented);
3288 return Py_NotImplemented;
3290 args = Py_BuildValue("(O)", other);
3291 if (args == NULL)
3292 res = NULL;
3293 else {
3294 res = PyObject_Call(func, args, NULL);
3295 Py_DECREF(args);
3297 Py_DECREF(func);
3298 return res;
3301 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3302 static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3304 static PyObject *
3305 slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3307 PyObject *res;
3309 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3310 res = half_richcompare(self, other, op);
3311 if (res != Py_NotImplemented)
3312 return res;
3313 Py_DECREF(res);
3315 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3316 res = half_richcompare(other, self, swapped_op[op]);
3317 if (res != Py_NotImplemented) {
3318 return res;
3320 Py_DECREF(res);
3322 Py_INCREF(Py_NotImplemented);
3323 return Py_NotImplemented;
3326 static PyObject *
3327 slot_tp_iter(PyObject *self)
3329 PyObject *func, *res;
3330 static PyObject *iter_str, *getitem_str;
3332 func = lookup_method(self, "__iter__", &iter_str);
3333 if (func != NULL) {
3334 res = PyObject_CallObject(func, NULL);
3335 Py_DECREF(func);
3336 return res;
3338 PyErr_Clear();
3339 func = lookup_method(self, "__getitem__", &getitem_str);
3340 if (func == NULL) {
3341 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
3342 return NULL;
3344 Py_DECREF(func);
3345 return PySeqIter_New(self);
3348 static PyObject *
3349 slot_tp_iternext(PyObject *self)
3351 static PyObject *next_str;
3352 return call_method(self, "next", &next_str, "()");
3355 static PyObject *
3356 slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3358 PyTypeObject *tp = self->ob_type;
3359 PyObject *get;
3360 static PyObject *get_str = NULL;
3362 if (get_str == NULL) {
3363 get_str = PyString_InternFromString("__get__");
3364 if (get_str == NULL)
3365 return NULL;
3367 get = _PyType_Lookup(tp, get_str);
3368 if (get == NULL) {
3369 /* Avoid further slowdowns */
3370 if (tp->tp_descr_get == slot_tp_descr_get)
3371 tp->tp_descr_get = NULL;
3372 Py_INCREF(self);
3373 return self;
3375 if (obj == NULL)
3376 obj = Py_None;
3377 if (type == NULL)
3378 type = Py_None;
3379 return PyObject_CallFunction(get, "OOO", self, obj, type);
3382 static int
3383 slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3385 PyObject *res;
3386 static PyObject *del_str, *set_str;
3388 if (value == NULL)
3389 res = call_method(self, "__delete__", &del_str,
3390 "(O)", target);
3391 else
3392 res = call_method(self, "__set__", &set_str,
3393 "(OO)", target, value);
3394 if (res == NULL)
3395 return -1;
3396 Py_DECREF(res);
3397 return 0;
3400 static int
3401 slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3403 static PyObject *init_str;
3404 PyObject *meth = lookup_method(self, "__init__", &init_str);
3405 PyObject *res;
3407 if (meth == NULL)
3408 return -1;
3409 res = PyObject_Call(meth, args, kwds);
3410 Py_DECREF(meth);
3411 if (res == NULL)
3412 return -1;
3413 Py_DECREF(res);
3414 return 0;
3417 static PyObject *
3418 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3420 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3421 PyObject *newargs, *x;
3422 int i, n;
3424 if (func == NULL)
3425 return NULL;
3426 assert(PyTuple_Check(args));
3427 n = PyTuple_GET_SIZE(args);
3428 newargs = PyTuple_New(n+1);
3429 if (newargs == NULL)
3430 return NULL;
3431 Py_INCREF(type);
3432 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3433 for (i = 0; i < n; i++) {
3434 x = PyTuple_GET_ITEM(args, i);
3435 Py_INCREF(x);
3436 PyTuple_SET_ITEM(newargs, i+1, x);
3438 x = PyObject_Call(func, newargs, kwds);
3439 Py_DECREF(newargs);
3440 Py_DECREF(func);
3441 return x;
3445 /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3446 functions. The offsets here are relative to the 'etype' structure, which
3447 incorporates the additional structures used for numbers, sequences and
3448 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3449 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3450 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3452 typedef struct wrapperbase slotdef;
3454 #undef TPSLOT
3455 #undef FLSLOT
3456 #undef ETSLOT
3457 #undef SQSLOT
3458 #undef MPSLOT
3459 #undef NBSLOT
3460 #undef UNSLOT
3461 #undef IBSLOT
3462 #undef BINSLOT
3463 #undef RBINSLOT
3465 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3466 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3467 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3468 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3469 DOC, FLAGS}
3470 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3471 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3472 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3473 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3474 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3475 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3476 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3477 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3478 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3479 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3480 "x." NAME "() <==> " DOC)
3481 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3482 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3483 "x." NAME "(y) <==> x" DOC "y")
3484 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3485 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3486 "x." NAME "(y) <==> x" DOC "y")
3487 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3488 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3489 "x." NAME "(y) <==> y" DOC "x")
3491 static slotdef slotdefs[] = {
3492 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3493 "x.__len__() <==> len(x)"),
3494 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3495 "x.__add__(y) <==> x+y"),
3496 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3497 "x.__mul__(n) <==> x*n"),
3498 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3499 "x.__rmul__(n) <==> n*x"),
3500 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3501 "x.__getitem__(y) <==> x[y]"),
3502 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3503 "x.__getslice__(i, j) <==> x[i:j]"),
3504 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3505 "x.__setitem__(i, y) <==> x[i]=y"),
3506 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3507 "x.__delitem__(y) <==> del x[y]"),
3508 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3509 wrap_intintobjargproc,
3510 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3511 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3512 "x.__delslice__(i, j) <==> del x[i:j]"),
3513 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3514 "x.__contains__(y) <==> y in x"),
3515 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3516 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
3517 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3518 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
3520 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3521 "x.__len__() <==> len(x)"),
3522 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3523 wrap_binaryfunc,
3524 "x.__getitem__(y) <==> x[y]"),
3525 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3526 wrap_objobjargproc,
3527 "x.__setitem__(i, y) <==> x[i]=y"),
3528 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3529 wrap_delitem,
3530 "x.__delitem__(y) <==> del x[y]"),
3532 BINSLOT("__add__", nb_add, slot_nb_add,
3533 "+"),
3534 RBINSLOT("__radd__", nb_add, slot_nb_add,
3535 "+"),
3536 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3537 "-"),
3538 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3539 "-"),
3540 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3541 "*"),
3542 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3543 "*"),
3544 BINSLOT("__div__", nb_divide, slot_nb_divide,
3545 "/"),
3546 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3547 "/"),
3548 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3549 "%"),
3550 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3551 "%"),
3552 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3553 "divmod(x, y)"),
3554 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3555 "divmod(y, x)"),
3556 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3557 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3558 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3559 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3560 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3561 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3562 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3563 "abs(x)"),
3564 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
3565 "x != 0"),
3566 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3567 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3568 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3569 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3570 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3571 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3572 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3573 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3574 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3575 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3576 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3577 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3578 "x.__coerce__(y) <==> coerce(x, y)"),
3579 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3580 "int(x)"),
3581 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3582 "long(x)"),
3583 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3584 "float(x)"),
3585 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3586 "oct(x)"),
3587 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3588 "hex(x)"),
3589 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3590 wrap_binaryfunc, "+"),
3591 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3592 wrap_binaryfunc, "-"),
3593 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3594 wrap_binaryfunc, "*"),
3595 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3596 wrap_binaryfunc, "/"),
3597 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3598 wrap_binaryfunc, "%"),
3599 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3600 wrap_ternaryfunc, "**"),
3601 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3602 wrap_binaryfunc, "<<"),
3603 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3604 wrap_binaryfunc, ">>"),
3605 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3606 wrap_binaryfunc, "&"),
3607 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3608 wrap_binaryfunc, "^"),
3609 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3610 wrap_binaryfunc, "|"),
3611 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3612 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3613 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3614 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3615 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3616 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3617 IBSLOT("__itruediv__", nb_inplace_true_divide,
3618 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
3620 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3621 "x.__str__() <==> str(x)"),
3622 TPSLOT("__str__", tp_print, NULL, NULL, ""),
3623 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3624 "x.__repr__() <==> repr(x)"),
3625 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
3626 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3627 "x.__cmp__(y) <==> cmp(x,y)"),
3628 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3629 "x.__hash__() <==> hash(x)"),
3630 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3631 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
3632 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
3633 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3634 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3635 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3636 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3637 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3638 "x.__setattr__('name', value) <==> x.name = value"),
3639 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3640 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3641 "x.__delattr__('name') <==> del x.name"),
3642 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3643 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3644 "x.__lt__(y) <==> x<y"),
3645 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3646 "x.__le__(y) <==> x<=y"),
3647 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3648 "x.__eq__(y) <==> x==y"),
3649 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3650 "x.__ne__(y) <==> x!=y"),
3651 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3652 "x.__gt__(y) <==> x>y"),
3653 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3654 "x.__ge__(y) <==> x>=y"),
3655 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3656 "x.__iter__() <==> iter(x)"),
3657 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3658 "x.next() -> the next value, or raise StopIteration"),
3659 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3660 "descr.__get__(obj[, type]) -> value"),
3661 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3662 "descr.__set__(obj, value)"),
3663 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
3664 "x.__init__(...) initializes x; "
3665 "see x.__class__.__doc__ for signature",
3666 PyWrapperFlag_KEYWORDS),
3667 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
3668 {NULL}
3671 static void **
3672 slotptr(PyTypeObject *type, int offset)
3674 char *ptr;
3676 assert(offset >= 0);
3677 assert(offset < offsetof(etype, as_buffer));
3678 if (offset >= offsetof(etype, as_mapping)) {
3679 ptr = (void *)type->tp_as_mapping;
3680 offset -= offsetof(etype, as_mapping);
3682 else if (offset >= offsetof(etype, as_sequence)) {
3683 ptr = (void *)type->tp_as_sequence;
3684 offset -= offsetof(etype, as_sequence);
3686 else if (offset >= offsetof(etype, as_number)) {
3687 ptr = (void *)type->tp_as_number;
3688 offset -= offsetof(etype, as_number);
3690 else {
3691 ptr = (void *)type;
3693 if (ptr != NULL)
3694 ptr += offset;
3695 return (void **)ptr;
3698 staticforward int recurse_down_subclasses(PyTypeObject *type,
3699 slotdef **pp, PyObject *name);
3701 static int
3702 update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
3704 slotdef **pp;
3706 for (pp = pp0; *pp; pp++) {
3707 slotdef *p = *pp;
3708 PyObject *descr;
3709 PyWrapperDescrObject *d;
3710 void *generic = NULL, *specific = NULL;
3711 int use_generic = 0;
3712 int offset = p->offset;
3713 void **ptr = slotptr(type, offset);
3714 if (ptr == NULL)
3715 continue;
3716 do {
3717 descr = _PyType_Lookup(type, p->name_strobj);
3718 if (descr == NULL)
3719 continue;
3720 generic = p->function;
3721 if (descr->ob_type == &PyWrapperDescr_Type) {
3722 d = (PyWrapperDescrObject *)descr;
3723 if (d->d_base->wrapper == p->wrapper &&
3724 PyType_IsSubtype(type, d->d_type)) {
3725 if (specific == NULL ||
3726 specific == d->d_wrapped)
3727 specific = d->d_wrapped;
3728 else
3729 use_generic = 1;
3732 else
3733 use_generic = 1;
3734 } while ((++p)->offset == offset);
3735 if (specific && !use_generic)
3736 *ptr = specific;
3737 else
3738 *ptr = generic;
3740 return recurse_down_subclasses(type, pp0, name);
3743 static int
3744 recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
3746 PyTypeObject *subclass;
3747 PyObject *ref, *subclasses, *dict;
3748 int i, n;
3750 subclasses = type->tp_subclasses;
3751 if (subclasses == NULL)
3752 return 0;
3753 assert(PyList_Check(subclasses));
3754 n = PyList_GET_SIZE(subclasses);
3755 for (i = 0; i < n; i++) {
3756 ref = PyList_GET_ITEM(subclasses, i);
3757 assert(PyWeakref_CheckRef(ref));
3758 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3759 if (subclass == NULL)
3760 continue;
3761 assert(PyType_Check(subclass));
3762 /* Avoid recursing down into unaffected classes */
3763 dict = subclass->tp_dict;
3764 if (dict != NULL && PyDict_Check(dict) &&
3765 PyDict_GetItem(dict, name) != NULL)
3766 continue;
3767 if (update_these_slots(subclass, pp, name) < 0)
3768 return -1;
3770 return 0;
3773 static int
3774 slotdef_cmp(const void *aa, const void *bb)
3776 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3777 int c = a->offset - b->offset;
3778 if (c != 0)
3779 return c;
3780 else
3781 return a - b;
3784 static void
3785 init_slotdefs(void)
3787 slotdef *p;
3788 static int initialized = 0;
3790 if (initialized)
3791 return;
3792 for (p = slotdefs; p->name; p++) {
3793 p->name_strobj = PyString_InternFromString(p->name);
3794 if (!p->name_strobj)
3795 Py_FatalError("XXX ouch");
3797 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3798 slotdef_cmp);
3799 initialized = 1;
3802 static int
3803 update_slot(PyTypeObject *type, PyObject *name)
3805 slotdef *ptrs[10];
3806 slotdef *p;
3807 slotdef **pp;
3808 int offset;
3810 init_slotdefs();
3811 pp = ptrs;
3812 for (p = slotdefs; p->name; p++) {
3813 /* XXX assume name is interned! */
3814 if (p->name_strobj == name)
3815 *pp++ = p;
3817 *pp = NULL;
3818 for (pp = ptrs; *pp; pp++) {
3819 p = *pp;
3820 offset = p->offset;
3821 while (p > slotdefs && (p-1)->offset == offset)
3822 --p;
3823 *pp = p;
3825 return update_these_slots(type, ptrs, name);
3828 static void
3829 fixup_slot_dispatchers(PyTypeObject *type)
3831 slotdef *p;
3832 PyObject *mro, *descr;
3833 PyWrapperDescrObject *d;
3834 int i, n, offset;
3835 void **ptr;
3836 void *generic, *specific;
3837 int use_generic;
3839 init_slotdefs();
3840 mro = type->tp_mro;
3841 assert(PyTuple_Check(mro));
3842 n = PyTuple_GET_SIZE(mro);
3843 for (p = slotdefs; p->name; ) {
3844 offset = p->offset;
3845 ptr = slotptr(type, offset);
3846 if (!ptr) {
3847 do {
3848 ++p;
3849 } while (p->offset == offset);
3850 continue;
3852 generic = specific = NULL;
3853 use_generic = 0;
3854 do {
3855 descr = NULL;
3856 for (i = 0; i < n; i++) {
3857 PyObject *b = PyTuple_GET_ITEM(mro, i);
3858 PyObject *dict = NULL;
3859 if (PyType_Check(b))
3860 dict = ((PyTypeObject *)b)->tp_dict;
3861 else if (PyClass_Check(b))
3862 dict = ((PyClassObject *)b)->cl_dict;
3863 if (dict != NULL) {
3864 descr = PyDict_GetItem(
3865 dict, p->name_strobj);
3866 if (descr != NULL)
3867 break;
3870 if (descr == NULL)
3871 continue;
3872 generic = p->function;
3873 if (descr->ob_type == &PyWrapperDescr_Type) {
3874 d = (PyWrapperDescrObject *)descr;
3875 if (d->d_base->wrapper == p->wrapper &&
3876 PyType_IsSubtype(type, d->d_type))
3878 if (specific == NULL ||
3879 specific == d->d_wrapped)
3880 specific = d->d_wrapped;
3881 else
3882 use_generic = 1;
3885 else
3886 use_generic = 1;
3887 } while ((++p)->offset == offset);
3888 if (specific && !use_generic)
3889 *ptr = specific;
3890 else
3891 *ptr = generic;
3895 /* This function is called by PyType_Ready() to populate the type's
3896 dictionary with method descriptors for function slots. For each
3897 function slot (like tp_repr) that's defined in the type, one or
3898 more corresponding descriptors are added in the type's tp_dict
3899 dictionary under the appropriate name (like __repr__). Some
3900 function slots cause more than one descriptor to be added (for
3901 example, the nb_add slot adds both __add__ and __radd__
3902 descriptors) and some function slots compete for the same
3903 descriptor (for example both sq_item and mp_subscript generate a
3904 __getitem__ descriptor). This only adds new descriptors and
3905 doesn't overwrite entries in tp_dict that were previously
3906 defined. The descriptors contain a reference to the C function
3907 they must call, so that it's safe if they are copied into a
3908 subtype's __dict__ and the subtype has a different C function in
3909 its slot -- calling the method defined by the descriptor will call
3910 the C function that was used to create it, rather than the C
3911 function present in the slot when it is called. (This is important
3912 because a subtype may have a C function in the slot that calls the
3913 method from the dictionary, and we want to avoid infinite recursion
3914 here.) */
3916 static int
3917 add_operators(PyTypeObject *type)
3919 PyObject *dict = type->tp_dict;
3920 slotdef *p;
3921 PyObject *descr;
3922 void **ptr;
3924 init_slotdefs();
3925 for (p = slotdefs; p->name; p++) {
3926 if (p->wrapper == NULL)
3927 continue;
3928 ptr = slotptr(type, p->offset);
3929 if (!ptr || !*ptr)
3930 continue;
3931 if (PyDict_GetItem(dict, p->name_strobj))
3932 continue;
3933 descr = PyDescr_NewWrapper(type, p, *ptr);
3934 if (descr == NULL)
3935 return -1;
3936 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
3937 return -1;
3938 Py_DECREF(descr);
3940 if (type->tp_new != NULL) {
3941 if (add_tp_new_wrapper(type) < 0)
3942 return -1;
3944 return 0;
3948 /* Cooperative 'super' */
3950 typedef struct {
3951 PyObject_HEAD
3952 PyTypeObject *type;
3953 PyObject *obj;
3954 } superobject;
3956 static PyMemberDef super_members[] = {
3957 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3958 "the class invoking super()"},
3959 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3960 "the instance invoking super(); may be None"},
3964 static void
3965 super_dealloc(PyObject *self)
3967 superobject *su = (superobject *)self;
3969 _PyObject_GC_UNTRACK(self);
3970 Py_XDECREF(su->obj);
3971 Py_XDECREF(su->type);
3972 self->ob_type->tp_free(self);
3975 static PyObject *
3976 super_repr(PyObject *self)
3978 superobject *su = (superobject *)self;
3980 if (su->obj)
3981 return PyString_FromFormat(
3982 "<super: <class '%s'>, <%s object>>",
3983 su->type ? su->type->tp_name : "NULL",
3984 su->obj->ob_type->tp_name);
3985 else
3986 return PyString_FromFormat(
3987 "<super: <class '%s'>, NULL>",
3988 su->type ? su->type->tp_name : "NULL");
3991 static PyObject *
3992 super_getattro(PyObject *self, PyObject *name)
3994 superobject *su = (superobject *)self;
3996 if (su->obj != NULL) {
3997 PyObject *mro, *res, *tmp, *dict;
3998 PyTypeObject *starttype;
3999 descrgetfunc f;
4000 int i, n;
4002 starttype = su->obj->ob_type;
4003 mro = starttype->tp_mro;
4005 if (mro == NULL)
4006 n = 0;
4007 else {
4008 assert(PyTuple_Check(mro));
4009 n = PyTuple_GET_SIZE(mro);
4011 for (i = 0; i < n; i++) {
4012 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
4013 break;
4015 if (i >= n && PyType_Check(su->obj)) {
4016 starttype = (PyTypeObject *)(su->obj);
4017 mro = starttype->tp_mro;
4018 if (mro == NULL)
4019 n = 0;
4020 else {
4021 assert(PyTuple_Check(mro));
4022 n = PyTuple_GET_SIZE(mro);
4024 for (i = 0; i < n; i++) {
4025 if ((PyObject *)(su->type) ==
4026 PyTuple_GET_ITEM(mro, i))
4027 break;
4030 i++;
4031 res = NULL;
4032 for (; i < n; i++) {
4033 tmp = PyTuple_GET_ITEM(mro, i);
4034 if (PyType_Check(tmp))
4035 dict = ((PyTypeObject *)tmp)->tp_dict;
4036 else if (PyClass_Check(tmp))
4037 dict = ((PyClassObject *)tmp)->cl_dict;
4038 else
4039 continue;
4040 res = PyDict_GetItem(dict, name);
4041 if (res != NULL && !PyDescr_IsData(res)) {
4042 Py_INCREF(res);
4043 f = res->ob_type->tp_descr_get;
4044 if (f != NULL) {
4045 tmp = f(res, su->obj, (PyObject *)starttype);
4046 Py_DECREF(res);
4047 res = tmp;
4049 return res;
4053 return PyObject_GenericGetAttr(self, name);
4056 static int
4057 supercheck(PyTypeObject *type, PyObject *obj)
4059 if (!PyType_IsSubtype(obj->ob_type, type) &&
4060 !(PyType_Check(obj) &&
4061 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4062 PyErr_SetString(PyExc_TypeError,
4063 "super(type, obj): "
4064 "obj must be an instance or subtype of type");
4065 return -1;
4067 else
4068 return 0;
4071 static PyObject *
4072 super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4074 superobject *su = (superobject *)self;
4075 superobject *new;
4077 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4078 /* Not binding to an object, or already bound */
4079 Py_INCREF(self);
4080 return self;
4082 if (su->ob_type != &PySuper_Type)
4083 /* If su is an instance of a subclass of super,
4084 call its type */
4085 return PyObject_CallFunction((PyObject *)su->ob_type,
4086 "OO", su->type, obj);
4087 else {
4088 /* Inline the common case */
4089 if (supercheck(su->type, obj) < 0)
4090 return NULL;
4091 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4092 NULL, NULL);
4093 if (new == NULL)
4094 return NULL;
4095 Py_INCREF(su->type);
4096 Py_INCREF(obj);
4097 new->type = su->type;
4098 new->obj = obj;
4099 return (PyObject *)new;
4103 static int
4104 super_init(PyObject *self, PyObject *args, PyObject *kwds)
4106 superobject *su = (superobject *)self;
4107 PyTypeObject *type;
4108 PyObject *obj = NULL;
4110 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4111 return -1;
4112 if (obj == Py_None)
4113 obj = NULL;
4114 if (obj != NULL && supercheck(type, obj) < 0)
4115 return -1;
4116 Py_INCREF(type);
4117 Py_XINCREF(obj);
4118 su->type = type;
4119 su->obj = obj;
4120 return 0;
4123 static char super_doc[] =
4124 "super(type) -> unbound super object\n"
4125 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
4126 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
4127 "Typical use to call a cooperative superclass method:\n"
4128 "class C(B):\n"
4129 " def meth(self, arg):\n"
4130 " super(C, self).meth(arg)";
4132 static int
4133 super_traverse(PyObject *self, visitproc visit, void *arg)
4135 superobject *su = (superobject *)self;
4136 int err;
4138 #define VISIT(SLOT) \
4139 if (SLOT) { \
4140 err = visit((PyObject *)(SLOT), arg); \
4141 if (err) \
4142 return err; \
4145 VISIT(su->obj);
4146 VISIT(su->type);
4148 #undef VISIT
4150 return 0;
4153 PyTypeObject PySuper_Type = {
4154 PyObject_HEAD_INIT(&PyType_Type)
4155 0, /* ob_size */
4156 "super", /* tp_name */
4157 sizeof(superobject), /* tp_basicsize */
4158 0, /* tp_itemsize */
4159 /* methods */
4160 super_dealloc, /* tp_dealloc */
4161 0, /* tp_print */
4162 0, /* tp_getattr */
4163 0, /* tp_setattr */
4164 0, /* tp_compare */
4165 super_repr, /* tp_repr */
4166 0, /* tp_as_number */
4167 0, /* tp_as_sequence */
4168 0, /* tp_as_mapping */
4169 0, /* tp_hash */
4170 0, /* tp_call */
4171 0, /* tp_str */
4172 super_getattro, /* tp_getattro */
4173 0, /* tp_setattro */
4174 0, /* tp_as_buffer */
4175 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4176 Py_TPFLAGS_BASETYPE, /* tp_flags */
4177 super_doc, /* tp_doc */
4178 super_traverse, /* tp_traverse */
4179 0, /* tp_clear */
4180 0, /* tp_richcompare */
4181 0, /* tp_weaklistoffset */
4182 0, /* tp_iter */
4183 0, /* tp_iternext */
4184 0, /* tp_methods */
4185 super_members, /* tp_members */
4186 0, /* tp_getset */
4187 0, /* tp_base */
4188 0, /* tp_dict */
4189 super_descr_get, /* tp_descr_get */
4190 0, /* tp_descr_set */
4191 0, /* tp_dictoffset */
4192 super_init, /* tp_init */
4193 PyType_GenericAlloc, /* tp_alloc */
4194 PyType_GenericNew, /* tp_new */
4195 _PyObject_GC_Del, /* tp_free */