Issue #7701: Fix crash in binascii.b2a_uu() in debug mode when given a
[python.git] / Objects / typeobject.c
blob28df7f29d156164985ad1b0a679e92357b74fbe8
1 /* Type object implementation */
3 #include "Python.h"
4 #include "structmember.h"
6 #include <ctype.h>
9 /* Support type attribute cache */
11 /* The cache can keep references to the names alive for longer than
12 they normally would. This is why the maximum size is limited to
13 MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
14 strings are used as attribute names. */
15 #define MCACHE_MAX_ATTR_SIZE 100
16 #define MCACHE_SIZE_EXP 10
17 #define MCACHE_HASH(version, name_hash) \
18 (((unsigned int)(version) * (unsigned int)(name_hash)) \
19 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
20 #define MCACHE_HASH_METHOD(type, name) \
21 MCACHE_HASH((type)->tp_version_tag, \
22 ((PyStringObject *)(name))->ob_shash)
23 #define MCACHE_CACHEABLE_NAME(name) \
24 PyString_CheckExact(name) && \
25 PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
27 struct method_cache_entry {
28 unsigned int version;
29 PyObject *name; /* reference to exactly a str or None */
30 PyObject *value; /* borrowed */
33 static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
34 static unsigned int next_version_tag = 0;
36 unsigned int
37 PyType_ClearCache(void)
39 Py_ssize_t i;
40 unsigned int cur_version_tag = next_version_tag - 1;
42 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
43 method_cache[i].version = 0;
44 Py_CLEAR(method_cache[i].name);
45 method_cache[i].value = NULL;
47 next_version_tag = 0;
48 /* mark all version tags as invalid */
49 PyType_Modified(&PyBaseObject_Type);
50 return cur_version_tag;
53 void
54 PyType_Modified(PyTypeObject *type)
56 /* Invalidate any cached data for the specified type and all
57 subclasses. This function is called after the base
58 classes, mro, or attributes of the type are altered.
60 Invariants:
62 - Py_TPFLAGS_VALID_VERSION_TAG is never set if
63 Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
64 objects coming from non-recompiled extension modules)
66 - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
67 it must first be set on all super types.
69 This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
70 type (so it must first clear it on all subclasses). The
71 tp_version_tag value is meaningless unless this flag is set.
72 We don't assign new version tags eagerly, but only as
73 needed.
75 PyObject *raw, *ref;
76 Py_ssize_t i, n;
78 if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
79 return;
81 raw = type->tp_subclasses;
82 if (raw != NULL) {
83 n = PyList_GET_SIZE(raw);
84 for (i = 0; i < n; i++) {
85 ref = PyList_GET_ITEM(raw, i);
86 ref = PyWeakref_GET_OBJECT(ref);
87 if (ref != Py_None) {
88 PyType_Modified((PyTypeObject *)ref);
92 type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
95 static void
96 type_mro_modified(PyTypeObject *type, PyObject *bases) {
98 Check that all base classes or elements of the mro of type are
99 able to be cached. This function is called after the base
100 classes or mro of the type are altered.
102 Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
103 inherits from an old-style class, either directly or if it
104 appears in the MRO of a new-style class. No support either for
105 custom MROs that include types that are not officially super
106 types.
108 Called from mro_internal, which will subsequently be called on
109 each subclass when their mro is recursively updated.
111 Py_ssize_t i, n;
112 int clear = 0;
114 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
115 return;
117 n = PyTuple_GET_SIZE(bases);
118 for (i = 0; i < n; i++) {
119 PyObject *b = PyTuple_GET_ITEM(bases, i);
120 PyTypeObject *cls;
122 if (!PyType_Check(b) ) {
123 clear = 1;
124 break;
127 cls = (PyTypeObject *)b;
129 if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
130 !PyType_IsSubtype(type, cls)) {
131 clear = 1;
132 break;
136 if (clear)
137 type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
138 Py_TPFLAGS_VALID_VERSION_TAG);
141 static int
142 assign_version_tag(PyTypeObject *type)
144 /* Ensure that the tp_version_tag is valid and set
145 Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
146 must first be done on all super classes. Return 0 if this
147 cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
149 Py_ssize_t i, n;
150 PyObject *bases;
152 if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
153 return 1;
154 if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
155 return 0;
156 if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
157 return 0;
159 type->tp_version_tag = next_version_tag++;
160 /* for stress-testing: next_version_tag &= 0xFF; */
162 if (type->tp_version_tag == 0) {
163 /* wrap-around or just starting Python - clear the whole
164 cache by filling names with references to Py_None.
165 Values are also set to NULL for added protection, as they
166 are borrowed reference */
167 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
168 method_cache[i].value = NULL;
169 Py_XDECREF(method_cache[i].name);
170 method_cache[i].name = Py_None;
171 Py_INCREF(Py_None);
173 /* mark all version tags as invalid */
174 PyType_Modified(&PyBaseObject_Type);
175 return 1;
177 bases = type->tp_bases;
178 n = PyTuple_GET_SIZE(bases);
179 for (i = 0; i < n; i++) {
180 PyObject *b = PyTuple_GET_ITEM(bases, i);
181 assert(PyType_Check(b));
182 if (!assign_version_tag((PyTypeObject *)b))
183 return 0;
185 type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
186 return 1;
190 static PyMemberDef type_members[] = {
191 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
192 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
193 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
194 {"__weakrefoffset__", T_LONG,
195 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
196 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
197 {"__dictoffset__", T_LONG,
198 offsetof(PyTypeObject, tp_dictoffset), READONLY},
199 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
203 static PyObject *
204 type_name(PyTypeObject *type, void *context)
206 const char *s;
208 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
209 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
211 Py_INCREF(et->ht_name);
212 return et->ht_name;
214 else {
215 s = strrchr(type->tp_name, '.');
216 if (s == NULL)
217 s = type->tp_name;
218 else
219 s++;
220 return PyString_FromString(s);
224 static int
225 type_set_name(PyTypeObject *type, PyObject *value, void *context)
227 PyHeapTypeObject* et;
229 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
230 PyErr_Format(PyExc_TypeError,
231 "can't set %s.__name__", type->tp_name);
232 return -1;
234 if (!value) {
235 PyErr_Format(PyExc_TypeError,
236 "can't delete %s.__name__", type->tp_name);
237 return -1;
239 if (!PyString_Check(value)) {
240 PyErr_Format(PyExc_TypeError,
241 "can only assign string to %s.__name__, not '%s'",
242 type->tp_name, Py_TYPE(value)->tp_name);
243 return -1;
245 if (strlen(PyString_AS_STRING(value))
246 != (size_t)PyString_GET_SIZE(value)) {
247 PyErr_Format(PyExc_ValueError,
248 "__name__ must not contain null bytes");
249 return -1;
252 et = (PyHeapTypeObject*)type;
254 Py_INCREF(value);
256 Py_DECREF(et->ht_name);
257 et->ht_name = value;
259 type->tp_name = PyString_AS_STRING(value);
261 return 0;
264 static PyObject *
265 type_module(PyTypeObject *type, void *context)
267 PyObject *mod;
268 char *s;
270 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
271 mod = PyDict_GetItemString(type->tp_dict, "__module__");
272 if (!mod) {
273 PyErr_Format(PyExc_AttributeError, "__module__");
274 return 0;
276 Py_XINCREF(mod);
277 return mod;
279 else {
280 s = strrchr(type->tp_name, '.');
281 if (s != NULL)
282 return PyString_FromStringAndSize(
283 type->tp_name, (Py_ssize_t)(s - type->tp_name));
284 return PyString_FromString("__builtin__");
288 static int
289 type_set_module(PyTypeObject *type, PyObject *value, void *context)
291 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
292 PyErr_Format(PyExc_TypeError,
293 "can't set %s.__module__", type->tp_name);
294 return -1;
296 if (!value) {
297 PyErr_Format(PyExc_TypeError,
298 "can't delete %s.__module__", type->tp_name);
299 return -1;
302 PyType_Modified(type);
304 return PyDict_SetItemString(type->tp_dict, "__module__", value);
307 static PyObject *
308 type_abstractmethods(PyTypeObject *type, void *context)
310 PyObject *mod = PyDict_GetItemString(type->tp_dict,
311 "__abstractmethods__");
312 if (!mod) {
313 PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
314 return NULL;
316 Py_XINCREF(mod);
317 return mod;
320 static int
321 type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
323 /* __abstractmethods__ should only be set once on a type, in
324 abc.ABCMeta.__new__, so this function doesn't do anything
325 special to update subclasses.
327 int res = PyDict_SetItemString(type->tp_dict,
328 "__abstractmethods__", value);
329 if (res == 0) {
330 PyType_Modified(type);
331 if (value && PyObject_IsTrue(value)) {
332 type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
334 else {
335 type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
338 return res;
341 static PyObject *
342 type_get_bases(PyTypeObject *type, void *context)
344 Py_INCREF(type->tp_bases);
345 return type->tp_bases;
348 static PyTypeObject *best_base(PyObject *);
349 static int mro_internal(PyTypeObject *);
350 static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
351 static int add_subclass(PyTypeObject*, PyTypeObject*);
352 static void remove_subclass(PyTypeObject *, PyTypeObject *);
353 static void update_all_slots(PyTypeObject *);
355 typedef int (*update_callback)(PyTypeObject *, void *);
356 static int update_subclasses(PyTypeObject *type, PyObject *name,
357 update_callback callback, void *data);
358 static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
359 update_callback callback, void *data);
361 static int
362 mro_subclasses(PyTypeObject *type, PyObject* temp)
364 PyTypeObject *subclass;
365 PyObject *ref, *subclasses, *old_mro;
366 Py_ssize_t i, n;
368 subclasses = type->tp_subclasses;
369 if (subclasses == NULL)
370 return 0;
371 assert(PyList_Check(subclasses));
372 n = PyList_GET_SIZE(subclasses);
373 for (i = 0; i < n; i++) {
374 ref = PyList_GET_ITEM(subclasses, i);
375 assert(PyWeakref_CheckRef(ref));
376 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
377 assert(subclass != NULL);
378 if ((PyObject *)subclass == Py_None)
379 continue;
380 assert(PyType_Check(subclass));
381 old_mro = subclass->tp_mro;
382 if (mro_internal(subclass) < 0) {
383 subclass->tp_mro = old_mro;
384 return -1;
386 else {
387 PyObject* tuple;
388 tuple = PyTuple_Pack(2, subclass, old_mro);
389 Py_DECREF(old_mro);
390 if (!tuple)
391 return -1;
392 if (PyList_Append(temp, tuple) < 0)
393 return -1;
394 Py_DECREF(tuple);
396 if (mro_subclasses(subclass, temp) < 0)
397 return -1;
399 return 0;
402 static int
403 type_set_bases(PyTypeObject *type, PyObject *value, void *context)
405 Py_ssize_t i;
406 int r = 0;
407 PyObject *ob, *temp;
408 PyTypeObject *new_base, *old_base;
409 PyObject *old_bases, *old_mro;
411 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
412 PyErr_Format(PyExc_TypeError,
413 "can't set %s.__bases__", type->tp_name);
414 return -1;
416 if (!value) {
417 PyErr_Format(PyExc_TypeError,
418 "can't delete %s.__bases__", type->tp_name);
419 return -1;
421 if (!PyTuple_Check(value)) {
422 PyErr_Format(PyExc_TypeError,
423 "can only assign tuple to %s.__bases__, not %s",
424 type->tp_name, Py_TYPE(value)->tp_name);
425 return -1;
427 if (PyTuple_GET_SIZE(value) == 0) {
428 PyErr_Format(PyExc_TypeError,
429 "can only assign non-empty tuple to %s.__bases__, not ()",
430 type->tp_name);
431 return -1;
433 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
434 ob = PyTuple_GET_ITEM(value, i);
435 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
436 PyErr_Format(
437 PyExc_TypeError,
438 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
439 type->tp_name, Py_TYPE(ob)->tp_name);
440 return -1;
442 if (PyType_Check(ob)) {
443 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
444 PyErr_SetString(PyExc_TypeError,
445 "a __bases__ item causes an inheritance cycle");
446 return -1;
451 new_base = best_base(value);
453 if (!new_base) {
454 return -1;
457 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
458 return -1;
460 Py_INCREF(new_base);
461 Py_INCREF(value);
463 old_bases = type->tp_bases;
464 old_base = type->tp_base;
465 old_mro = type->tp_mro;
467 type->tp_bases = value;
468 type->tp_base = new_base;
470 if (mro_internal(type) < 0) {
471 goto bail;
474 temp = PyList_New(0);
475 if (!temp)
476 goto bail;
478 r = mro_subclasses(type, temp);
480 if (r < 0) {
481 for (i = 0; i < PyList_Size(temp); i++) {
482 PyTypeObject* cls;
483 PyObject* mro;
484 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
485 "", 2, 2, &cls, &mro);
486 Py_INCREF(mro);
487 ob = cls->tp_mro;
488 cls->tp_mro = mro;
489 Py_DECREF(ob);
491 Py_DECREF(temp);
492 goto bail;
495 Py_DECREF(temp);
497 /* any base that was in __bases__ but now isn't, we
498 need to remove |type| from its tp_subclasses.
499 conversely, any class now in __bases__ that wasn't
500 needs to have |type| added to its subclasses. */
502 /* for now, sod that: just remove from all old_bases,
503 add to all new_bases */
505 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
506 ob = PyTuple_GET_ITEM(old_bases, i);
507 if (PyType_Check(ob)) {
508 remove_subclass(
509 (PyTypeObject*)ob, type);
513 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
514 ob = PyTuple_GET_ITEM(value, i);
515 if (PyType_Check(ob)) {
516 if (add_subclass((PyTypeObject*)ob, type) < 0)
517 r = -1;
521 update_all_slots(type);
523 Py_DECREF(old_bases);
524 Py_DECREF(old_base);
525 Py_DECREF(old_mro);
527 return r;
529 bail:
530 Py_DECREF(type->tp_bases);
531 Py_DECREF(type->tp_base);
532 if (type->tp_mro != old_mro) {
533 Py_DECREF(type->tp_mro);
536 type->tp_bases = old_bases;
537 type->tp_base = old_base;
538 type->tp_mro = old_mro;
540 return -1;
543 static PyObject *
544 type_dict(PyTypeObject *type, void *context)
546 if (type->tp_dict == NULL) {
547 Py_INCREF(Py_None);
548 return Py_None;
550 return PyDictProxy_New(type->tp_dict);
553 static PyObject *
554 type_get_doc(PyTypeObject *type, void *context)
556 PyObject *result;
557 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
558 return PyString_FromString(type->tp_doc);
559 result = PyDict_GetItemString(type->tp_dict, "__doc__");
560 if (result == NULL) {
561 result = Py_None;
562 Py_INCREF(result);
564 else if (Py_TYPE(result)->tp_descr_get) {
565 result = Py_TYPE(result)->tp_descr_get(result, NULL,
566 (PyObject *)type);
568 else {
569 Py_INCREF(result);
571 return result;
574 static PyObject *
575 type___instancecheck__(PyObject *type, PyObject *inst)
577 switch (_PyObject_RealIsInstance(inst, type)) {
578 case -1:
579 return NULL;
580 case 0:
581 Py_RETURN_FALSE;
582 default:
583 Py_RETURN_TRUE;
588 static PyObject *
589 type___subclasscheck__(PyObject *type, PyObject *inst)
591 switch (_PyObject_RealIsSubclass(inst, type)) {
592 case -1:
593 return NULL;
594 case 0:
595 Py_RETURN_FALSE;
596 default:
597 Py_RETURN_TRUE;
602 static PyGetSetDef type_getsets[] = {
603 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
604 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
605 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
606 {"__abstractmethods__", (getter)type_abstractmethods,
607 (setter)type_set_abstractmethods, NULL},
608 {"__dict__", (getter)type_dict, NULL, NULL},
609 {"__doc__", (getter)type_get_doc, NULL, NULL},
614 static PyObject*
615 type_richcompare(PyObject *v, PyObject *w, int op)
617 PyObject *result;
618 Py_uintptr_t vv, ww;
619 int c;
621 /* Make sure both arguments are types. */
622 if (!PyType_Check(v) || !PyType_Check(w) ||
623 /* If there is a __cmp__ method defined, let it be called instead
624 of our dumb function designed merely to warn. See bug
625 #7491. */
626 Py_TYPE(v)->tp_compare || Py_TYPE(w)->tp_compare) {
627 result = Py_NotImplemented;
628 goto out;
631 /* Py3K warning if comparison isn't == or != */
632 if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
633 PyErr_WarnEx(PyExc_DeprecationWarning,
634 "type inequality comparisons not supported "
635 "in 3.x", 1) < 0) {
636 return NULL;
639 /* Compare addresses */
640 vv = (Py_uintptr_t)v;
641 ww = (Py_uintptr_t)w;
642 switch (op) {
643 case Py_LT: c = vv < ww; break;
644 case Py_LE: c = vv <= ww; break;
645 case Py_EQ: c = vv == ww; break;
646 case Py_NE: c = vv != ww; break;
647 case Py_GT: c = vv > ww; break;
648 case Py_GE: c = vv >= ww; break;
649 default:
650 result = Py_NotImplemented;
651 goto out;
653 result = c ? Py_True : Py_False;
655 /* incref and return */
656 out:
657 Py_INCREF(result);
658 return result;
661 static PyObject *
662 type_repr(PyTypeObject *type)
664 PyObject *mod, *name, *rtn;
665 char *kind;
667 mod = type_module(type, NULL);
668 if (mod == NULL)
669 PyErr_Clear();
670 else if (!PyString_Check(mod)) {
671 Py_DECREF(mod);
672 mod = NULL;
674 name = type_name(type, NULL);
675 if (name == NULL)
676 return NULL;
678 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
679 kind = "class";
680 else
681 kind = "type";
683 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
684 rtn = PyString_FromFormat("<%s '%s.%s'>",
685 kind,
686 PyString_AS_STRING(mod),
687 PyString_AS_STRING(name));
689 else
690 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
692 Py_XDECREF(mod);
693 Py_DECREF(name);
694 return rtn;
697 static PyObject *
698 type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
700 PyObject *obj;
702 if (type->tp_new == NULL) {
703 PyErr_Format(PyExc_TypeError,
704 "cannot create '%.100s' instances",
705 type->tp_name);
706 return NULL;
709 obj = type->tp_new(type, args, kwds);
710 if (obj != NULL) {
711 /* Ugly exception: when the call was type(something),
712 don't call tp_init on the result. */
713 if (type == &PyType_Type &&
714 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
715 (kwds == NULL ||
716 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
717 return obj;
718 /* If the returned object is not an instance of type,
719 it won't be initialized. */
720 if (!PyType_IsSubtype(obj->ob_type, type))
721 return obj;
722 type = obj->ob_type;
723 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
724 type->tp_init != NULL &&
725 type->tp_init(obj, args, kwds) < 0) {
726 Py_DECREF(obj);
727 obj = NULL;
730 return obj;
733 PyObject *
734 PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
736 PyObject *obj;
737 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
738 /* note that we need to add one, for the sentinel */
740 if (PyType_IS_GC(type))
741 obj = _PyObject_GC_Malloc(size);
742 else
743 obj = (PyObject *)PyObject_MALLOC(size);
745 if (obj == NULL)
746 return PyErr_NoMemory();
748 memset(obj, '\0', size);
750 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
751 Py_INCREF(type);
753 if (type->tp_itemsize == 0)
754 PyObject_INIT(obj, type);
755 else
756 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
758 if (PyType_IS_GC(type))
759 _PyObject_GC_TRACK(obj);
760 return obj;
763 PyObject *
764 PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
766 return type->tp_alloc(type, 0);
769 /* Helpers for subtyping */
771 static int
772 traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
774 Py_ssize_t i, n;
775 PyMemberDef *mp;
777 n = Py_SIZE(type);
778 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
779 for (i = 0; i < n; i++, mp++) {
780 if (mp->type == T_OBJECT_EX) {
781 char *addr = (char *)self + mp->offset;
782 PyObject *obj = *(PyObject **)addr;
783 if (obj != NULL) {
784 int err = visit(obj, arg);
785 if (err)
786 return err;
790 return 0;
793 static int
794 subtype_traverse(PyObject *self, visitproc visit, void *arg)
796 PyTypeObject *type, *base;
797 traverseproc basetraverse;
799 /* Find the nearest base with a different tp_traverse,
800 and traverse slots while we're at it */
801 type = Py_TYPE(self);
802 base = type;
803 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
804 if (Py_SIZE(base)) {
805 int err = traverse_slots(base, self, visit, arg);
806 if (err)
807 return err;
809 base = base->tp_base;
810 assert(base);
813 if (type->tp_dictoffset != base->tp_dictoffset) {
814 PyObject **dictptr = _PyObject_GetDictPtr(self);
815 if (dictptr && *dictptr)
816 Py_VISIT(*dictptr);
819 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
820 /* For a heaptype, the instances count as references
821 to the type. Traverse the type so the collector
822 can find cycles involving this link. */
823 Py_VISIT(type);
825 if (basetraverse)
826 return basetraverse(self, visit, arg);
827 return 0;
830 static void
831 clear_slots(PyTypeObject *type, PyObject *self)
833 Py_ssize_t i, n;
834 PyMemberDef *mp;
836 n = Py_SIZE(type);
837 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
838 for (i = 0; i < n; i++, mp++) {
839 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
840 char *addr = (char *)self + mp->offset;
841 PyObject *obj = *(PyObject **)addr;
842 if (obj != NULL) {
843 *(PyObject **)addr = NULL;
844 Py_DECREF(obj);
850 static int
851 subtype_clear(PyObject *self)
853 PyTypeObject *type, *base;
854 inquiry baseclear;
856 /* Find the nearest base with a different tp_clear
857 and clear slots while we're at it */
858 type = Py_TYPE(self);
859 base = type;
860 while ((baseclear = base->tp_clear) == subtype_clear) {
861 if (Py_SIZE(base))
862 clear_slots(base, self);
863 base = base->tp_base;
864 assert(base);
867 /* There's no need to clear the instance dict (if any);
868 the collector will call its tp_clear handler. */
870 if (baseclear)
871 return baseclear(self);
872 return 0;
875 static void
876 subtype_dealloc(PyObject *self)
878 PyTypeObject *type, *base;
879 destructor basedealloc;
881 /* Extract the type; we expect it to be a heap type */
882 type = Py_TYPE(self);
883 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
885 /* Test whether the type has GC exactly once */
887 if (!PyType_IS_GC(type)) {
888 /* It's really rare to find a dynamic type that doesn't have
889 GC; it can only happen when deriving from 'object' and not
890 adding any slots or instance variables. This allows
891 certain simplifications: there's no need to call
892 clear_slots(), or DECREF the dict, or clear weakrefs. */
894 /* Maybe call finalizer; exit early if resurrected */
895 if (type->tp_del) {
896 type->tp_del(self);
897 if (self->ob_refcnt > 0)
898 return;
901 /* Find the nearest base with a different tp_dealloc */
902 base = type;
903 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
904 assert(Py_SIZE(base) == 0);
905 base = base->tp_base;
906 assert(base);
909 /* Extract the type again; tp_del may have changed it */
910 type = Py_TYPE(self);
912 /* Call the base tp_dealloc() */
913 assert(basedealloc);
914 basedealloc(self);
916 /* Can't reference self beyond this point */
917 Py_DECREF(type);
919 /* Done */
920 return;
923 /* We get here only if the type has GC */
925 /* UnTrack and re-Track around the trashcan macro, alas */
926 /* See explanation at end of function for full disclosure */
927 PyObject_GC_UnTrack(self);
928 ++_PyTrash_delete_nesting;
929 Py_TRASHCAN_SAFE_BEGIN(self);
930 --_PyTrash_delete_nesting;
931 /* DO NOT restore GC tracking at this point. weakref callbacks
932 * (if any, and whether directly here or indirectly in something we
933 * call) may trigger GC, and if self is tracked at that point, it
934 * will look like trash to GC and GC will try to delete self again.
937 /* Find the nearest base with a different tp_dealloc */
938 base = type;
939 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
940 base = base->tp_base;
941 assert(base);
944 /* If we added a weaklist, we clear it. Do this *before* calling
945 the finalizer (__del__), clearing slots, or clearing the instance
946 dict. */
948 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
949 PyObject_ClearWeakRefs(self);
951 /* Maybe call finalizer; exit early if resurrected */
952 if (type->tp_del) {
953 _PyObject_GC_TRACK(self);
954 type->tp_del(self);
955 if (self->ob_refcnt > 0)
956 goto endlabel; /* resurrected */
957 else
958 _PyObject_GC_UNTRACK(self);
959 /* New weakrefs could be created during the finalizer call.
960 If this occurs, clear them out without calling their
961 finalizers since they might rely on part of the object
962 being finalized that has already been destroyed. */
963 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
964 /* Modeled after GET_WEAKREFS_LISTPTR() */
965 PyWeakReference **list = (PyWeakReference **) \
966 PyObject_GET_WEAKREFS_LISTPTR(self);
967 while (*list)
968 _PyWeakref_ClearRef(*list);
972 /* Clear slots up to the nearest base with a different tp_dealloc */
973 base = type;
974 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
975 if (Py_SIZE(base))
976 clear_slots(base, self);
977 base = base->tp_base;
978 assert(base);
981 /* If we added a dict, DECREF it */
982 if (type->tp_dictoffset && !base->tp_dictoffset) {
983 PyObject **dictptr = _PyObject_GetDictPtr(self);
984 if (dictptr != NULL) {
985 PyObject *dict = *dictptr;
986 if (dict != NULL) {
987 Py_DECREF(dict);
988 *dictptr = NULL;
993 /* Extract the type again; tp_del may have changed it */
994 type = Py_TYPE(self);
996 /* Call the base tp_dealloc(); first retrack self if
997 * basedealloc knows about gc.
999 if (PyType_IS_GC(base))
1000 _PyObject_GC_TRACK(self);
1001 assert(basedealloc);
1002 basedealloc(self);
1004 /* Can't reference self beyond this point */
1005 Py_DECREF(type);
1007 endlabel:
1008 ++_PyTrash_delete_nesting;
1009 Py_TRASHCAN_SAFE_END(self);
1010 --_PyTrash_delete_nesting;
1012 /* Explanation of the weirdness around the trashcan macros:
1014 Q. What do the trashcan macros do?
1016 A. Read the comment titled "Trashcan mechanism" in object.h.
1017 For one, this explains why there must be a call to GC-untrack
1018 before the trashcan begin macro. Without understanding the
1019 trashcan code, the answers to the following questions don't make
1020 sense.
1022 Q. Why do we GC-untrack before the trashcan and then immediately
1023 GC-track again afterward?
1025 A. In the case that the base class is GC-aware, the base class
1026 probably GC-untracks the object. If it does that using the
1027 UNTRACK macro, this will crash when the object is already
1028 untracked. Because we don't know what the base class does, the
1029 only safe thing is to make sure the object is tracked when we
1030 call the base class dealloc. But... The trashcan begin macro
1031 requires that the object is *untracked* before it is called. So
1032 the dance becomes:
1034 GC untrack
1035 trashcan begin
1036 GC track
1038 Q. Why did the last question say "immediately GC-track again"?
1039 It's nowhere near immediately.
1041 A. Because the code *used* to re-track immediately. Bad Idea.
1042 self has a refcount of 0, and if gc ever gets its hands on it
1043 (which can happen if any weakref callback gets invoked), it
1044 looks like trash to gc too, and gc also tries to delete self
1045 then. But we're already deleting self. Double dealloction is
1046 a subtle disaster.
1048 Q. Why the bizarre (net-zero) manipulation of
1049 _PyTrash_delete_nesting around the trashcan macros?
1051 A. Some base classes (e.g. list) also use the trashcan mechanism.
1052 The following scenario used to be possible:
1054 - suppose the trashcan level is one below the trashcan limit
1056 - subtype_dealloc() is called
1058 - the trashcan limit is not yet reached, so the trashcan level
1059 is incremented and the code between trashcan begin and end is
1060 executed
1062 - this destroys much of the object's contents, including its
1063 slots and __dict__
1065 - basedealloc() is called; this is really list_dealloc(), or
1066 some other type which also uses the trashcan macros
1068 - the trashcan limit is now reached, so the object is put on the
1069 trashcan's to-be-deleted-later list
1071 - basedealloc() returns
1073 - subtype_dealloc() decrefs the object's type
1075 - subtype_dealloc() returns
1077 - later, the trashcan code starts deleting the objects from its
1078 to-be-deleted-later list
1080 - subtype_dealloc() is called *AGAIN* for the same object
1082 - at the very least (if the destroyed slots and __dict__ don't
1083 cause problems) the object's type gets decref'ed a second
1084 time, which is *BAD*!!!
1086 The remedy is to make sure that if the code between trashcan
1087 begin and end in subtype_dealloc() is called, the code between
1088 trashcan begin and end in basedealloc() will also be called.
1089 This is done by decrementing the level after passing into the
1090 trashcan block, and incrementing it just before leaving the
1091 block.
1093 But now it's possible that a chain of objects consisting solely
1094 of objects whose deallocator is subtype_dealloc() will defeat
1095 the trashcan mechanism completely: the decremented level means
1096 that the effective level never reaches the limit. Therefore, we
1097 *increment* the level *before* entering the trashcan block, and
1098 matchingly decrement it after leaving. This means the trashcan
1099 code will trigger a little early, but that's no big deal.
1101 Q. Are there any live examples of code in need of all this
1102 complexity?
1104 A. Yes. See SF bug 668433 for code that crashed (when Python was
1105 compiled in debug mode) before the trashcan level manipulations
1106 were added. For more discussion, see SF patches 581742, 575073
1107 and bug 574207.
1111 static PyTypeObject *solid_base(PyTypeObject *type);
1113 /* type test with subclassing support */
1116 PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1118 PyObject *mro;
1120 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1121 return b == a || b == &PyBaseObject_Type;
1123 mro = a->tp_mro;
1124 if (mro != NULL) {
1125 /* Deal with multiple inheritance without recursion
1126 by walking the MRO tuple */
1127 Py_ssize_t i, n;
1128 assert(PyTuple_Check(mro));
1129 n = PyTuple_GET_SIZE(mro);
1130 for (i = 0; i < n; i++) {
1131 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1132 return 1;
1134 return 0;
1136 else {
1137 /* a is not completely initilized yet; follow tp_base */
1138 do {
1139 if (a == b)
1140 return 1;
1141 a = a->tp_base;
1142 } while (a != NULL);
1143 return b == &PyBaseObject_Type;
1147 /* Internal routines to do a method lookup in the type
1148 without looking in the instance dictionary
1149 (so we can't use PyObject_GetAttr) but still binding
1150 it to the instance. The arguments are the object,
1151 the method name as a C string, and the address of a
1152 static variable used to cache the interned Python string.
1154 Two variants:
1156 - lookup_maybe() returns NULL without raising an exception
1157 when the _PyType_Lookup() call fails;
1159 - lookup_method() always raises an exception upon errors.
1161 - _PyObject_LookupSpecial() exported for the benefit of other places.
1164 static PyObject *
1165 lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
1167 PyObject *res;
1169 if (*attrobj == NULL) {
1170 *attrobj = PyString_InternFromString(attrstr);
1171 if (*attrobj == NULL)
1172 return NULL;
1174 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
1175 if (res != NULL) {
1176 descrgetfunc f;
1177 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1178 Py_INCREF(res);
1179 else
1180 res = f(res, self, (PyObject *)(Py_TYPE(self)));
1182 return res;
1185 static PyObject *
1186 lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
1188 PyObject *res = lookup_maybe(self, attrstr, attrobj);
1189 if (res == NULL && !PyErr_Occurred())
1190 PyErr_SetObject(PyExc_AttributeError, *attrobj);
1191 return res;
1194 PyObject *
1195 _PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
1197 assert(!PyInstance_Check(self));
1198 return lookup_maybe(self, attrstr, attrobj);
1201 /* A variation of PyObject_CallMethod that uses lookup_method()
1202 instead of PyObject_GetAttrString(). This uses the same convention
1203 as lookup_method to cache the interned name string object. */
1205 static PyObject *
1206 call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1208 va_list va;
1209 PyObject *args, *func = 0, *retval;
1210 va_start(va, format);
1212 func = lookup_maybe(o, name, nameobj);
1213 if (func == NULL) {
1214 va_end(va);
1215 if (!PyErr_Occurred())
1216 PyErr_SetObject(PyExc_AttributeError, *nameobj);
1217 return NULL;
1220 if (format && *format)
1221 args = Py_VaBuildValue(format, va);
1222 else
1223 args = PyTuple_New(0);
1225 va_end(va);
1227 if (args == NULL)
1228 return NULL;
1230 assert(PyTuple_Check(args));
1231 retval = PyObject_Call(func, args, NULL);
1233 Py_DECREF(args);
1234 Py_DECREF(func);
1236 return retval;
1239 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
1241 static PyObject *
1242 call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
1244 va_list va;
1245 PyObject *args, *func = 0, *retval;
1246 va_start(va, format);
1248 func = lookup_maybe(o, name, nameobj);
1249 if (func == NULL) {
1250 va_end(va);
1251 if (!PyErr_Occurred()) {
1252 Py_INCREF(Py_NotImplemented);
1253 return Py_NotImplemented;
1255 return NULL;
1258 if (format && *format)
1259 args = Py_VaBuildValue(format, va);
1260 else
1261 args = PyTuple_New(0);
1263 va_end(va);
1265 if (args == NULL)
1266 return NULL;
1268 assert(PyTuple_Check(args));
1269 retval = PyObject_Call(func, args, NULL);
1271 Py_DECREF(args);
1272 Py_DECREF(func);
1274 return retval;
1277 static int
1278 fill_classic_mro(PyObject *mro, PyObject *cls)
1280 PyObject *bases, *base;
1281 Py_ssize_t i, n;
1283 assert(PyList_Check(mro));
1284 assert(PyClass_Check(cls));
1285 i = PySequence_Contains(mro, cls);
1286 if (i < 0)
1287 return -1;
1288 if (!i) {
1289 if (PyList_Append(mro, cls) < 0)
1290 return -1;
1292 bases = ((PyClassObject *)cls)->cl_bases;
1293 assert(bases && PyTuple_Check(bases));
1294 n = PyTuple_GET_SIZE(bases);
1295 for (i = 0; i < n; i++) {
1296 base = PyTuple_GET_ITEM(bases, i);
1297 if (fill_classic_mro(mro, base) < 0)
1298 return -1;
1300 return 0;
1303 static PyObject *
1304 classic_mro(PyObject *cls)
1306 PyObject *mro;
1308 assert(PyClass_Check(cls));
1309 mro = PyList_New(0);
1310 if (mro != NULL) {
1311 if (fill_classic_mro(mro, cls) == 0)
1312 return mro;
1313 Py_DECREF(mro);
1315 return NULL;
1319 Method resolution order algorithm C3 described in
1320 "A Monotonic Superclass Linearization for Dylan",
1321 by Kim Barrett, Bob Cassel, Paul Haahr,
1322 David A. Moon, Keith Playford, and P. Tucker Withington.
1323 (OOPSLA 1996)
1325 Some notes about the rules implied by C3:
1327 No duplicate bases.
1328 It isn't legal to repeat a class in a list of base classes.
1330 The next three properties are the 3 constraints in "C3".
1332 Local precendece order.
1333 If A precedes B in C's MRO, then A will precede B in the MRO of all
1334 subclasses of C.
1336 Monotonicity.
1337 The MRO of a class must be an extension without reordering of the
1338 MRO of each of its superclasses.
1340 Extended Precedence Graph (EPG).
1341 Linearization is consistent if there is a path in the EPG from
1342 each class to all its successors in the linearization. See
1343 the paper for definition of EPG.
1346 static int
1347 tail_contains(PyObject *list, int whence, PyObject *o) {
1348 Py_ssize_t j, size;
1349 size = PyList_GET_SIZE(list);
1351 for (j = whence+1; j < size; j++) {
1352 if (PyList_GET_ITEM(list, j) == o)
1353 return 1;
1355 return 0;
1358 static PyObject *
1359 class_name(PyObject *cls)
1361 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1362 if (name == NULL) {
1363 PyErr_Clear();
1364 Py_XDECREF(name);
1365 name = PyObject_Repr(cls);
1367 if (name == NULL)
1368 return NULL;
1369 if (!PyString_Check(name)) {
1370 Py_DECREF(name);
1371 return NULL;
1373 return name;
1376 static int
1377 check_duplicates(PyObject *list)
1379 Py_ssize_t i, j, n;
1380 /* Let's use a quadratic time algorithm,
1381 assuming that the bases lists is short.
1383 n = PyList_GET_SIZE(list);
1384 for (i = 0; i < n; i++) {
1385 PyObject *o = PyList_GET_ITEM(list, i);
1386 for (j = i + 1; j < n; j++) {
1387 if (PyList_GET_ITEM(list, j) == o) {
1388 o = class_name(o);
1389 PyErr_Format(PyExc_TypeError,
1390 "duplicate base class %s",
1391 o ? PyString_AS_STRING(o) : "?");
1392 Py_XDECREF(o);
1393 return -1;
1397 return 0;
1400 /* Raise a TypeError for an MRO order disagreement.
1402 It's hard to produce a good error message. In the absence of better
1403 insight into error reporting, report the classes that were candidates
1404 to be put next into the MRO. There is some conflict between the
1405 order in which they should be put in the MRO, but it's hard to
1406 diagnose what constraint can't be satisfied.
1409 static void
1410 set_mro_error(PyObject *to_merge, int *remain)
1412 Py_ssize_t i, n, off, to_merge_size;
1413 char buf[1000];
1414 PyObject *k, *v;
1415 PyObject *set = PyDict_New();
1416 if (!set) return;
1418 to_merge_size = PyList_GET_SIZE(to_merge);
1419 for (i = 0; i < to_merge_size; i++) {
1420 PyObject *L = PyList_GET_ITEM(to_merge, i);
1421 if (remain[i] < PyList_GET_SIZE(L)) {
1422 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1423 if (PyDict_SetItem(set, c, Py_None) < 0) {
1424 Py_DECREF(set);
1425 return;
1429 n = PyDict_Size(set);
1431 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1432 consistent method resolution\norder (MRO) for bases");
1433 i = 0;
1434 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1435 PyObject *name = class_name(k);
1436 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1437 name ? PyString_AS_STRING(name) : "?");
1438 Py_XDECREF(name);
1439 if (--n && (size_t)(off+1) < sizeof(buf)) {
1440 buf[off++] = ',';
1441 buf[off] = '\0';
1444 PyErr_SetString(PyExc_TypeError, buf);
1445 Py_DECREF(set);
1448 static int
1449 pmerge(PyObject *acc, PyObject* to_merge) {
1450 Py_ssize_t i, j, to_merge_size, empty_cnt;
1451 int *remain;
1452 int ok;
1454 to_merge_size = PyList_GET_SIZE(to_merge);
1456 /* remain stores an index into each sublist of to_merge.
1457 remain[i] is the index of the next base in to_merge[i]
1458 that is not included in acc.
1460 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1461 if (remain == NULL)
1462 return -1;
1463 for (i = 0; i < to_merge_size; i++)
1464 remain[i] = 0;
1466 again:
1467 empty_cnt = 0;
1468 for (i = 0; i < to_merge_size; i++) {
1469 PyObject *candidate;
1471 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1473 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1474 empty_cnt++;
1475 continue;
1478 /* Choose next candidate for MRO.
1480 The input sequences alone can determine the choice.
1481 If not, choose the class which appears in the MRO
1482 of the earliest direct superclass of the new class.
1485 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1486 for (j = 0; j < to_merge_size; j++) {
1487 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1488 if (tail_contains(j_lst, remain[j], candidate)) {
1489 goto skip; /* continue outer loop */
1492 ok = PyList_Append(acc, candidate);
1493 if (ok < 0) {
1494 PyMem_Free(remain);
1495 return -1;
1497 for (j = 0; j < to_merge_size; j++) {
1498 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1499 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1500 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1501 remain[j]++;
1504 goto again;
1505 skip: ;
1508 if (empty_cnt == to_merge_size) {
1509 PyMem_FREE(remain);
1510 return 0;
1512 set_mro_error(to_merge, remain);
1513 PyMem_FREE(remain);
1514 return -1;
1517 static PyObject *
1518 mro_implementation(PyTypeObject *type)
1520 Py_ssize_t i, n;
1521 int ok;
1522 PyObject *bases, *result;
1523 PyObject *to_merge, *bases_aslist;
1525 if (type->tp_dict == NULL) {
1526 if (PyType_Ready(type) < 0)
1527 return NULL;
1530 /* Find a superclass linearization that honors the constraints
1531 of the explicit lists of bases and the constraints implied by
1532 each base class.
1534 to_merge is a list of lists, where each list is a superclass
1535 linearization implied by a base class. The last element of
1536 to_merge is the declared list of bases.
1539 bases = type->tp_bases;
1540 n = PyTuple_GET_SIZE(bases);
1542 to_merge = PyList_New(n+1);
1543 if (to_merge == NULL)
1544 return NULL;
1546 for (i = 0; i < n; i++) {
1547 PyObject *base = PyTuple_GET_ITEM(bases, i);
1548 PyObject *parentMRO;
1549 if (PyType_Check(base))
1550 parentMRO = PySequence_List(
1551 ((PyTypeObject*)base)->tp_mro);
1552 else
1553 parentMRO = classic_mro(base);
1554 if (parentMRO == NULL) {
1555 Py_DECREF(to_merge);
1556 return NULL;
1559 PyList_SET_ITEM(to_merge, i, parentMRO);
1562 bases_aslist = PySequence_List(bases);
1563 if (bases_aslist == NULL) {
1564 Py_DECREF(to_merge);
1565 return NULL;
1567 /* This is just a basic sanity check. */
1568 if (check_duplicates(bases_aslist) < 0) {
1569 Py_DECREF(to_merge);
1570 Py_DECREF(bases_aslist);
1571 return NULL;
1573 PyList_SET_ITEM(to_merge, n, bases_aslist);
1575 result = Py_BuildValue("[O]", (PyObject *)type);
1576 if (result == NULL) {
1577 Py_DECREF(to_merge);
1578 return NULL;
1581 ok = pmerge(result, to_merge);
1582 Py_DECREF(to_merge);
1583 if (ok < 0) {
1584 Py_DECREF(result);
1585 return NULL;
1588 return result;
1591 static PyObject *
1592 mro_external(PyObject *self)
1594 PyTypeObject *type = (PyTypeObject *)self;
1596 return mro_implementation(type);
1599 static int
1600 mro_internal(PyTypeObject *type)
1602 PyObject *mro, *result, *tuple;
1603 int checkit = 0;
1605 if (Py_TYPE(type) == &PyType_Type) {
1606 result = mro_implementation(type);
1608 else {
1609 static PyObject *mro_str;
1610 checkit = 1;
1611 mro = lookup_method((PyObject *)type, "mro", &mro_str);
1612 if (mro == NULL)
1613 return -1;
1614 result = PyObject_CallObject(mro, NULL);
1615 Py_DECREF(mro);
1617 if (result == NULL)
1618 return -1;
1619 tuple = PySequence_Tuple(result);
1620 Py_DECREF(result);
1621 if (tuple == NULL)
1622 return -1;
1623 if (checkit) {
1624 Py_ssize_t i, len;
1625 PyObject *cls;
1626 PyTypeObject *solid;
1628 solid = solid_base(type);
1630 len = PyTuple_GET_SIZE(tuple);
1632 for (i = 0; i < len; i++) {
1633 PyTypeObject *t;
1634 cls = PyTuple_GET_ITEM(tuple, i);
1635 if (PyClass_Check(cls))
1636 continue;
1637 else if (!PyType_Check(cls)) {
1638 PyErr_Format(PyExc_TypeError,
1639 "mro() returned a non-class ('%.500s')",
1640 Py_TYPE(cls)->tp_name);
1641 Py_DECREF(tuple);
1642 return -1;
1644 t = (PyTypeObject*)cls;
1645 if (!PyType_IsSubtype(solid, solid_base(t))) {
1646 PyErr_Format(PyExc_TypeError,
1647 "mro() returned base with unsuitable layout ('%.500s')",
1648 t->tp_name);
1649 Py_DECREF(tuple);
1650 return -1;
1654 type->tp_mro = tuple;
1656 type_mro_modified(type, type->tp_mro);
1657 /* corner case: the old-style super class might have been hidden
1658 from the custom MRO */
1659 type_mro_modified(type, type->tp_bases);
1661 PyType_Modified(type);
1663 return 0;
1667 /* Calculate the best base amongst multiple base classes.
1668 This is the first one that's on the path to the "solid base". */
1670 static PyTypeObject *
1671 best_base(PyObject *bases)
1673 Py_ssize_t i, n;
1674 PyTypeObject *base, *winner, *candidate, *base_i;
1675 PyObject *base_proto;
1677 assert(PyTuple_Check(bases));
1678 n = PyTuple_GET_SIZE(bases);
1679 assert(n > 0);
1680 base = NULL;
1681 winner = NULL;
1682 for (i = 0; i < n; i++) {
1683 base_proto = PyTuple_GET_ITEM(bases, i);
1684 if (PyClass_Check(base_proto))
1685 continue;
1686 if (!PyType_Check(base_proto)) {
1687 PyErr_SetString(
1688 PyExc_TypeError,
1689 "bases must be types");
1690 return NULL;
1692 base_i = (PyTypeObject *)base_proto;
1693 if (base_i->tp_dict == NULL) {
1694 if (PyType_Ready(base_i) < 0)
1695 return NULL;
1697 candidate = solid_base(base_i);
1698 if (winner == NULL) {
1699 winner = candidate;
1700 base = base_i;
1702 else if (PyType_IsSubtype(winner, candidate))
1704 else if (PyType_IsSubtype(candidate, winner)) {
1705 winner = candidate;
1706 base = base_i;
1708 else {
1709 PyErr_SetString(
1710 PyExc_TypeError,
1711 "multiple bases have "
1712 "instance lay-out conflict");
1713 return NULL;
1716 if (base == NULL)
1717 PyErr_SetString(PyExc_TypeError,
1718 "a new-style class can't have only classic bases");
1719 return base;
1722 static int
1723 extra_ivars(PyTypeObject *type, PyTypeObject *base)
1725 size_t t_size = type->tp_basicsize;
1726 size_t b_size = base->tp_basicsize;
1728 assert(t_size >= b_size); /* Else type smaller than base! */
1729 if (type->tp_itemsize || base->tp_itemsize) {
1730 /* If itemsize is involved, stricter rules */
1731 return t_size != b_size ||
1732 type->tp_itemsize != base->tp_itemsize;
1734 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1735 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1736 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1737 t_size -= sizeof(PyObject *);
1738 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1739 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1740 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1741 t_size -= sizeof(PyObject *);
1743 return t_size != b_size;
1746 static PyTypeObject *
1747 solid_base(PyTypeObject *type)
1749 PyTypeObject *base;
1751 if (type->tp_base)
1752 base = solid_base(type->tp_base);
1753 else
1754 base = &PyBaseObject_Type;
1755 if (extra_ivars(type, base))
1756 return type;
1757 else
1758 return base;
1761 static void object_dealloc(PyObject *);
1762 static int object_init(PyObject *, PyObject *, PyObject *);
1763 static int update_slot(PyTypeObject *, PyObject *);
1764 static void fixup_slot_dispatchers(PyTypeObject *);
1767 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1768 * inherited from various builtin types. The builtin base usually provides
1769 * its own __dict__ descriptor, so we use that when we can.
1771 static PyTypeObject *
1772 get_builtin_base_with_dict(PyTypeObject *type)
1774 while (type->tp_base != NULL) {
1775 if (type->tp_dictoffset != 0 &&
1776 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1777 return type;
1778 type = type->tp_base;
1780 return NULL;
1783 static PyObject *
1784 get_dict_descriptor(PyTypeObject *type)
1786 static PyObject *dict_str;
1787 PyObject *descr;
1789 if (dict_str == NULL) {
1790 dict_str = PyString_InternFromString("__dict__");
1791 if (dict_str == NULL)
1792 return NULL;
1794 descr = _PyType_Lookup(type, dict_str);
1795 if (descr == NULL || !PyDescr_IsData(descr))
1796 return NULL;
1798 return descr;
1801 static void
1802 raise_dict_descr_error(PyObject *obj)
1804 PyErr_Format(PyExc_TypeError,
1805 "this __dict__ descriptor does not support "
1806 "'%.200s' objects", obj->ob_type->tp_name);
1809 static PyObject *
1810 subtype_dict(PyObject *obj, void *context)
1812 PyObject **dictptr;
1813 PyObject *dict;
1814 PyTypeObject *base;
1816 base = get_builtin_base_with_dict(obj->ob_type);
1817 if (base != NULL) {
1818 descrgetfunc func;
1819 PyObject *descr = get_dict_descriptor(base);
1820 if (descr == NULL) {
1821 raise_dict_descr_error(obj);
1822 return NULL;
1824 func = descr->ob_type->tp_descr_get;
1825 if (func == NULL) {
1826 raise_dict_descr_error(obj);
1827 return NULL;
1829 return func(descr, obj, (PyObject *)(obj->ob_type));
1832 dictptr = _PyObject_GetDictPtr(obj);
1833 if (dictptr == NULL) {
1834 PyErr_SetString(PyExc_AttributeError,
1835 "This object has no __dict__");
1836 return NULL;
1838 dict = *dictptr;
1839 if (dict == NULL)
1840 *dictptr = dict = PyDict_New();
1841 Py_XINCREF(dict);
1842 return dict;
1845 static int
1846 subtype_setdict(PyObject *obj, PyObject *value, void *context)
1848 PyObject **dictptr;
1849 PyObject *dict;
1850 PyTypeObject *base;
1852 base = get_builtin_base_with_dict(obj->ob_type);
1853 if (base != NULL) {
1854 descrsetfunc func;
1855 PyObject *descr = get_dict_descriptor(base);
1856 if (descr == NULL) {
1857 raise_dict_descr_error(obj);
1858 return -1;
1860 func = descr->ob_type->tp_descr_set;
1861 if (func == NULL) {
1862 raise_dict_descr_error(obj);
1863 return -1;
1865 return func(descr, obj, value);
1868 dictptr = _PyObject_GetDictPtr(obj);
1869 if (dictptr == NULL) {
1870 PyErr_SetString(PyExc_AttributeError,
1871 "This object has no __dict__");
1872 return -1;
1874 if (value != NULL && !PyDict_Check(value)) {
1875 PyErr_Format(PyExc_TypeError,
1876 "__dict__ must be set to a dictionary, "
1877 "not a '%.200s'", Py_TYPE(value)->tp_name);
1878 return -1;
1880 dict = *dictptr;
1881 Py_XINCREF(value);
1882 *dictptr = value;
1883 Py_XDECREF(dict);
1884 return 0;
1887 static PyObject *
1888 subtype_getweakref(PyObject *obj, void *context)
1890 PyObject **weaklistptr;
1891 PyObject *result;
1893 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
1894 PyErr_SetString(PyExc_AttributeError,
1895 "This object has no __weakref__");
1896 return NULL;
1898 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1899 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1900 (size_t)(Py_TYPE(obj)->tp_basicsize));
1901 weaklistptr = (PyObject **)
1902 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
1903 if (*weaklistptr == NULL)
1904 result = Py_None;
1905 else
1906 result = *weaklistptr;
1907 Py_INCREF(result);
1908 return result;
1911 /* Three variants on the subtype_getsets list. */
1913 static PyGetSetDef subtype_getsets_full[] = {
1914 {"__dict__", subtype_dict, subtype_setdict,
1915 PyDoc_STR("dictionary for instance variables (if defined)")},
1916 {"__weakref__", subtype_getweakref, NULL,
1917 PyDoc_STR("list of weak references to the object (if defined)")},
1921 static PyGetSetDef subtype_getsets_dict_only[] = {
1922 {"__dict__", subtype_dict, subtype_setdict,
1923 PyDoc_STR("dictionary for instance variables (if defined)")},
1927 static PyGetSetDef subtype_getsets_weakref_only[] = {
1928 {"__weakref__", subtype_getweakref, NULL,
1929 PyDoc_STR("list of weak references to the object (if defined)")},
1933 static int
1934 valid_identifier(PyObject *s)
1936 unsigned char *p;
1937 Py_ssize_t i, n;
1939 if (!PyString_Check(s)) {
1940 PyErr_Format(PyExc_TypeError,
1941 "__slots__ items must be strings, not '%.200s'",
1942 Py_TYPE(s)->tp_name);
1943 return 0;
1945 p = (unsigned char *) PyString_AS_STRING(s);
1946 n = PyString_GET_SIZE(s);
1947 /* We must reject an empty name. As a hack, we bump the
1948 length to 1 so that the loop will balk on the trailing \0. */
1949 if (n == 0)
1950 n = 1;
1951 for (i = 0; i < n; i++, p++) {
1952 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1953 PyErr_SetString(PyExc_TypeError,
1954 "__slots__ must be identifiers");
1955 return 0;
1958 return 1;
1961 #ifdef Py_USING_UNICODE
1962 /* Replace Unicode objects in slots. */
1964 static PyObject *
1965 _unicode_to_string(PyObject *slots, Py_ssize_t nslots)
1967 PyObject *tmp = NULL;
1968 PyObject *slot_name, *new_name;
1969 Py_ssize_t i;
1971 for (i = 0; i < nslots; i++) {
1972 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1973 if (tmp == NULL) {
1974 tmp = PySequence_List(slots);
1975 if (tmp == NULL)
1976 return NULL;
1978 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1979 NULL);
1980 if (new_name == NULL) {
1981 Py_DECREF(tmp);
1982 return NULL;
1984 Py_INCREF(new_name);
1985 PyList_SET_ITEM(tmp, i, new_name);
1986 Py_DECREF(slot_name);
1989 if (tmp != NULL) {
1990 slots = PyList_AsTuple(tmp);
1991 Py_DECREF(tmp);
1993 return slots;
1995 #endif
1997 /* Forward */
1998 static int
1999 object_init(PyObject *self, PyObject *args, PyObject *kwds);
2001 static int
2002 type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2004 int res;
2006 assert(args != NULL && PyTuple_Check(args));
2007 assert(kwds == NULL || PyDict_Check(kwds));
2009 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2010 PyErr_SetString(PyExc_TypeError,
2011 "type.__init__() takes no keyword arguments");
2012 return -1;
2015 if (args != NULL && PyTuple_Check(args) &&
2016 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2017 PyErr_SetString(PyExc_TypeError,
2018 "type.__init__() takes 1 or 3 arguments");
2019 return -1;
2022 /* Call object.__init__(self) now. */
2023 /* XXX Could call super(type, cls).__init__() but what's the point? */
2024 args = PyTuple_GetSlice(args, 0, 0);
2025 res = object_init(cls, args, NULL);
2026 Py_DECREF(args);
2027 return res;
2030 static PyObject *
2031 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2033 PyObject *name, *bases, *dict;
2034 static char *kwlist[] = {"name", "bases", "dict", 0};
2035 PyObject *slots, *tmp, *newslots;
2036 PyTypeObject *type, *base, *tmptype, *winner;
2037 PyHeapTypeObject *et;
2038 PyMemberDef *mp;
2039 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
2040 int j, may_add_dict, may_add_weak;
2042 assert(args != NULL && PyTuple_Check(args));
2043 assert(kwds == NULL || PyDict_Check(kwds));
2045 /* Special case: type(x) should return x->ob_type */
2047 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2048 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
2050 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
2051 PyObject *x = PyTuple_GET_ITEM(args, 0);
2052 Py_INCREF(Py_TYPE(x));
2053 return (PyObject *) Py_TYPE(x);
2056 /* SF bug 475327 -- if that didn't trigger, we need 3
2057 arguments. but PyArg_ParseTupleAndKeywords below may give
2058 a msg saying type() needs exactly 3. */
2059 if (nargs + nkwds != 3) {
2060 PyErr_SetString(PyExc_TypeError,
2061 "type() takes 1 or 3 arguments");
2062 return NULL;
2066 /* Check arguments: (name, bases, dict) */
2067 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
2068 &name,
2069 &PyTuple_Type, &bases,
2070 &PyDict_Type, &dict))
2071 return NULL;
2073 /* Determine the proper metatype to deal with this,
2074 and check for metatype conflicts while we're at it.
2075 Note that if some other metatype wins to contract,
2076 it's possible that its instances are not types. */
2077 nbases = PyTuple_GET_SIZE(bases);
2078 winner = metatype;
2079 for (i = 0; i < nbases; i++) {
2080 tmp = PyTuple_GET_ITEM(bases, i);
2081 tmptype = tmp->ob_type;
2082 if (tmptype == &PyClass_Type)
2083 continue; /* Special case classic classes */
2084 if (PyType_IsSubtype(winner, tmptype))
2085 continue;
2086 if (PyType_IsSubtype(tmptype, winner)) {
2087 winner = tmptype;
2088 continue;
2090 PyErr_SetString(PyExc_TypeError,
2091 "metaclass conflict: "
2092 "the metaclass of a derived class "
2093 "must be a (non-strict) subclass "
2094 "of the metaclasses of all its bases");
2095 return NULL;
2097 if (winner != metatype) {
2098 if (winner->tp_new != type_new) /* Pass it to the winner */
2099 return winner->tp_new(winner, args, kwds);
2100 metatype = winner;
2103 /* Adjust for empty tuple bases */
2104 if (nbases == 0) {
2105 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2106 if (bases == NULL)
2107 return NULL;
2108 nbases = 1;
2110 else
2111 Py_INCREF(bases);
2113 /* XXX From here until type is allocated, "return NULL" leaks bases! */
2115 /* Calculate best base, and check that all bases are type objects */
2116 base = best_base(bases);
2117 if (base == NULL) {
2118 Py_DECREF(bases);
2119 return NULL;
2121 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2122 PyErr_Format(PyExc_TypeError,
2123 "type '%.100s' is not an acceptable base type",
2124 base->tp_name);
2125 Py_DECREF(bases);
2126 return NULL;
2129 /* Check for a __slots__ sequence variable in dict, and count it */
2130 slots = PyDict_GetItemString(dict, "__slots__");
2131 nslots = 0;
2132 add_dict = 0;
2133 add_weak = 0;
2134 may_add_dict = base->tp_dictoffset == 0;
2135 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2136 if (slots == NULL) {
2137 if (may_add_dict) {
2138 add_dict++;
2140 if (may_add_weak) {
2141 add_weak++;
2144 else {
2145 /* Have slots */
2147 /* Make it into a tuple */
2148 if (PyString_Check(slots) || PyUnicode_Check(slots))
2149 slots = PyTuple_Pack(1, slots);
2150 else
2151 slots = PySequence_Tuple(slots);
2152 if (slots == NULL) {
2153 Py_DECREF(bases);
2154 return NULL;
2156 assert(PyTuple_Check(slots));
2158 /* Are slots allowed? */
2159 nslots = PyTuple_GET_SIZE(slots);
2160 if (nslots > 0 && base->tp_itemsize != 0) {
2161 PyErr_Format(PyExc_TypeError,
2162 "nonempty __slots__ "
2163 "not supported for subtype of '%s'",
2164 base->tp_name);
2165 bad_slots:
2166 Py_DECREF(bases);
2167 Py_DECREF(slots);
2168 return NULL;
2171 #ifdef Py_USING_UNICODE
2172 tmp = _unicode_to_string(slots, nslots);
2173 if (tmp == NULL)
2174 goto bad_slots;
2175 if (tmp != slots) {
2176 Py_DECREF(slots);
2177 slots = tmp;
2179 #endif
2180 /* Check for valid slot names and two special cases */
2181 for (i = 0; i < nslots; i++) {
2182 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2183 char *s;
2184 if (!valid_identifier(tmp))
2185 goto bad_slots;
2186 assert(PyString_Check(tmp));
2187 s = PyString_AS_STRING(tmp);
2188 if (strcmp(s, "__dict__") == 0) {
2189 if (!may_add_dict || add_dict) {
2190 PyErr_SetString(PyExc_TypeError,
2191 "__dict__ slot disallowed: "
2192 "we already got one");
2193 goto bad_slots;
2195 add_dict++;
2197 if (strcmp(s, "__weakref__") == 0) {
2198 if (!may_add_weak || add_weak) {
2199 PyErr_SetString(PyExc_TypeError,
2200 "__weakref__ slot disallowed: "
2201 "either we already got one, "
2202 "or __itemsize__ != 0");
2203 goto bad_slots;
2205 add_weak++;
2209 /* Copy slots into a list, mangle names and sort them.
2210 Sorted names are needed for __class__ assignment.
2211 Convert them back to tuple at the end.
2213 newslots = PyList_New(nslots - add_dict - add_weak);
2214 if (newslots == NULL)
2215 goto bad_slots;
2216 for (i = j = 0; i < nslots; i++) {
2217 char *s;
2218 tmp = PyTuple_GET_ITEM(slots, i);
2219 s = PyString_AS_STRING(tmp);
2220 if ((add_dict && strcmp(s, "__dict__") == 0) ||
2221 (add_weak && strcmp(s, "__weakref__") == 0))
2222 continue;
2223 tmp =_Py_Mangle(name, tmp);
2224 if (!tmp)
2225 goto bad_slots;
2226 PyList_SET_ITEM(newslots, j, tmp);
2227 j++;
2229 assert(j == nslots - add_dict - add_weak);
2230 nslots = j;
2231 Py_DECREF(slots);
2232 if (PyList_Sort(newslots) == -1) {
2233 Py_DECREF(bases);
2234 Py_DECREF(newslots);
2235 return NULL;
2237 slots = PyList_AsTuple(newslots);
2238 Py_DECREF(newslots);
2239 if (slots == NULL) {
2240 Py_DECREF(bases);
2241 return NULL;
2244 /* Secondary bases may provide weakrefs or dict */
2245 if (nbases > 1 &&
2246 ((may_add_dict && !add_dict) ||
2247 (may_add_weak && !add_weak))) {
2248 for (i = 0; i < nbases; i++) {
2249 tmp = PyTuple_GET_ITEM(bases, i);
2250 if (tmp == (PyObject *)base)
2251 continue; /* Skip primary base */
2252 if (PyClass_Check(tmp)) {
2253 /* Classic base class provides both */
2254 if (may_add_dict && !add_dict)
2255 add_dict++;
2256 if (may_add_weak && !add_weak)
2257 add_weak++;
2258 break;
2260 assert(PyType_Check(tmp));
2261 tmptype = (PyTypeObject *)tmp;
2262 if (may_add_dict && !add_dict &&
2263 tmptype->tp_dictoffset != 0)
2264 add_dict++;
2265 if (may_add_weak && !add_weak &&
2266 tmptype->tp_weaklistoffset != 0)
2267 add_weak++;
2268 if (may_add_dict && !add_dict)
2269 continue;
2270 if (may_add_weak && !add_weak)
2271 continue;
2272 /* Nothing more to check */
2273 break;
2278 /* XXX From here until type is safely allocated,
2279 "return NULL" may leak slots! */
2281 /* Allocate the type object */
2282 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2283 if (type == NULL) {
2284 Py_XDECREF(slots);
2285 Py_DECREF(bases);
2286 return NULL;
2289 /* Keep name and slots alive in the extended type object */
2290 et = (PyHeapTypeObject *)type;
2291 Py_INCREF(name);
2292 et->ht_name = name;
2293 et->ht_slots = slots;
2295 /* Initialize tp_flags */
2296 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2297 Py_TPFLAGS_BASETYPE;
2298 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2299 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2300 if (base->tp_flags & Py_TPFLAGS_HAVE_NEWBUFFER)
2301 type->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
2303 /* It's a new-style number unless it specifically inherits any
2304 old-style numeric behavior */
2305 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
2306 (base->tp_as_number == NULL))
2307 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
2309 /* Initialize essential fields */
2310 type->tp_as_number = &et->as_number;
2311 type->tp_as_sequence = &et->as_sequence;
2312 type->tp_as_mapping = &et->as_mapping;
2313 type->tp_as_buffer = &et->as_buffer;
2314 type->tp_name = PyString_AS_STRING(name);
2316 /* Set tp_base and tp_bases */
2317 type->tp_bases = bases;
2318 Py_INCREF(base);
2319 type->tp_base = base;
2321 /* Initialize tp_dict from passed-in dict */
2322 type->tp_dict = dict = PyDict_Copy(dict);
2323 if (dict == NULL) {
2324 Py_DECREF(type);
2325 return NULL;
2328 /* Set __module__ in the dict */
2329 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2330 tmp = PyEval_GetGlobals();
2331 if (tmp != NULL) {
2332 tmp = PyDict_GetItemString(tmp, "__name__");
2333 if (tmp != NULL) {
2334 if (PyDict_SetItemString(dict, "__module__",
2335 tmp) < 0)
2336 return NULL;
2341 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2342 and is a string. The __doc__ accessor will first look for tp_doc;
2343 if that fails, it will still look into __dict__.
2346 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2347 if (doc != NULL && PyString_Check(doc)) {
2348 const size_t n = (size_t)PyString_GET_SIZE(doc);
2349 char *tp_doc = (char *)PyObject_MALLOC(n+1);
2350 if (tp_doc == NULL) {
2351 Py_DECREF(type);
2352 return NULL;
2354 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
2355 type->tp_doc = tp_doc;
2359 /* Special-case __new__: if it's a plain function,
2360 make it a static function */
2361 tmp = PyDict_GetItemString(dict, "__new__");
2362 if (tmp != NULL && PyFunction_Check(tmp)) {
2363 tmp = PyStaticMethod_New(tmp);
2364 if (tmp == NULL) {
2365 Py_DECREF(type);
2366 return NULL;
2368 PyDict_SetItemString(dict, "__new__", tmp);
2369 Py_DECREF(tmp);
2372 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2373 mp = PyHeapType_GET_MEMBERS(et);
2374 slotoffset = base->tp_basicsize;
2375 if (slots != NULL) {
2376 for (i = 0; i < nslots; i++, mp++) {
2377 mp->name = PyString_AS_STRING(
2378 PyTuple_GET_ITEM(slots, i));
2379 mp->type = T_OBJECT_EX;
2380 mp->offset = slotoffset;
2382 /* __dict__ and __weakref__ are already filtered out */
2383 assert(strcmp(mp->name, "__dict__") != 0);
2384 assert(strcmp(mp->name, "__weakref__") != 0);
2386 slotoffset += sizeof(PyObject *);
2389 if (add_dict) {
2390 if (base->tp_itemsize)
2391 type->tp_dictoffset = -(long)sizeof(PyObject *);
2392 else
2393 type->tp_dictoffset = slotoffset;
2394 slotoffset += sizeof(PyObject *);
2396 if (add_weak) {
2397 assert(!base->tp_itemsize);
2398 type->tp_weaklistoffset = slotoffset;
2399 slotoffset += sizeof(PyObject *);
2401 type->tp_basicsize = slotoffset;
2402 type->tp_itemsize = base->tp_itemsize;
2403 type->tp_members = PyHeapType_GET_MEMBERS(et);
2405 if (type->tp_weaklistoffset && type->tp_dictoffset)
2406 type->tp_getset = subtype_getsets_full;
2407 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2408 type->tp_getset = subtype_getsets_weakref_only;
2409 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2410 type->tp_getset = subtype_getsets_dict_only;
2411 else
2412 type->tp_getset = NULL;
2414 /* Special case some slots */
2415 if (type->tp_dictoffset != 0 || nslots > 0) {
2416 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2417 type->tp_getattro = PyObject_GenericGetAttr;
2418 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2419 type->tp_setattro = PyObject_GenericSetAttr;
2421 type->tp_dealloc = subtype_dealloc;
2423 /* Enable GC unless there are really no instance variables possible */
2424 if (!(type->tp_basicsize == sizeof(PyObject) &&
2425 type->tp_itemsize == 0))
2426 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2428 /* Always override allocation strategy to use regular heap */
2429 type->tp_alloc = PyType_GenericAlloc;
2430 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2431 type->tp_free = PyObject_GC_Del;
2432 type->tp_traverse = subtype_traverse;
2433 type->tp_clear = subtype_clear;
2435 else
2436 type->tp_free = PyObject_Del;
2438 /* Initialize the rest */
2439 if (PyType_Ready(type) < 0) {
2440 Py_DECREF(type);
2441 return NULL;
2444 /* Put the proper slots in place */
2445 fixup_slot_dispatchers(type);
2447 return (PyObject *)type;
2450 /* Internal API to look for a name through the MRO.
2451 This returns a borrowed reference, and doesn't set an exception! */
2452 PyObject *
2453 _PyType_Lookup(PyTypeObject *type, PyObject *name)
2455 Py_ssize_t i, n;
2456 PyObject *mro, *res, *base, *dict;
2457 unsigned int h;
2459 if (MCACHE_CACHEABLE_NAME(name) &&
2460 PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2461 /* fast path */
2462 h = MCACHE_HASH_METHOD(type, name);
2463 if (method_cache[h].version == type->tp_version_tag &&
2464 method_cache[h].name == name)
2465 return method_cache[h].value;
2468 /* Look in tp_dict of types in MRO */
2469 mro = type->tp_mro;
2471 /* If mro is NULL, the type is either not yet initialized
2472 by PyType_Ready(), or already cleared by type_clear().
2473 Either way the safest thing to do is to return NULL. */
2474 if (mro == NULL)
2475 return NULL;
2477 res = NULL;
2478 assert(PyTuple_Check(mro));
2479 n = PyTuple_GET_SIZE(mro);
2480 for (i = 0; i < n; i++) {
2481 base = PyTuple_GET_ITEM(mro, i);
2482 if (PyClass_Check(base))
2483 dict = ((PyClassObject *)base)->cl_dict;
2484 else {
2485 assert(PyType_Check(base));
2486 dict = ((PyTypeObject *)base)->tp_dict;
2488 assert(dict && PyDict_Check(dict));
2489 res = PyDict_GetItem(dict, name);
2490 if (res != NULL)
2491 break;
2494 if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2495 h = MCACHE_HASH_METHOD(type, name);
2496 method_cache[h].version = type->tp_version_tag;
2497 method_cache[h].value = res; /* borrowed */
2498 Py_INCREF(name);
2499 Py_DECREF(method_cache[h].name);
2500 method_cache[h].name = name;
2502 return res;
2505 /* This is similar to PyObject_GenericGetAttr(),
2506 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2507 static PyObject *
2508 type_getattro(PyTypeObject *type, PyObject *name)
2510 PyTypeObject *metatype = Py_TYPE(type);
2511 PyObject *meta_attribute, *attribute;
2512 descrgetfunc meta_get;
2514 /* Initialize this type (we'll assume the metatype is initialized) */
2515 if (type->tp_dict == NULL) {
2516 if (PyType_Ready(type) < 0)
2517 return NULL;
2520 /* No readable descriptor found yet */
2521 meta_get = NULL;
2523 /* Look for the attribute in the metatype */
2524 meta_attribute = _PyType_Lookup(metatype, name);
2526 if (meta_attribute != NULL) {
2527 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
2529 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2530 /* Data descriptors implement tp_descr_set to intercept
2531 * writes. Assume the attribute is not overridden in
2532 * type's tp_dict (and bases): call the descriptor now.
2534 return meta_get(meta_attribute, (PyObject *)type,
2535 (PyObject *)metatype);
2537 Py_INCREF(meta_attribute);
2540 /* No data descriptor found on metatype. Look in tp_dict of this
2541 * type and its bases */
2542 attribute = _PyType_Lookup(type, name);
2543 if (attribute != NULL) {
2544 /* Implement descriptor functionality, if any */
2545 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
2547 Py_XDECREF(meta_attribute);
2549 if (local_get != NULL) {
2550 /* NULL 2nd argument indicates the descriptor was
2551 * found on the target object itself (or a base) */
2552 return local_get(attribute, (PyObject *)NULL,
2553 (PyObject *)type);
2556 Py_INCREF(attribute);
2557 return attribute;
2560 /* No attribute found in local __dict__ (or bases): use the
2561 * descriptor from the metatype, if any */
2562 if (meta_get != NULL) {
2563 PyObject *res;
2564 res = meta_get(meta_attribute, (PyObject *)type,
2565 (PyObject *)metatype);
2566 Py_DECREF(meta_attribute);
2567 return res;
2570 /* If an ordinary attribute was found on the metatype, return it now */
2571 if (meta_attribute != NULL) {
2572 return meta_attribute;
2575 /* Give up */
2576 PyErr_Format(PyExc_AttributeError,
2577 "type object '%.50s' has no attribute '%.400s'",
2578 type->tp_name, PyString_AS_STRING(name));
2579 return NULL;
2582 static int
2583 type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2585 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2586 PyErr_Format(
2587 PyExc_TypeError,
2588 "can't set attributes of built-in/extension type '%s'",
2589 type->tp_name);
2590 return -1;
2592 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2593 return -1;
2594 return update_slot(type, name);
2597 static void
2598 type_dealloc(PyTypeObject *type)
2600 PyHeapTypeObject *et;
2602 /* Assert this is a heap-allocated type object */
2603 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2604 _PyObject_GC_UNTRACK(type);
2605 PyObject_ClearWeakRefs((PyObject *)type);
2606 et = (PyHeapTypeObject *)type;
2607 Py_XDECREF(type->tp_base);
2608 Py_XDECREF(type->tp_dict);
2609 Py_XDECREF(type->tp_bases);
2610 Py_XDECREF(type->tp_mro);
2611 Py_XDECREF(type->tp_cache);
2612 Py_XDECREF(type->tp_subclasses);
2613 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2614 * of most other objects. It's okay to cast it to char *.
2616 PyObject_Free((char *)type->tp_doc);
2617 Py_XDECREF(et->ht_name);
2618 Py_XDECREF(et->ht_slots);
2619 Py_TYPE(type)->tp_free((PyObject *)type);
2622 static PyObject *
2623 type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2625 PyObject *list, *raw, *ref;
2626 Py_ssize_t i, n;
2628 list = PyList_New(0);
2629 if (list == NULL)
2630 return NULL;
2631 raw = type->tp_subclasses;
2632 if (raw == NULL)
2633 return list;
2634 assert(PyList_Check(raw));
2635 n = PyList_GET_SIZE(raw);
2636 for (i = 0; i < n; i++) {
2637 ref = PyList_GET_ITEM(raw, i);
2638 assert(PyWeakref_CheckRef(ref));
2639 ref = PyWeakref_GET_OBJECT(ref);
2640 if (ref != Py_None) {
2641 if (PyList_Append(list, ref) < 0) {
2642 Py_DECREF(list);
2643 return NULL;
2647 return list;
2650 static PyMethodDef type_methods[] = {
2651 {"mro", (PyCFunction)mro_external, METH_NOARGS,
2652 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2653 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2654 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2655 {"__instancecheck__", type___instancecheck__, METH_O,
2656 PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
2657 {"__subclasscheck__", type___subclasscheck__, METH_O,
2658 PyDoc_STR("__subclasschck__ -> check if an class is a subclass")},
2662 PyDoc_STRVAR(type_doc,
2663 "type(object) -> the object's type\n"
2664 "type(name, bases, dict) -> a new type");
2666 static int
2667 type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2669 /* Because of type_is_gc(), the collector only calls this
2670 for heaptypes. */
2671 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2673 Py_VISIT(type->tp_dict);
2674 Py_VISIT(type->tp_cache);
2675 Py_VISIT(type->tp_mro);
2676 Py_VISIT(type->tp_bases);
2677 Py_VISIT(type->tp_base);
2679 /* There's no need to visit type->tp_subclasses or
2680 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
2681 in cycles; tp_subclasses is a list of weak references,
2682 and slots is a tuple of strings. */
2684 return 0;
2687 static int
2688 type_clear(PyTypeObject *type)
2690 /* Because of type_is_gc(), the collector only calls this
2691 for heaptypes. */
2692 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2694 /* The only field we need to clear is tp_mro, which is part of a
2695 hard cycle (its first element is the class itself) that won't
2696 be broken otherwise (it's a tuple and tuples don't have a
2697 tp_clear handler). None of the other fields need to be
2698 cleared, and here's why:
2700 tp_dict:
2701 It is a dict, so the collector will call its tp_clear.
2703 tp_cache:
2704 Not used; if it were, it would be a dict.
2706 tp_bases, tp_base:
2707 If these are involved in a cycle, there must be at least
2708 one other, mutable object in the cycle, e.g. a base
2709 class's dict; the cycle will be broken that way.
2711 tp_subclasses:
2712 A list of weak references can't be part of a cycle; and
2713 lists have their own tp_clear.
2715 slots (in PyHeapTypeObject):
2716 A tuple of strings can't be part of a cycle.
2719 Py_CLEAR(type->tp_mro);
2721 return 0;
2724 static int
2725 type_is_gc(PyTypeObject *type)
2727 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2730 PyTypeObject PyType_Type = {
2731 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2732 "type", /* tp_name */
2733 sizeof(PyHeapTypeObject), /* tp_basicsize */
2734 sizeof(PyMemberDef), /* tp_itemsize */
2735 (destructor)type_dealloc, /* tp_dealloc */
2736 0, /* tp_print */
2737 0, /* tp_getattr */
2738 0, /* tp_setattr */
2739 0, /* tp_compare */
2740 (reprfunc)type_repr, /* tp_repr */
2741 0, /* tp_as_number */
2742 0, /* tp_as_sequence */
2743 0, /* tp_as_mapping */
2744 (hashfunc)_Py_HashPointer, /* tp_hash */
2745 (ternaryfunc)type_call, /* tp_call */
2746 0, /* tp_str */
2747 (getattrofunc)type_getattro, /* tp_getattro */
2748 (setattrofunc)type_setattro, /* tp_setattro */
2749 0, /* tp_as_buffer */
2750 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2751 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
2752 type_doc, /* tp_doc */
2753 (traverseproc)type_traverse, /* tp_traverse */
2754 (inquiry)type_clear, /* tp_clear */
2755 type_richcompare, /* tp_richcompare */
2756 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
2757 0, /* tp_iter */
2758 0, /* tp_iternext */
2759 type_methods, /* tp_methods */
2760 type_members, /* tp_members */
2761 type_getsets, /* tp_getset */
2762 0, /* tp_base */
2763 0, /* tp_dict */
2764 0, /* tp_descr_get */
2765 0, /* tp_descr_set */
2766 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2767 type_init, /* tp_init */
2768 0, /* tp_alloc */
2769 type_new, /* tp_new */
2770 PyObject_GC_Del, /* tp_free */
2771 (inquiry)type_is_gc, /* tp_is_gc */
2775 /* The base type of all types (eventually)... except itself. */
2777 /* You may wonder why object.__new__() only complains about arguments
2778 when object.__init__() is not overridden, and vice versa.
2780 Consider the use cases:
2782 1. When neither is overridden, we want to hear complaints about
2783 excess (i.e., any) arguments, since their presence could
2784 indicate there's a bug.
2786 2. When defining an Immutable type, we are likely to override only
2787 __new__(), since __init__() is called too late to initialize an
2788 Immutable object. Since __new__() defines the signature for the
2789 type, it would be a pain to have to override __init__() just to
2790 stop it from complaining about excess arguments.
2792 3. When defining a Mutable type, we are likely to override only
2793 __init__(). So here the converse reasoning applies: we don't
2794 want to have to override __new__() just to stop it from
2795 complaining.
2797 4. When __init__() is overridden, and the subclass __init__() calls
2798 object.__init__(), the latter should complain about excess
2799 arguments; ditto for __new__().
2801 Use cases 2 and 3 make it unattractive to unconditionally check for
2802 excess arguments. The best solution that addresses all four use
2803 cases is as follows: __init__() complains about excess arguments
2804 unless __new__() is overridden and __init__() is not overridden
2805 (IOW, if __init__() is overridden or __new__() is not overridden);
2806 symmetrically, __new__() complains about excess arguments unless
2807 __init__() is overridden and __new__() is not overridden
2808 (IOW, if __new__() is overridden or __init__() is not overridden).
2810 However, for backwards compatibility, this breaks too much code.
2811 Therefore, in 2.6, we'll *warn* about excess arguments when both
2812 methods are overridden; for all other cases we'll use the above
2813 rules.
2817 /* Forward */
2818 static PyObject *
2819 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2821 static int
2822 excess_args(PyObject *args, PyObject *kwds)
2824 return PyTuple_GET_SIZE(args) ||
2825 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2828 static int
2829 object_init(PyObject *self, PyObject *args, PyObject *kwds)
2831 int err = 0;
2832 if (excess_args(args, kwds)) {
2833 PyTypeObject *type = Py_TYPE(self);
2834 if (type->tp_init != object_init &&
2835 type->tp_new != object_new)
2837 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2838 "object.__init__() takes no parameters",
2841 else if (type->tp_init != object_init ||
2842 type->tp_new == object_new)
2844 PyErr_SetString(PyExc_TypeError,
2845 "object.__init__() takes no parameters");
2846 err = -1;
2849 return err;
2852 static PyObject *
2853 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2855 int err = 0;
2856 if (excess_args(args, kwds)) {
2857 if (type->tp_new != object_new &&
2858 type->tp_init != object_init)
2860 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2861 "object.__new__() takes no parameters",
2864 else if (type->tp_new != object_new ||
2865 type->tp_init == object_init)
2867 PyErr_SetString(PyExc_TypeError,
2868 "object.__new__() takes no parameters");
2869 err = -1;
2872 if (err < 0)
2873 return NULL;
2875 if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
2876 static PyObject *comma = NULL;
2877 PyObject *abstract_methods = NULL;
2878 PyObject *builtins;
2879 PyObject *sorted;
2880 PyObject *sorted_methods = NULL;
2881 PyObject *joined = NULL;
2882 const char *joined_str;
2884 /* Compute ", ".join(sorted(type.__abstractmethods__))
2885 into joined. */
2886 abstract_methods = type_abstractmethods(type, NULL);
2887 if (abstract_methods == NULL)
2888 goto error;
2889 builtins = PyEval_GetBuiltins();
2890 if (builtins == NULL)
2891 goto error;
2892 sorted = PyDict_GetItemString(builtins, "sorted");
2893 if (sorted == NULL)
2894 goto error;
2895 sorted_methods = PyObject_CallFunctionObjArgs(sorted,
2896 abstract_methods,
2897 NULL);
2898 if (sorted_methods == NULL)
2899 goto error;
2900 if (comma == NULL) {
2901 comma = PyString_InternFromString(", ");
2902 if (comma == NULL)
2903 goto error;
2905 joined = PyObject_CallMethod(comma, "join",
2906 "O", sorted_methods);
2907 if (joined == NULL)
2908 goto error;
2909 joined_str = PyString_AsString(joined);
2910 if (joined_str == NULL)
2911 goto error;
2913 PyErr_Format(PyExc_TypeError,
2914 "Can't instantiate abstract class %s "
2915 "with abstract methods %s",
2916 type->tp_name,
2917 joined_str);
2918 error:
2919 Py_XDECREF(joined);
2920 Py_XDECREF(sorted_methods);
2921 Py_XDECREF(abstract_methods);
2922 return NULL;
2924 return type->tp_alloc(type, 0);
2927 static void
2928 object_dealloc(PyObject *self)
2930 Py_TYPE(self)->tp_free(self);
2933 static PyObject *
2934 object_repr(PyObject *self)
2936 PyTypeObject *type;
2937 PyObject *mod, *name, *rtn;
2939 type = Py_TYPE(self);
2940 mod = type_module(type, NULL);
2941 if (mod == NULL)
2942 PyErr_Clear();
2943 else if (!PyString_Check(mod)) {
2944 Py_DECREF(mod);
2945 mod = NULL;
2947 name = type_name(type, NULL);
2948 if (name == NULL)
2949 return NULL;
2950 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
2951 rtn = PyString_FromFormat("<%s.%s object at %p>",
2952 PyString_AS_STRING(mod),
2953 PyString_AS_STRING(name),
2954 self);
2955 else
2956 rtn = PyString_FromFormat("<%s object at %p>",
2957 type->tp_name, self);
2958 Py_XDECREF(mod);
2959 Py_DECREF(name);
2960 return rtn;
2963 static PyObject *
2964 object_str(PyObject *self)
2966 unaryfunc f;
2968 f = Py_TYPE(self)->tp_repr;
2969 if (f == NULL)
2970 f = object_repr;
2971 return f(self);
2974 static PyObject *
2975 object_get_class(PyObject *self, void *closure)
2977 Py_INCREF(Py_TYPE(self));
2978 return (PyObject *)(Py_TYPE(self));
2981 static int
2982 equiv_structs(PyTypeObject *a, PyTypeObject *b)
2984 return a == b ||
2985 (a != NULL &&
2986 b != NULL &&
2987 a->tp_basicsize == b->tp_basicsize &&
2988 a->tp_itemsize == b->tp_itemsize &&
2989 a->tp_dictoffset == b->tp_dictoffset &&
2990 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2991 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2992 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2995 static int
2996 same_slots_added(PyTypeObject *a, PyTypeObject *b)
2998 PyTypeObject *base = a->tp_base;
2999 Py_ssize_t size;
3000 PyObject *slots_a, *slots_b;
3002 if (base != b->tp_base)
3003 return 0;
3004 if (equiv_structs(a, base) && equiv_structs(b, base))
3005 return 1;
3006 size = base->tp_basicsize;
3007 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3008 size += sizeof(PyObject *);
3009 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3010 size += sizeof(PyObject *);
3012 /* Check slots compliance */
3013 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3014 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3015 if (slots_a && slots_b) {
3016 if (PyObject_Compare(slots_a, slots_b) != 0)
3017 return 0;
3018 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3020 return size == a->tp_basicsize && size == b->tp_basicsize;
3023 static int
3024 compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
3026 PyTypeObject *newbase, *oldbase;
3028 if (newto->tp_dealloc != oldto->tp_dealloc ||
3029 newto->tp_free != oldto->tp_free)
3031 PyErr_Format(PyExc_TypeError,
3032 "%s assignment: "
3033 "'%s' deallocator differs from '%s'",
3034 attr,
3035 newto->tp_name,
3036 oldto->tp_name);
3037 return 0;
3039 newbase = newto;
3040 oldbase = oldto;
3041 while (equiv_structs(newbase, newbase->tp_base))
3042 newbase = newbase->tp_base;
3043 while (equiv_structs(oldbase, oldbase->tp_base))
3044 oldbase = oldbase->tp_base;
3045 if (newbase != oldbase &&
3046 (newbase->tp_base != oldbase->tp_base ||
3047 !same_slots_added(newbase, oldbase))) {
3048 PyErr_Format(PyExc_TypeError,
3049 "%s assignment: "
3050 "'%s' object layout differs from '%s'",
3051 attr,
3052 newto->tp_name,
3053 oldto->tp_name);
3054 return 0;
3057 return 1;
3060 static int
3061 object_set_class(PyObject *self, PyObject *value, void *closure)
3063 PyTypeObject *oldto = Py_TYPE(self);
3064 PyTypeObject *newto;
3066 if (value == NULL) {
3067 PyErr_SetString(PyExc_TypeError,
3068 "can't delete __class__ attribute");
3069 return -1;
3071 if (!PyType_Check(value)) {
3072 PyErr_Format(PyExc_TypeError,
3073 "__class__ must be set to new-style class, not '%s' object",
3074 Py_TYPE(value)->tp_name);
3075 return -1;
3077 newto = (PyTypeObject *)value;
3078 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3079 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
3081 PyErr_Format(PyExc_TypeError,
3082 "__class__ assignment: only for heap types");
3083 return -1;
3085 if (compatible_for_assignment(newto, oldto, "__class__")) {
3086 Py_INCREF(newto);
3087 Py_TYPE(self) = newto;
3088 Py_DECREF(oldto);
3089 return 0;
3091 else {
3092 return -1;
3096 static PyGetSetDef object_getsets[] = {
3097 {"__class__", object_get_class, object_set_class,
3098 PyDoc_STR("the object's class")},
3103 /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
3104 We fall back to helpers in copy_reg for:
3105 - pickle protocols < 2
3106 - calculating the list of slot names (done only once per class)
3107 - the __newobj__ function (which is used as a token but never called)
3110 static PyObject *
3111 import_copyreg(void)
3113 static PyObject *copyreg_str;
3115 if (!copyreg_str) {
3116 copyreg_str = PyString_InternFromString("copy_reg");
3117 if (copyreg_str == NULL)
3118 return NULL;
3121 return PyImport_Import(copyreg_str);
3124 static PyObject *
3125 slotnames(PyObject *cls)
3127 PyObject *clsdict;
3128 PyObject *copyreg;
3129 PyObject *slotnames;
3131 if (!PyType_Check(cls)) {
3132 Py_INCREF(Py_None);
3133 return Py_None;
3136 clsdict = ((PyTypeObject *)cls)->tp_dict;
3137 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
3138 if (slotnames != NULL && PyList_Check(slotnames)) {
3139 Py_INCREF(slotnames);
3140 return slotnames;
3143 copyreg = import_copyreg();
3144 if (copyreg == NULL)
3145 return NULL;
3147 slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
3148 Py_DECREF(copyreg);
3149 if (slotnames != NULL &&
3150 slotnames != Py_None &&
3151 !PyList_Check(slotnames))
3153 PyErr_SetString(PyExc_TypeError,
3154 "copy_reg._slotnames didn't return a list or None");
3155 Py_DECREF(slotnames);
3156 slotnames = NULL;
3159 return slotnames;
3162 static PyObject *
3163 reduce_2(PyObject *obj)
3165 PyObject *cls, *getnewargs;
3166 PyObject *args = NULL, *args2 = NULL;
3167 PyObject *getstate = NULL, *state = NULL, *names = NULL;
3168 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
3169 PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
3170 Py_ssize_t i, n;
3172 cls = PyObject_GetAttrString(obj, "__class__");
3173 if (cls == NULL)
3174 return NULL;
3176 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
3177 if (getnewargs != NULL) {
3178 args = PyObject_CallObject(getnewargs, NULL);
3179 Py_DECREF(getnewargs);
3180 if (args != NULL && !PyTuple_Check(args)) {
3181 PyErr_Format(PyExc_TypeError,
3182 "__getnewargs__ should return a tuple, "
3183 "not '%.200s'", Py_TYPE(args)->tp_name);
3184 goto end;
3187 else {
3188 PyErr_Clear();
3189 args = PyTuple_New(0);
3191 if (args == NULL)
3192 goto end;
3194 getstate = PyObject_GetAttrString(obj, "__getstate__");
3195 if (getstate != NULL) {
3196 state = PyObject_CallObject(getstate, NULL);
3197 Py_DECREF(getstate);
3198 if (state == NULL)
3199 goto end;
3201 else {
3202 PyErr_Clear();
3203 state = PyObject_GetAttrString(obj, "__dict__");
3204 if (state == NULL) {
3205 PyErr_Clear();
3206 state = Py_None;
3207 Py_INCREF(state);
3209 names = slotnames(cls);
3210 if (names == NULL)
3211 goto end;
3212 if (names != Py_None) {
3213 assert(PyList_Check(names));
3214 slots = PyDict_New();
3215 if (slots == NULL)
3216 goto end;
3217 n = 0;
3218 /* Can't pre-compute the list size; the list
3219 is stored on the class so accessible to other
3220 threads, which may be run by DECREF */
3221 for (i = 0; i < PyList_GET_SIZE(names); i++) {
3222 PyObject *name, *value;
3223 name = PyList_GET_ITEM(names, i);
3224 value = PyObject_GetAttr(obj, name);
3225 if (value == NULL)
3226 PyErr_Clear();
3227 else {
3228 int err = PyDict_SetItem(slots, name,
3229 value);
3230 Py_DECREF(value);
3231 if (err)
3232 goto end;
3233 n++;
3236 if (n) {
3237 state = Py_BuildValue("(NO)", state, slots);
3238 if (state == NULL)
3239 goto end;
3244 if (!PyList_Check(obj)) {
3245 listitems = Py_None;
3246 Py_INCREF(listitems);
3248 else {
3249 listitems = PyObject_GetIter(obj);
3250 if (listitems == NULL)
3251 goto end;
3254 if (!PyDict_Check(obj)) {
3255 dictitems = Py_None;
3256 Py_INCREF(dictitems);
3258 else {
3259 dictitems = PyObject_CallMethod(obj, "iteritems", "");
3260 if (dictitems == NULL)
3261 goto end;
3264 copyreg = import_copyreg();
3265 if (copyreg == NULL)
3266 goto end;
3267 newobj = PyObject_GetAttrString(copyreg, "__newobj__");
3268 if (newobj == NULL)
3269 goto end;
3271 n = PyTuple_GET_SIZE(args);
3272 args2 = PyTuple_New(n+1);
3273 if (args2 == NULL)
3274 goto end;
3275 PyTuple_SET_ITEM(args2, 0, cls);
3276 cls = NULL;
3277 for (i = 0; i < n; i++) {
3278 PyObject *v = PyTuple_GET_ITEM(args, i);
3279 Py_INCREF(v);
3280 PyTuple_SET_ITEM(args2, i+1, v);
3283 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
3285 end:
3286 Py_XDECREF(cls);
3287 Py_XDECREF(args);
3288 Py_XDECREF(args2);
3289 Py_XDECREF(slots);
3290 Py_XDECREF(state);
3291 Py_XDECREF(names);
3292 Py_XDECREF(listitems);
3293 Py_XDECREF(dictitems);
3294 Py_XDECREF(copyreg);
3295 Py_XDECREF(newobj);
3296 return res;
3300 * There were two problems when object.__reduce__ and object.__reduce_ex__
3301 * were implemented in the same function:
3302 * - trying to pickle an object with a custom __reduce__ method that
3303 * fell back to object.__reduce__ in certain circumstances led to
3304 * infinite recursion at Python level and eventual RuntimeError.
3305 * - Pickling objects that lied about their type by overwriting the
3306 * __class__ descriptor could lead to infinite recursion at C level
3307 * and eventual segfault.
3309 * Because of backwards compatibility, the two methods still have to
3310 * behave in the same way, even if this is not required by the pickle
3311 * protocol. This common functionality was moved to the _common_reduce
3312 * function.
3314 static PyObject *
3315 _common_reduce(PyObject *self, int proto)
3317 PyObject *copyreg, *res;
3319 if (proto >= 2)
3320 return reduce_2(self);
3322 copyreg = import_copyreg();
3323 if (!copyreg)
3324 return NULL;
3326 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
3327 Py_DECREF(copyreg);
3329 return res;
3332 static PyObject *
3333 object_reduce(PyObject *self, PyObject *args)
3335 int proto = 0;
3337 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
3338 return NULL;
3340 return _common_reduce(self, proto);
3343 static PyObject *
3344 object_reduce_ex(PyObject *self, PyObject *args)
3346 PyObject *reduce, *res;
3347 int proto = 0;
3349 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3350 return NULL;
3352 reduce = PyObject_GetAttrString(self, "__reduce__");
3353 if (reduce == NULL)
3354 PyErr_Clear();
3355 else {
3356 PyObject *cls, *clsreduce, *objreduce;
3357 int override;
3358 cls = PyObject_GetAttrString(self, "__class__");
3359 if (cls == NULL) {
3360 Py_DECREF(reduce);
3361 return NULL;
3363 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
3364 Py_DECREF(cls);
3365 if (clsreduce == NULL) {
3366 Py_DECREF(reduce);
3367 return NULL;
3369 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
3370 "__reduce__");
3371 override = (clsreduce != objreduce);
3372 Py_DECREF(clsreduce);
3373 if (override) {
3374 res = PyObject_CallObject(reduce, NULL);
3375 Py_DECREF(reduce);
3376 return res;
3378 else
3379 Py_DECREF(reduce);
3382 return _common_reduce(self, proto);
3385 static PyObject *
3386 object_subclasshook(PyObject *cls, PyObject *args)
3388 Py_INCREF(Py_NotImplemented);
3389 return Py_NotImplemented;
3392 PyDoc_STRVAR(object_subclasshook_doc,
3393 "Abstract classes can override this to customize issubclass().\n"
3394 "\n"
3395 "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
3396 "It should return True, False or NotImplemented. If it returns\n"
3397 "NotImplemented, the normal algorithm is used. Otherwise, it\n"
3398 "overrides the normal algorithm (and the outcome is cached).\n");
3401 from PEP 3101, this code implements:
3403 class object:
3404 def __format__(self, format_spec):
3405 if isinstance(format_spec, str):
3406 return format(str(self), format_spec)
3407 elif isinstance(format_spec, unicode):
3408 return format(unicode(self), format_spec)
3410 static PyObject *
3411 object_format(PyObject *self, PyObject *args)
3413 PyObject *format_spec;
3414 PyObject *self_as_str = NULL;
3415 PyObject *result = NULL;
3416 PyObject *format_meth = NULL;
3418 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3419 return NULL;
3420 #ifdef Py_USING_UNICODE
3421 if (PyUnicode_Check(format_spec)) {
3422 self_as_str = PyObject_Unicode(self);
3423 } else if (PyString_Check(format_spec)) {
3424 #else
3425 if (PyString_Check(format_spec)) {
3426 #endif
3427 self_as_str = PyObject_Str(self);
3428 } else {
3429 PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
3430 return NULL;
3433 if (self_as_str != NULL) {
3434 /* find the format function */
3435 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
3436 if (format_meth != NULL) {
3437 /* and call it */
3438 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
3442 Py_XDECREF(self_as_str);
3443 Py_XDECREF(format_meth);
3445 return result;
3448 static PyObject *
3449 object_sizeof(PyObject *self, PyObject *args)
3451 Py_ssize_t res, isize;
3453 res = 0;
3454 isize = self->ob_type->tp_itemsize;
3455 if (isize > 0)
3456 res = self->ob_type->ob_size * isize;
3457 res += self->ob_type->tp_basicsize;
3459 return PyInt_FromSsize_t(res);
3462 static PyMethodDef object_methods[] = {
3463 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3464 PyDoc_STR("helper for pickle")},
3465 {"__reduce__", object_reduce, METH_VARARGS,
3466 PyDoc_STR("helper for pickle")},
3467 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
3468 object_subclasshook_doc},
3469 {"__format__", object_format, METH_VARARGS,
3470 PyDoc_STR("default object formatter")},
3471 {"__sizeof__", object_sizeof, METH_NOARGS,
3472 PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
3477 PyTypeObject PyBaseObject_Type = {
3478 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3479 "object", /* tp_name */
3480 sizeof(PyObject), /* tp_basicsize */
3481 0, /* tp_itemsize */
3482 object_dealloc, /* tp_dealloc */
3483 0, /* tp_print */
3484 0, /* tp_getattr */
3485 0, /* tp_setattr */
3486 0, /* tp_compare */
3487 object_repr, /* tp_repr */
3488 0, /* tp_as_number */
3489 0, /* tp_as_sequence */
3490 0, /* tp_as_mapping */
3491 (hashfunc)_Py_HashPointer, /* tp_hash */
3492 0, /* tp_call */
3493 object_str, /* tp_str */
3494 PyObject_GenericGetAttr, /* tp_getattro */
3495 PyObject_GenericSetAttr, /* tp_setattro */
3496 0, /* tp_as_buffer */
3497 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3498 PyDoc_STR("The most base type"), /* tp_doc */
3499 0, /* tp_traverse */
3500 0, /* tp_clear */
3501 0, /* tp_richcompare */
3502 0, /* tp_weaklistoffset */
3503 0, /* tp_iter */
3504 0, /* tp_iternext */
3505 object_methods, /* tp_methods */
3506 0, /* tp_members */
3507 object_getsets, /* tp_getset */
3508 0, /* tp_base */
3509 0, /* tp_dict */
3510 0, /* tp_descr_get */
3511 0, /* tp_descr_set */
3512 0, /* tp_dictoffset */
3513 object_init, /* tp_init */
3514 PyType_GenericAlloc, /* tp_alloc */
3515 object_new, /* tp_new */
3516 PyObject_Del, /* tp_free */
3520 /* Initialize the __dict__ in a type object */
3522 static int
3523 add_methods(PyTypeObject *type, PyMethodDef *meth)
3525 PyObject *dict = type->tp_dict;
3527 for (; meth->ml_name != NULL; meth++) {
3528 PyObject *descr;
3529 if (PyDict_GetItemString(dict, meth->ml_name) &&
3530 !(meth->ml_flags & METH_COEXIST))
3531 continue;
3532 if (meth->ml_flags & METH_CLASS) {
3533 if (meth->ml_flags & METH_STATIC) {
3534 PyErr_SetString(PyExc_ValueError,
3535 "method cannot be both class and static");
3536 return -1;
3538 descr = PyDescr_NewClassMethod(type, meth);
3540 else if (meth->ml_flags & METH_STATIC) {
3541 PyObject *cfunc = PyCFunction_New(meth, NULL);
3542 if (cfunc == NULL)
3543 return -1;
3544 descr = PyStaticMethod_New(cfunc);
3545 Py_DECREF(cfunc);
3547 else {
3548 descr = PyDescr_NewMethod(type, meth);
3550 if (descr == NULL)
3551 return -1;
3552 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
3553 return -1;
3554 Py_DECREF(descr);
3556 return 0;
3559 static int
3560 add_members(PyTypeObject *type, PyMemberDef *memb)
3562 PyObject *dict = type->tp_dict;
3564 for (; memb->name != NULL; memb++) {
3565 PyObject *descr;
3566 if (PyDict_GetItemString(dict, memb->name))
3567 continue;
3568 descr = PyDescr_NewMember(type, memb);
3569 if (descr == NULL)
3570 return -1;
3571 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3572 return -1;
3573 Py_DECREF(descr);
3575 return 0;
3578 static int
3579 add_getset(PyTypeObject *type, PyGetSetDef *gsp)
3581 PyObject *dict = type->tp_dict;
3583 for (; gsp->name != NULL; gsp++) {
3584 PyObject *descr;
3585 if (PyDict_GetItemString(dict, gsp->name))
3586 continue;
3587 descr = PyDescr_NewGetSet(type, gsp);
3589 if (descr == NULL)
3590 return -1;
3591 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3592 return -1;
3593 Py_DECREF(descr);
3595 return 0;
3598 #define BUFFER_FLAGS (Py_TPFLAGS_HAVE_GETCHARBUFFER | Py_TPFLAGS_HAVE_NEWBUFFER)
3600 static void
3601 inherit_special(PyTypeObject *type, PyTypeObject *base)
3603 Py_ssize_t oldsize, newsize;
3605 /* Special flag magic */
3606 if (!type->tp_as_buffer && base->tp_as_buffer) {
3607 type->tp_flags &= ~BUFFER_FLAGS;
3608 type->tp_flags |=
3609 base->tp_flags & BUFFER_FLAGS;
3611 if (!type->tp_as_sequence && base->tp_as_sequence) {
3612 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3613 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3615 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3616 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3617 if ((!type->tp_as_number && base->tp_as_number) ||
3618 (!type->tp_as_sequence && base->tp_as_sequence)) {
3619 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3620 if (!type->tp_as_number && !type->tp_as_sequence) {
3621 type->tp_flags |= base->tp_flags &
3622 Py_TPFLAGS_HAVE_INPLACEOPS;
3625 /* Wow */
3627 if (!type->tp_as_number && base->tp_as_number) {
3628 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3629 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3632 /* Copying basicsize is connected to the GC flags */
3633 oldsize = base->tp_basicsize;
3634 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3635 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3636 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3637 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3638 (!type->tp_traverse && !type->tp_clear)) {
3639 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
3640 if (type->tp_traverse == NULL)
3641 type->tp_traverse = base->tp_traverse;
3642 if (type->tp_clear == NULL)
3643 type->tp_clear = base->tp_clear;
3645 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3646 /* The condition below could use some explanation.
3647 It appears that tp_new is not inherited for static types
3648 whose base class is 'object'; this seems to be a precaution
3649 so that old extension types don't suddenly become
3650 callable (object.__new__ wouldn't insure the invariants
3651 that the extension type's own factory function ensures).
3652 Heap types, of course, are under our control, so they do
3653 inherit tp_new; static extension types that specify some
3654 other built-in type as the default are considered
3655 new-style-aware so they also inherit object.__new__. */
3656 if (base != &PyBaseObject_Type ||
3657 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3658 if (type->tp_new == NULL)
3659 type->tp_new = base->tp_new;
3662 type->tp_basicsize = newsize;
3664 /* Copy other non-function slots */
3666 #undef COPYVAL
3667 #define COPYVAL(SLOT) \
3668 if (type->SLOT == 0) type->SLOT = base->SLOT
3670 COPYVAL(tp_itemsize);
3671 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3672 COPYVAL(tp_weaklistoffset);
3674 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3675 COPYVAL(tp_dictoffset);
3678 /* Setup fast subclass flags */
3679 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3680 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3681 else if (PyType_IsSubtype(base, &PyType_Type))
3682 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3683 else if (PyType_IsSubtype(base, &PyInt_Type))
3684 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3685 else if (PyType_IsSubtype(base, &PyLong_Type))
3686 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3687 else if (PyType_IsSubtype(base, &PyString_Type))
3688 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3689 #ifdef Py_USING_UNICODE
3690 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3691 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3692 #endif
3693 else if (PyType_IsSubtype(base, &PyTuple_Type))
3694 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3695 else if (PyType_IsSubtype(base, &PyList_Type))
3696 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3697 else if (PyType_IsSubtype(base, &PyDict_Type))
3698 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
3701 static int
3702 overrides_name(PyTypeObject *type, char *name)
3704 PyObject *dict = type->tp_dict;
3706 assert(dict != NULL);
3707 if (PyDict_GetItemString(dict, name) != NULL) {
3708 return 1;
3710 return 0;
3713 #define OVERRIDES_HASH(x) overrides_name(x, "__hash__")
3714 #define OVERRIDES_CMP(x) overrides_name(x, "__cmp__")
3715 #define OVERRIDES_EQ(x) overrides_name(x, "__eq__")
3717 static void
3718 inherit_slots(PyTypeObject *type, PyTypeObject *base)
3720 PyTypeObject *basebase;
3722 #undef SLOTDEFINED
3723 #undef COPYSLOT
3724 #undef COPYNUM
3725 #undef COPYSEQ
3726 #undef COPYMAP
3727 #undef COPYBUF
3729 #define SLOTDEFINED(SLOT) \
3730 (base->SLOT != 0 && \
3731 (basebase == NULL || base->SLOT != basebase->SLOT))
3733 #define COPYSLOT(SLOT) \
3734 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
3736 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3737 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3738 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
3739 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
3741 /* This won't inherit indirect slots (from tp_as_number etc.)
3742 if type doesn't provide the space. */
3744 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3745 basebase = base->tp_base;
3746 if (basebase->tp_as_number == NULL)
3747 basebase = NULL;
3748 COPYNUM(nb_add);
3749 COPYNUM(nb_subtract);
3750 COPYNUM(nb_multiply);
3751 COPYNUM(nb_divide);
3752 COPYNUM(nb_remainder);
3753 COPYNUM(nb_divmod);
3754 COPYNUM(nb_power);
3755 COPYNUM(nb_negative);
3756 COPYNUM(nb_positive);
3757 COPYNUM(nb_absolute);
3758 COPYNUM(nb_nonzero);
3759 COPYNUM(nb_invert);
3760 COPYNUM(nb_lshift);
3761 COPYNUM(nb_rshift);
3762 COPYNUM(nb_and);
3763 COPYNUM(nb_xor);
3764 COPYNUM(nb_or);
3765 COPYNUM(nb_coerce);
3766 COPYNUM(nb_int);
3767 COPYNUM(nb_long);
3768 COPYNUM(nb_float);
3769 COPYNUM(nb_oct);
3770 COPYNUM(nb_hex);
3771 COPYNUM(nb_inplace_add);
3772 COPYNUM(nb_inplace_subtract);
3773 COPYNUM(nb_inplace_multiply);
3774 COPYNUM(nb_inplace_divide);
3775 COPYNUM(nb_inplace_remainder);
3776 COPYNUM(nb_inplace_power);
3777 COPYNUM(nb_inplace_lshift);
3778 COPYNUM(nb_inplace_rshift);
3779 COPYNUM(nb_inplace_and);
3780 COPYNUM(nb_inplace_xor);
3781 COPYNUM(nb_inplace_or);
3782 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3783 COPYNUM(nb_true_divide);
3784 COPYNUM(nb_floor_divide);
3785 COPYNUM(nb_inplace_true_divide);
3786 COPYNUM(nb_inplace_floor_divide);
3788 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3789 COPYNUM(nb_index);
3793 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3794 basebase = base->tp_base;
3795 if (basebase->tp_as_sequence == NULL)
3796 basebase = NULL;
3797 COPYSEQ(sq_length);
3798 COPYSEQ(sq_concat);
3799 COPYSEQ(sq_repeat);
3800 COPYSEQ(sq_item);
3801 COPYSEQ(sq_slice);
3802 COPYSEQ(sq_ass_item);
3803 COPYSEQ(sq_ass_slice);
3804 COPYSEQ(sq_contains);
3805 COPYSEQ(sq_inplace_concat);
3806 COPYSEQ(sq_inplace_repeat);
3809 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3810 basebase = base->tp_base;
3811 if (basebase->tp_as_mapping == NULL)
3812 basebase = NULL;
3813 COPYMAP(mp_length);
3814 COPYMAP(mp_subscript);
3815 COPYMAP(mp_ass_subscript);
3818 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3819 basebase = base->tp_base;
3820 if (basebase->tp_as_buffer == NULL)
3821 basebase = NULL;
3822 COPYBUF(bf_getreadbuffer);
3823 COPYBUF(bf_getwritebuffer);
3824 COPYBUF(bf_getsegcount);
3825 COPYBUF(bf_getcharbuffer);
3826 COPYBUF(bf_getbuffer);
3827 COPYBUF(bf_releasebuffer);
3830 basebase = base->tp_base;
3832 COPYSLOT(tp_dealloc);
3833 COPYSLOT(tp_print);
3834 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3835 type->tp_getattr = base->tp_getattr;
3836 type->tp_getattro = base->tp_getattro;
3838 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3839 type->tp_setattr = base->tp_setattr;
3840 type->tp_setattro = base->tp_setattro;
3842 /* tp_compare see tp_richcompare */
3843 COPYSLOT(tp_repr);
3844 /* tp_hash see tp_richcompare */
3845 COPYSLOT(tp_call);
3846 COPYSLOT(tp_str);
3847 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
3848 if (type->tp_compare == NULL &&
3849 type->tp_richcompare == NULL &&
3850 type->tp_hash == NULL)
3852 type->tp_compare = base->tp_compare;
3853 type->tp_richcompare = base->tp_richcompare;
3854 type->tp_hash = base->tp_hash;
3855 /* Check for changes to inherited methods in Py3k*/
3856 if (Py_Py3kWarningFlag) {
3857 if (base->tp_hash &&
3858 (base->tp_hash != PyObject_HashNotImplemented) &&
3859 !OVERRIDES_HASH(type)) {
3860 if (OVERRIDES_CMP(type)) {
3861 PyErr_WarnPy3k("Overriding "
3862 "__cmp__ blocks inheritance "
3863 "of __hash__ in 3.x",
3866 if (OVERRIDES_EQ(type)) {
3867 PyErr_WarnPy3k("Overriding "
3868 "__eq__ blocks inheritance "
3869 "of __hash__ in 3.x",
3876 else {
3877 COPYSLOT(tp_compare);
3879 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3880 COPYSLOT(tp_iter);
3881 COPYSLOT(tp_iternext);
3883 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3884 COPYSLOT(tp_descr_get);
3885 COPYSLOT(tp_descr_set);
3886 COPYSLOT(tp_dictoffset);
3887 COPYSLOT(tp_init);
3888 COPYSLOT(tp_alloc);
3889 COPYSLOT(tp_is_gc);
3890 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3891 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3892 /* They agree about gc. */
3893 COPYSLOT(tp_free);
3895 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3896 type->tp_free == NULL &&
3897 base->tp_free == _PyObject_Del) {
3898 /* A bit of magic to plug in the correct default
3899 * tp_free function when a derived class adds gc,
3900 * didn't define tp_free, and the base uses the
3901 * default non-gc tp_free.
3903 type->tp_free = PyObject_GC_Del;
3905 /* else they didn't agree about gc, and there isn't something
3906 * obvious to be done -- the type is on its own.
3911 static int add_operators(PyTypeObject *);
3914 PyType_Ready(PyTypeObject *type)
3916 PyObject *dict, *bases;
3917 PyTypeObject *base;
3918 Py_ssize_t i, n;
3920 if (type->tp_flags & Py_TPFLAGS_READY) {
3921 assert(type->tp_dict != NULL);
3922 return 0;
3924 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
3926 type->tp_flags |= Py_TPFLAGS_READYING;
3928 #ifdef Py_TRACE_REFS
3929 /* PyType_Ready is the closest thing we have to a choke point
3930 * for type objects, so is the best place I can think of to try
3931 * to get type objects into the doubly-linked list of all objects.
3932 * Still, not all type objects go thru PyType_Ready.
3934 _Py_AddToAllObjects((PyObject *)type, 0);
3935 #endif
3937 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3938 base = type->tp_base;
3939 if (base == NULL && type != &PyBaseObject_Type) {
3940 base = type->tp_base = &PyBaseObject_Type;
3941 Py_INCREF(base);
3944 /* Now the only way base can still be NULL is if type is
3945 * &PyBaseObject_Type.
3948 /* Initialize the base class */
3949 if (base && base->tp_dict == NULL) {
3950 if (PyType_Ready(base) < 0)
3951 goto error;
3954 /* Initialize ob_type if NULL. This means extensions that want to be
3955 compilable separately on Windows can call PyType_Ready() instead of
3956 initializing the ob_type field of their type objects. */
3957 /* The test for base != NULL is really unnecessary, since base is only
3958 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3959 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3960 know that. */
3961 if (Py_TYPE(type) == NULL && base != NULL)
3962 Py_TYPE(type) = Py_TYPE(base);
3964 /* Initialize tp_bases */
3965 bases = type->tp_bases;
3966 if (bases == NULL) {
3967 if (base == NULL)
3968 bases = PyTuple_New(0);
3969 else
3970 bases = PyTuple_Pack(1, base);
3971 if (bases == NULL)
3972 goto error;
3973 type->tp_bases = bases;
3976 /* Initialize tp_dict */
3977 dict = type->tp_dict;
3978 if (dict == NULL) {
3979 dict = PyDict_New();
3980 if (dict == NULL)
3981 goto error;
3982 type->tp_dict = dict;
3985 /* Add type-specific descriptors to tp_dict */
3986 if (add_operators(type) < 0)
3987 goto error;
3988 if (type->tp_methods != NULL) {
3989 if (add_methods(type, type->tp_methods) < 0)
3990 goto error;
3992 if (type->tp_members != NULL) {
3993 if (add_members(type, type->tp_members) < 0)
3994 goto error;
3996 if (type->tp_getset != NULL) {
3997 if (add_getset(type, type->tp_getset) < 0)
3998 goto error;
4001 /* Calculate method resolution order */
4002 if (mro_internal(type) < 0) {
4003 goto error;
4006 /* Inherit special flags from dominant base */
4007 if (type->tp_base != NULL)
4008 inherit_special(type, type->tp_base);
4010 /* Initialize tp_dict properly */
4011 bases = type->tp_mro;
4012 assert(bases != NULL);
4013 assert(PyTuple_Check(bases));
4014 n = PyTuple_GET_SIZE(bases);
4015 for (i = 1; i < n; i++) {
4016 PyObject *b = PyTuple_GET_ITEM(bases, i);
4017 if (PyType_Check(b))
4018 inherit_slots(type, (PyTypeObject *)b);
4021 /* Sanity check for tp_free. */
4022 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
4023 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
4024 /* This base class needs to call tp_free, but doesn't have
4025 * one, or its tp_free is for non-gc'ed objects.
4027 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
4028 "gc and is a base type but has inappropriate "
4029 "tp_free slot",
4030 type->tp_name);
4031 goto error;
4034 /* if the type dictionary doesn't contain a __doc__, set it from
4035 the tp_doc slot.
4037 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
4038 if (type->tp_doc != NULL) {
4039 PyObject *doc = PyString_FromString(type->tp_doc);
4040 if (doc == NULL)
4041 goto error;
4042 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
4043 Py_DECREF(doc);
4044 } else {
4045 PyDict_SetItemString(type->tp_dict,
4046 "__doc__", Py_None);
4050 /* Some more special stuff */
4051 base = type->tp_base;
4052 if (base != NULL) {
4053 if (type->tp_as_number == NULL)
4054 type->tp_as_number = base->tp_as_number;
4055 if (type->tp_as_sequence == NULL)
4056 type->tp_as_sequence = base->tp_as_sequence;
4057 if (type->tp_as_mapping == NULL)
4058 type->tp_as_mapping = base->tp_as_mapping;
4059 if (type->tp_as_buffer == NULL)
4060 type->tp_as_buffer = base->tp_as_buffer;
4063 /* Link into each base class's list of subclasses */
4064 bases = type->tp_bases;
4065 n = PyTuple_GET_SIZE(bases);
4066 for (i = 0; i < n; i++) {
4067 PyObject *b = PyTuple_GET_ITEM(bases, i);
4068 if (PyType_Check(b) &&
4069 add_subclass((PyTypeObject *)b, type) < 0)
4070 goto error;
4073 /* All done -- set the ready flag */
4074 assert(type->tp_dict != NULL);
4075 type->tp_flags =
4076 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4077 return 0;
4079 error:
4080 type->tp_flags &= ~Py_TPFLAGS_READYING;
4081 return -1;
4084 static int
4085 add_subclass(PyTypeObject *base, PyTypeObject *type)
4087 Py_ssize_t i;
4088 int result;
4089 PyObject *list, *ref, *newobj;
4091 list = base->tp_subclasses;
4092 if (list == NULL) {
4093 base->tp_subclasses = list = PyList_New(0);
4094 if (list == NULL)
4095 return -1;
4097 assert(PyList_Check(list));
4098 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
4099 i = PyList_GET_SIZE(list);
4100 while (--i >= 0) {
4101 ref = PyList_GET_ITEM(list, i);
4102 assert(PyWeakref_CheckRef(ref));
4103 if (PyWeakref_GET_OBJECT(ref) == Py_None)
4104 return PyList_SetItem(list, i, newobj);
4106 result = PyList_Append(list, newobj);
4107 Py_DECREF(newobj);
4108 return result;
4111 static void
4112 remove_subclass(PyTypeObject *base, PyTypeObject *type)
4114 Py_ssize_t i;
4115 PyObject *list, *ref;
4117 list = base->tp_subclasses;
4118 if (list == NULL) {
4119 return;
4121 assert(PyList_Check(list));
4122 i = PyList_GET_SIZE(list);
4123 while (--i >= 0) {
4124 ref = PyList_GET_ITEM(list, i);
4125 assert(PyWeakref_CheckRef(ref));
4126 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
4127 /* this can't fail, right? */
4128 PySequence_DelItem(list, i);
4129 return;
4134 static int
4135 check_num_args(PyObject *ob, int n)
4137 if (!PyTuple_CheckExact(ob)) {
4138 PyErr_SetString(PyExc_SystemError,
4139 "PyArg_UnpackTuple() argument list is not a tuple");
4140 return 0;
4142 if (n == PyTuple_GET_SIZE(ob))
4143 return 1;
4144 PyErr_Format(
4145 PyExc_TypeError,
4146 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
4147 return 0;
4150 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
4152 /* There's a wrapper *function* for each distinct function typedef used
4153 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
4154 wrapper *table* for each distinct operation (e.g. __len__, __add__).
4155 Most tables have only one entry; the tables for binary operators have two
4156 entries, one regular and one with reversed arguments. */
4158 static PyObject *
4159 wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
4161 lenfunc func = (lenfunc)wrapped;
4162 Py_ssize_t res;
4164 if (!check_num_args(args, 0))
4165 return NULL;
4166 res = (*func)(self);
4167 if (res == -1 && PyErr_Occurred())
4168 return NULL;
4169 return PyInt_FromLong((long)res);
4172 static PyObject *
4173 wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
4175 inquiry func = (inquiry)wrapped;
4176 int res;
4178 if (!check_num_args(args, 0))
4179 return NULL;
4180 res = (*func)(self);
4181 if (res == -1 && PyErr_Occurred())
4182 return NULL;
4183 return PyBool_FromLong((long)res);
4186 static PyObject *
4187 wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
4189 binaryfunc func = (binaryfunc)wrapped;
4190 PyObject *other;
4192 if (!check_num_args(args, 1))
4193 return NULL;
4194 other = PyTuple_GET_ITEM(args, 0);
4195 return (*func)(self, other);
4198 static PyObject *
4199 wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
4201 binaryfunc func = (binaryfunc)wrapped;
4202 PyObject *other;
4204 if (!check_num_args(args, 1))
4205 return NULL;
4206 other = PyTuple_GET_ITEM(args, 0);
4207 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
4208 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
4209 Py_INCREF(Py_NotImplemented);
4210 return Py_NotImplemented;
4212 return (*func)(self, other);
4215 static PyObject *
4216 wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4218 binaryfunc func = (binaryfunc)wrapped;
4219 PyObject *other;
4221 if (!check_num_args(args, 1))
4222 return NULL;
4223 other = PyTuple_GET_ITEM(args, 0);
4224 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
4225 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
4226 Py_INCREF(Py_NotImplemented);
4227 return Py_NotImplemented;
4229 return (*func)(other, self);
4232 static PyObject *
4233 wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
4235 coercion func = (coercion)wrapped;
4236 PyObject *other, *res;
4237 int ok;
4239 if (!check_num_args(args, 1))
4240 return NULL;
4241 other = PyTuple_GET_ITEM(args, 0);
4242 ok = func(&self, &other);
4243 if (ok < 0)
4244 return NULL;
4245 if (ok > 0) {
4246 Py_INCREF(Py_NotImplemented);
4247 return Py_NotImplemented;
4249 res = PyTuple_New(2);
4250 if (res == NULL) {
4251 Py_DECREF(self);
4252 Py_DECREF(other);
4253 return NULL;
4255 PyTuple_SET_ITEM(res, 0, self);
4256 PyTuple_SET_ITEM(res, 1, other);
4257 return res;
4260 static PyObject *
4261 wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
4263 ternaryfunc func = (ternaryfunc)wrapped;
4264 PyObject *other;
4265 PyObject *third = Py_None;
4267 /* Note: This wrapper only works for __pow__() */
4269 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4270 return NULL;
4271 return (*func)(self, other, third);
4274 static PyObject *
4275 wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
4277 ternaryfunc func = (ternaryfunc)wrapped;
4278 PyObject *other;
4279 PyObject *third = Py_None;
4281 /* Note: This wrapper only works for __pow__() */
4283 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
4284 return NULL;
4285 return (*func)(other, self, third);
4288 static PyObject *
4289 wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
4291 unaryfunc func = (unaryfunc)wrapped;
4293 if (!check_num_args(args, 0))
4294 return NULL;
4295 return (*func)(self);
4298 static PyObject *
4299 wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
4301 ssizeargfunc func = (ssizeargfunc)wrapped;
4302 PyObject* o;
4303 Py_ssize_t i;
4305 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
4306 return NULL;
4307 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
4308 if (i == -1 && PyErr_Occurred())
4309 return NULL;
4310 return (*func)(self, i);
4313 static Py_ssize_t
4314 getindex(PyObject *self, PyObject *arg)
4316 Py_ssize_t i;
4318 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
4319 if (i == -1 && PyErr_Occurred())
4320 return -1;
4321 if (i < 0) {
4322 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
4323 if (sq && sq->sq_length) {
4324 Py_ssize_t n = (*sq->sq_length)(self);
4325 if (n < 0)
4326 return -1;
4327 i += n;
4330 return i;
4333 static PyObject *
4334 wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
4336 ssizeargfunc func = (ssizeargfunc)wrapped;
4337 PyObject *arg;
4338 Py_ssize_t i;
4340 if (PyTuple_GET_SIZE(args) == 1) {
4341 arg = PyTuple_GET_ITEM(args, 0);
4342 i = getindex(self, arg);
4343 if (i == -1 && PyErr_Occurred())
4344 return NULL;
4345 return (*func)(self, i);
4347 check_num_args(args, 1);
4348 assert(PyErr_Occurred());
4349 return NULL;
4352 static PyObject *
4353 wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
4355 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
4356 Py_ssize_t i, j;
4358 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4359 return NULL;
4360 return (*func)(self, i, j);
4363 static PyObject *
4364 wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
4366 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4367 Py_ssize_t i;
4368 int res;
4369 PyObject *arg, *value;
4371 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
4372 return NULL;
4373 i = getindex(self, arg);
4374 if (i == -1 && PyErr_Occurred())
4375 return NULL;
4376 res = (*func)(self, i, value);
4377 if (res == -1 && PyErr_Occurred())
4378 return NULL;
4379 Py_INCREF(Py_None);
4380 return Py_None;
4383 static PyObject *
4384 wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
4386 ssizeobjargproc func = (ssizeobjargproc)wrapped;
4387 Py_ssize_t i;
4388 int res;
4389 PyObject *arg;
4391 if (!check_num_args(args, 1))
4392 return NULL;
4393 arg = PyTuple_GET_ITEM(args, 0);
4394 i = getindex(self, arg);
4395 if (i == -1 && PyErr_Occurred())
4396 return NULL;
4397 res = (*func)(self, i, NULL);
4398 if (res == -1 && PyErr_Occurred())
4399 return NULL;
4400 Py_INCREF(Py_None);
4401 return Py_None;
4404 static PyObject *
4405 wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
4407 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4408 Py_ssize_t i, j;
4409 int res;
4410 PyObject *value;
4412 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
4413 return NULL;
4414 res = (*func)(self, i, j, value);
4415 if (res == -1 && PyErr_Occurred())
4416 return NULL;
4417 Py_INCREF(Py_None);
4418 return Py_None;
4421 static PyObject *
4422 wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
4424 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
4425 Py_ssize_t i, j;
4426 int res;
4428 if (!PyArg_ParseTuple(args, "nn", &i, &j))
4429 return NULL;
4430 res = (*func)(self, i, j, NULL);
4431 if (res == -1 && PyErr_Occurred())
4432 return NULL;
4433 Py_INCREF(Py_None);
4434 return Py_None;
4437 /* XXX objobjproc is a misnomer; should be objargpred */
4438 static PyObject *
4439 wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
4441 objobjproc func = (objobjproc)wrapped;
4442 int res;
4443 PyObject *value;
4445 if (!check_num_args(args, 1))
4446 return NULL;
4447 value = PyTuple_GET_ITEM(args, 0);
4448 res = (*func)(self, value);
4449 if (res == -1 && PyErr_Occurred())
4450 return NULL;
4451 else
4452 return PyBool_FromLong(res);
4455 static PyObject *
4456 wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
4458 objobjargproc func = (objobjargproc)wrapped;
4459 int res;
4460 PyObject *key, *value;
4462 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
4463 return NULL;
4464 res = (*func)(self, key, value);
4465 if (res == -1 && PyErr_Occurred())
4466 return NULL;
4467 Py_INCREF(Py_None);
4468 return Py_None;
4471 static PyObject *
4472 wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
4474 objobjargproc func = (objobjargproc)wrapped;
4475 int res;
4476 PyObject *key;
4478 if (!check_num_args(args, 1))
4479 return NULL;
4480 key = PyTuple_GET_ITEM(args, 0);
4481 res = (*func)(self, key, NULL);
4482 if (res == -1 && PyErr_Occurred())
4483 return NULL;
4484 Py_INCREF(Py_None);
4485 return Py_None;
4488 static PyObject *
4489 wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
4491 cmpfunc func = (cmpfunc)wrapped;
4492 int res;
4493 PyObject *other;
4495 if (!check_num_args(args, 1))
4496 return NULL;
4497 other = PyTuple_GET_ITEM(args, 0);
4498 if (Py_TYPE(other)->tp_compare != func &&
4499 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
4500 PyErr_Format(
4501 PyExc_TypeError,
4502 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
4503 Py_TYPE(self)->tp_name,
4504 Py_TYPE(self)->tp_name,
4505 Py_TYPE(other)->tp_name);
4506 return NULL;
4508 res = (*func)(self, other);
4509 if (PyErr_Occurred())
4510 return NULL;
4511 return PyInt_FromLong((long)res);
4514 /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
4515 This is called the Carlo Verre hack after its discoverer. */
4516 static int
4517 hackcheck(PyObject *self, setattrofunc func, char *what)
4519 PyTypeObject *type = Py_TYPE(self);
4520 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4521 type = type->tp_base;
4522 /* If type is NULL now, this is a really weird type.
4523 In the spirit of backwards compatibility (?), just shut up. */
4524 if (type && type->tp_setattro != func) {
4525 PyErr_Format(PyExc_TypeError,
4526 "can't apply this %s to %s object",
4527 what,
4528 type->tp_name);
4529 return 0;
4531 return 1;
4534 static PyObject *
4535 wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4537 setattrofunc func = (setattrofunc)wrapped;
4538 int res;
4539 PyObject *name, *value;
4541 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
4542 return NULL;
4543 if (!hackcheck(self, func, "__setattr__"))
4544 return NULL;
4545 res = (*func)(self, name, value);
4546 if (res < 0)
4547 return NULL;
4548 Py_INCREF(Py_None);
4549 return Py_None;
4552 static PyObject *
4553 wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4555 setattrofunc func = (setattrofunc)wrapped;
4556 int res;
4557 PyObject *name;
4559 if (!check_num_args(args, 1))
4560 return NULL;
4561 name = PyTuple_GET_ITEM(args, 0);
4562 if (!hackcheck(self, func, "__delattr__"))
4563 return NULL;
4564 res = (*func)(self, name, NULL);
4565 if (res < 0)
4566 return NULL;
4567 Py_INCREF(Py_None);
4568 return Py_None;
4571 static PyObject *
4572 wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4574 hashfunc func = (hashfunc)wrapped;
4575 long res;
4577 if (!check_num_args(args, 0))
4578 return NULL;
4579 res = (*func)(self);
4580 if (res == -1 && PyErr_Occurred())
4581 return NULL;
4582 return PyInt_FromLong(res);
4585 static PyObject *
4586 wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
4588 ternaryfunc func = (ternaryfunc)wrapped;
4590 return (*func)(self, args, kwds);
4593 static PyObject *
4594 wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4596 richcmpfunc func = (richcmpfunc)wrapped;
4597 PyObject *other;
4599 if (!check_num_args(args, 1))
4600 return NULL;
4601 other = PyTuple_GET_ITEM(args, 0);
4602 return (*func)(self, other, op);
4605 #undef RICHCMP_WRAPPER
4606 #define RICHCMP_WRAPPER(NAME, OP) \
4607 static PyObject * \
4608 richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4610 return wrap_richcmpfunc(self, args, wrapped, OP); \
4613 RICHCMP_WRAPPER(lt, Py_LT)
4614 RICHCMP_WRAPPER(le, Py_LE)
4615 RICHCMP_WRAPPER(eq, Py_EQ)
4616 RICHCMP_WRAPPER(ne, Py_NE)
4617 RICHCMP_WRAPPER(gt, Py_GT)
4618 RICHCMP_WRAPPER(ge, Py_GE)
4620 static PyObject *
4621 wrap_next(PyObject *self, PyObject *args, void *wrapped)
4623 unaryfunc func = (unaryfunc)wrapped;
4624 PyObject *res;
4626 if (!check_num_args(args, 0))
4627 return NULL;
4628 res = (*func)(self);
4629 if (res == NULL && !PyErr_Occurred())
4630 PyErr_SetNone(PyExc_StopIteration);
4631 return res;
4634 static PyObject *
4635 wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4637 descrgetfunc func = (descrgetfunc)wrapped;
4638 PyObject *obj;
4639 PyObject *type = NULL;
4641 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
4642 return NULL;
4643 if (obj == Py_None)
4644 obj = NULL;
4645 if (type == Py_None)
4646 type = NULL;
4647 if (type == NULL &&obj == NULL) {
4648 PyErr_SetString(PyExc_TypeError,
4649 "__get__(None, None) is invalid");
4650 return NULL;
4652 return (*func)(self, obj, type);
4655 static PyObject *
4656 wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
4658 descrsetfunc func = (descrsetfunc)wrapped;
4659 PyObject *obj, *value;
4660 int ret;
4662 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
4663 return NULL;
4664 ret = (*func)(self, obj, value);
4665 if (ret < 0)
4666 return NULL;
4667 Py_INCREF(Py_None);
4668 return Py_None;
4671 static PyObject *
4672 wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4674 descrsetfunc func = (descrsetfunc)wrapped;
4675 PyObject *obj;
4676 int ret;
4678 if (!check_num_args(args, 1))
4679 return NULL;
4680 obj = PyTuple_GET_ITEM(args, 0);
4681 ret = (*func)(self, obj, NULL);
4682 if (ret < 0)
4683 return NULL;
4684 Py_INCREF(Py_None);
4685 return Py_None;
4688 static PyObject *
4689 wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
4691 initproc func = (initproc)wrapped;
4693 if (func(self, args, kwds) < 0)
4694 return NULL;
4695 Py_INCREF(Py_None);
4696 return Py_None;
4699 static PyObject *
4700 tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
4702 PyTypeObject *type, *subtype, *staticbase;
4703 PyObject *arg0, *res;
4705 if (self == NULL || !PyType_Check(self))
4706 Py_FatalError("__new__() called with non-type 'self'");
4707 type = (PyTypeObject *)self;
4708 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
4709 PyErr_Format(PyExc_TypeError,
4710 "%s.__new__(): not enough arguments",
4711 type->tp_name);
4712 return NULL;
4714 arg0 = PyTuple_GET_ITEM(args, 0);
4715 if (!PyType_Check(arg0)) {
4716 PyErr_Format(PyExc_TypeError,
4717 "%s.__new__(X): X is not a type object (%s)",
4718 type->tp_name,
4719 Py_TYPE(arg0)->tp_name);
4720 return NULL;
4722 subtype = (PyTypeObject *)arg0;
4723 if (!PyType_IsSubtype(subtype, type)) {
4724 PyErr_Format(PyExc_TypeError,
4725 "%s.__new__(%s): %s is not a subtype of %s",
4726 type->tp_name,
4727 subtype->tp_name,
4728 subtype->tp_name,
4729 type->tp_name);
4730 return NULL;
4733 /* Check that the use doesn't do something silly and unsafe like
4734 object.__new__(dict). To do this, we check that the
4735 most derived base that's not a heap type is this type. */
4736 staticbase = subtype;
4737 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4738 staticbase = staticbase->tp_base;
4739 /* If staticbase is NULL now, it is a really weird type.
4740 In the spirit of backwards compatibility (?), just shut up. */
4741 if (staticbase && staticbase->tp_new != type->tp_new) {
4742 PyErr_Format(PyExc_TypeError,
4743 "%s.__new__(%s) is not safe, use %s.__new__()",
4744 type->tp_name,
4745 subtype->tp_name,
4746 staticbase == NULL ? "?" : staticbase->tp_name);
4747 return NULL;
4750 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4751 if (args == NULL)
4752 return NULL;
4753 res = type->tp_new(subtype, args, kwds);
4754 Py_DECREF(args);
4755 return res;
4758 static struct PyMethodDef tp_new_methoddef[] = {
4759 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
4760 PyDoc_STR("T.__new__(S, ...) -> "
4761 "a new object with type S, a subtype of T")},
4765 static int
4766 add_tp_new_wrapper(PyTypeObject *type)
4768 PyObject *func;
4770 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
4771 return 0;
4772 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
4773 if (func == NULL)
4774 return -1;
4775 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
4776 Py_DECREF(func);
4777 return -1;
4779 Py_DECREF(func);
4780 return 0;
4783 /* Slot wrappers that call the corresponding __foo__ slot. See comments
4784 below at override_slots() for more explanation. */
4786 #define SLOT0(FUNCNAME, OPSTR) \
4787 static PyObject * \
4788 FUNCNAME(PyObject *self) \
4790 static PyObject *cache_str; \
4791 return call_method(self, OPSTR, &cache_str, "()"); \
4794 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
4795 static PyObject * \
4796 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
4798 static PyObject *cache_str; \
4799 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
4802 /* Boolean helper for SLOT1BINFULL().
4803 right.__class__ is a nontrivial subclass of left.__class__. */
4804 static int
4805 method_is_overloaded(PyObject *left, PyObject *right, char *name)
4807 PyObject *a, *b;
4808 int ok;
4810 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
4811 if (b == NULL) {
4812 PyErr_Clear();
4813 /* If right doesn't have it, it's not overloaded */
4814 return 0;
4817 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
4818 if (a == NULL) {
4819 PyErr_Clear();
4820 Py_DECREF(b);
4821 /* If right has it but left doesn't, it's overloaded */
4822 return 1;
4825 ok = PyObject_RichCompareBool(a, b, Py_NE);
4826 Py_DECREF(a);
4827 Py_DECREF(b);
4828 if (ok < 0) {
4829 PyErr_Clear();
4830 return 0;
4833 return ok;
4837 #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
4838 static PyObject * \
4839 FUNCNAME(PyObject *self, PyObject *other) \
4841 static PyObject *cache_str, *rcache_str; \
4842 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4843 Py_TYPE(other)->tp_as_number != NULL && \
4844 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4845 if (Py_TYPE(self)->tp_as_number != NULL && \
4846 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
4847 PyObject *r; \
4848 if (do_other && \
4849 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
4850 method_is_overloaded(self, other, ROPSTR)) { \
4851 r = call_maybe( \
4852 other, ROPSTR, &rcache_str, "(O)", self); \
4853 if (r != Py_NotImplemented) \
4854 return r; \
4855 Py_DECREF(r); \
4856 do_other = 0; \
4858 r = call_maybe( \
4859 self, OPSTR, &cache_str, "(O)", other); \
4860 if (r != Py_NotImplemented || \
4861 Py_TYPE(other) == Py_TYPE(self)) \
4862 return r; \
4863 Py_DECREF(r); \
4865 if (do_other) { \
4866 return call_maybe( \
4867 other, ROPSTR, &rcache_str, "(O)", self); \
4869 Py_INCREF(Py_NotImplemented); \
4870 return Py_NotImplemented; \
4873 #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4874 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4876 #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4877 static PyObject * \
4878 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4880 static PyObject *cache_str; \
4881 return call_method(self, OPSTR, &cache_str, \
4882 "(" ARGCODES ")", arg1, arg2); \
4885 static Py_ssize_t
4886 slot_sq_length(PyObject *self)
4888 static PyObject *len_str;
4889 PyObject *res = call_method(self, "__len__", &len_str, "()");
4890 Py_ssize_t len;
4892 if (res == NULL)
4893 return -1;
4894 len = PyInt_AsSsize_t(res);
4895 Py_DECREF(res);
4896 if (len < 0) {
4897 if (!PyErr_Occurred())
4898 PyErr_SetString(PyExc_ValueError,
4899 "__len__() should return >= 0");
4900 return -1;
4902 return len;
4905 /* Super-optimized version of slot_sq_item.
4906 Other slots could do the same... */
4907 static PyObject *
4908 slot_sq_item(PyObject *self, Py_ssize_t i)
4910 static PyObject *getitem_str;
4911 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4912 descrgetfunc f;
4914 if (getitem_str == NULL) {
4915 getitem_str = PyString_InternFromString("__getitem__");
4916 if (getitem_str == NULL)
4917 return NULL;
4919 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
4920 if (func != NULL) {
4921 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
4922 Py_INCREF(func);
4923 else {
4924 func = f(func, self, (PyObject *)(Py_TYPE(self)));
4925 if (func == NULL) {
4926 return NULL;
4929 ival = PyInt_FromSsize_t(i);
4930 if (ival != NULL) {
4931 args = PyTuple_New(1);
4932 if (args != NULL) {
4933 PyTuple_SET_ITEM(args, 0, ival);
4934 retval = PyObject_Call(func, args, NULL);
4935 Py_XDECREF(args);
4936 Py_XDECREF(func);
4937 return retval;
4941 else {
4942 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4944 Py_XDECREF(args);
4945 Py_XDECREF(ival);
4946 Py_XDECREF(func);
4947 return NULL;
4950 static PyObject*
4951 slot_sq_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j)
4953 static PyObject *getslice_str;
4955 if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
4956 "use __getitem__", 1) < 0)
4957 return NULL;
4958 return call_method(self, "__getslice__", &getslice_str,
4959 "nn", i, j);
4962 static int
4963 slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
4965 PyObject *res;
4966 static PyObject *delitem_str, *setitem_str;
4968 if (value == NULL)
4969 res = call_method(self, "__delitem__", &delitem_str,
4970 "(n)", index);
4971 else
4972 res = call_method(self, "__setitem__", &setitem_str,
4973 "(nO)", index, value);
4974 if (res == NULL)
4975 return -1;
4976 Py_DECREF(res);
4977 return 0;
4980 static int
4981 slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
4983 PyObject *res;
4984 static PyObject *delslice_str, *setslice_str;
4986 if (value == NULL) {
4987 if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; "
4988 "use __delitem__", 1) < 0)
4989 return -1;
4990 res = call_method(self, "__delslice__", &delslice_str,
4991 "(nn)", i, j);
4993 else {
4994 if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; "
4995 "use __setitem__", 1) < 0)
4996 return -1;
4997 res = call_method(self, "__setslice__", &setslice_str,
4998 "(nnO)", i, j, value);
5000 if (res == NULL)
5001 return -1;
5002 Py_DECREF(res);
5003 return 0;
5006 static int
5007 slot_sq_contains(PyObject *self, PyObject *value)
5009 PyObject *func, *res, *args;
5010 int result = -1;
5012 static PyObject *contains_str;
5014 func = lookup_maybe(self, "__contains__", &contains_str);
5015 if (func != NULL) {
5016 args = PyTuple_Pack(1, value);
5017 if (args == NULL)
5018 res = NULL;
5019 else {
5020 res = PyObject_Call(func, args, NULL);
5021 Py_DECREF(args);
5023 Py_DECREF(func);
5024 if (res != NULL) {
5025 result = PyObject_IsTrue(res);
5026 Py_DECREF(res);
5029 else if (! PyErr_Occurred()) {
5030 /* Possible results: -1 and 1 */
5031 result = (int)_PySequence_IterSearch(self, value,
5032 PY_ITERSEARCH_CONTAINS);
5034 return result;
5037 #define slot_mp_length slot_sq_length
5039 SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
5041 static int
5042 slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5044 PyObject *res;
5045 static PyObject *delitem_str, *setitem_str;
5047 if (value == NULL)
5048 res = call_method(self, "__delitem__", &delitem_str,
5049 "(O)", key);
5050 else
5051 res = call_method(self, "__setitem__", &setitem_str,
5052 "(OO)", key, value);
5053 if (res == NULL)
5054 return -1;
5055 Py_DECREF(res);
5056 return 0;
5059 SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5060 SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5061 SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
5062 SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
5063 SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5064 SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5066 static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
5068 SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
5069 nb_power, "__pow__", "__rpow__")
5071 static PyObject *
5072 slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5074 static PyObject *pow_str;
5076 if (modulus == Py_None)
5077 return slot_nb_power_binary(self, other);
5078 /* Three-arg power doesn't use __rpow__. But ternary_op
5079 can call this when the second argument's type uses
5080 slot_nb_power, so check before calling self.__pow__. */
5081 if (Py_TYPE(self)->tp_as_number != NULL &&
5082 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
5083 return call_method(self, "__pow__", &pow_str,
5084 "(OO)", other, modulus);
5086 Py_INCREF(Py_NotImplemented);
5087 return Py_NotImplemented;
5090 SLOT0(slot_nb_negative, "__neg__")
5091 SLOT0(slot_nb_positive, "__pos__")
5092 SLOT0(slot_nb_absolute, "__abs__")
5094 static int
5095 slot_nb_nonzero(PyObject *self)
5097 PyObject *func, *args;
5098 static PyObject *nonzero_str, *len_str;
5099 int result = -1;
5100 int using_len = 0;
5102 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
5103 if (func == NULL) {
5104 if (PyErr_Occurred())
5105 return -1;
5106 func = lookup_maybe(self, "__len__", &len_str);
5107 if (func == NULL)
5108 return PyErr_Occurred() ? -1 : 1;
5109 using_len = 1;
5111 args = PyTuple_New(0);
5112 if (args != NULL) {
5113 PyObject *temp = PyObject_Call(func, args, NULL);
5114 Py_DECREF(args);
5115 if (temp != NULL) {
5116 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
5117 result = PyObject_IsTrue(temp);
5118 else {
5119 PyErr_Format(PyExc_TypeError,
5120 "%s should return "
5121 "bool or int, returned %s",
5122 (using_len ? "__len__"
5123 : "__nonzero__"),
5124 temp->ob_type->tp_name);
5125 result = -1;
5127 Py_DECREF(temp);
5130 Py_DECREF(func);
5131 return result;
5135 static PyObject *
5136 slot_nb_index(PyObject *self)
5138 static PyObject *index_str;
5139 return call_method(self, "__index__", &index_str, "()");
5143 SLOT0(slot_nb_invert, "__invert__")
5144 SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5145 SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5146 SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5147 SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5148 SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
5150 static int
5151 slot_nb_coerce(PyObject **a, PyObject **b)
5153 static PyObject *coerce_str;
5154 PyObject *self = *a, *other = *b;
5156 if (self->ob_type->tp_as_number != NULL &&
5157 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5158 PyObject *r;
5159 r = call_maybe(
5160 self, "__coerce__", &coerce_str, "(O)", other);
5161 if (r == NULL)
5162 return -1;
5163 if (r == Py_NotImplemented) {
5164 Py_DECREF(r);
5166 else {
5167 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5168 PyErr_SetString(PyExc_TypeError,
5169 "__coerce__ didn't return a 2-tuple");
5170 Py_DECREF(r);
5171 return -1;
5173 *a = PyTuple_GET_ITEM(r, 0);
5174 Py_INCREF(*a);
5175 *b = PyTuple_GET_ITEM(r, 1);
5176 Py_INCREF(*b);
5177 Py_DECREF(r);
5178 return 0;
5181 if (other->ob_type->tp_as_number != NULL &&
5182 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
5183 PyObject *r;
5184 r = call_maybe(
5185 other, "__coerce__", &coerce_str, "(O)", self);
5186 if (r == NULL)
5187 return -1;
5188 if (r == Py_NotImplemented) {
5189 Py_DECREF(r);
5190 return 1;
5192 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
5193 PyErr_SetString(PyExc_TypeError,
5194 "__coerce__ didn't return a 2-tuple");
5195 Py_DECREF(r);
5196 return -1;
5198 *a = PyTuple_GET_ITEM(r, 1);
5199 Py_INCREF(*a);
5200 *b = PyTuple_GET_ITEM(r, 0);
5201 Py_INCREF(*b);
5202 Py_DECREF(r);
5203 return 0;
5205 return 1;
5208 SLOT0(slot_nb_int, "__int__")
5209 SLOT0(slot_nb_long, "__long__")
5210 SLOT0(slot_nb_float, "__float__")
5211 SLOT0(slot_nb_oct, "__oct__")
5212 SLOT0(slot_nb_hex, "__hex__")
5213 SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
5214 SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
5215 SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
5216 SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
5217 SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
5218 /* Can't use SLOT1 here, because nb_inplace_power is ternary */
5219 static PyObject *
5220 slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
5222 static PyObject *cache_str;
5223 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
5225 SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
5226 SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
5227 SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
5228 SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
5229 SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
5230 SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
5231 "__floordiv__", "__rfloordiv__")
5232 SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
5233 SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
5234 SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
5236 static int
5237 half_compare(PyObject *self, PyObject *other)
5239 PyObject *func, *args, *res;
5240 static PyObject *cmp_str;
5241 Py_ssize_t c;
5243 func = lookup_method(self, "__cmp__", &cmp_str);
5244 if (func == NULL) {
5245 PyErr_Clear();
5247 else {
5248 args = PyTuple_Pack(1, other);
5249 if (args == NULL)
5250 res = NULL;
5251 else {
5252 res = PyObject_Call(func, args, NULL);
5253 Py_DECREF(args);
5255 Py_DECREF(func);
5256 if (res != Py_NotImplemented) {
5257 if (res == NULL)
5258 return -2;
5259 c = PyInt_AsLong(res);
5260 Py_DECREF(res);
5261 if (c == -1 && PyErr_Occurred())
5262 return -2;
5263 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
5265 Py_DECREF(res);
5267 return 2;
5270 /* This slot is published for the benefit of try_3way_compare in object.c */
5272 _PyObject_SlotCompare(PyObject *self, PyObject *other)
5274 int c;
5276 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
5277 c = half_compare(self, other);
5278 if (c <= 1)
5279 return c;
5281 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
5282 c = half_compare(other, self);
5283 if (c < -1)
5284 return -2;
5285 if (c <= 1)
5286 return -c;
5288 return (void *)self < (void *)other ? -1 :
5289 (void *)self > (void *)other ? 1 : 0;
5292 static PyObject *
5293 slot_tp_repr(PyObject *self)
5295 PyObject *func, *res;
5296 static PyObject *repr_str;
5298 func = lookup_method(self, "__repr__", &repr_str);
5299 if (func != NULL) {
5300 res = PyEval_CallObject(func, NULL);
5301 Py_DECREF(func);
5302 return res;
5304 PyErr_Clear();
5305 return PyString_FromFormat("<%s object at %p>",
5306 Py_TYPE(self)->tp_name, self);
5309 static PyObject *
5310 slot_tp_str(PyObject *self)
5312 PyObject *func, *res;
5313 static PyObject *str_str;
5315 func = lookup_method(self, "__str__", &str_str);
5316 if (func != NULL) {
5317 res = PyEval_CallObject(func, NULL);
5318 Py_DECREF(func);
5319 return res;
5321 else {
5322 PyErr_Clear();
5323 return slot_tp_repr(self);
5327 static long
5328 slot_tp_hash(PyObject *self)
5330 PyObject *func;
5331 static PyObject *hash_str, *eq_str, *cmp_str;
5332 long h;
5334 func = lookup_method(self, "__hash__", &hash_str);
5336 if (func != NULL && func != Py_None) {
5337 PyObject *res = PyEval_CallObject(func, NULL);
5338 Py_DECREF(func);
5339 if (res == NULL)
5340 return -1;
5341 if (PyLong_Check(res))
5342 h = PyLong_Type.tp_hash(res);
5343 else
5344 h = PyInt_AsLong(res);
5345 Py_DECREF(res);
5347 else {
5348 Py_XDECREF(func); /* may be None */
5349 PyErr_Clear();
5350 func = lookup_method(self, "__eq__", &eq_str);
5351 if (func == NULL) {
5352 PyErr_Clear();
5353 func = lookup_method(self, "__cmp__", &cmp_str);
5355 if (func != NULL) {
5356 Py_DECREF(func);
5357 return PyObject_HashNotImplemented(self);
5359 PyErr_Clear();
5360 h = _Py_HashPointer((void *)self);
5362 if (h == -1 && !PyErr_Occurred())
5363 h = -2;
5364 return h;
5367 static PyObject *
5368 slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
5370 static PyObject *call_str;
5371 PyObject *meth = lookup_method(self, "__call__", &call_str);
5372 PyObject *res;
5374 if (meth == NULL)
5375 return NULL;
5377 res = PyObject_Call(meth, args, kwds);
5379 Py_DECREF(meth);
5380 return res;
5383 /* There are two slot dispatch functions for tp_getattro.
5385 - slot_tp_getattro() is used when __getattribute__ is overridden
5386 but no __getattr__ hook is present;
5388 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
5390 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
5391 detects the absence of __getattr__ and then installs the simpler slot if
5392 necessary. */
5394 static PyObject *
5395 slot_tp_getattro(PyObject *self, PyObject *name)
5397 static PyObject *getattribute_str = NULL;
5398 return call_method(self, "__getattribute__", &getattribute_str,
5399 "(O)", name);
5402 static PyObject *
5403 call_attribute(PyObject *self, PyObject *attr, PyObject *name)
5405 PyObject *res, *descr = NULL;
5406 descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
5408 if (f != NULL) {
5409 descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
5410 if (descr == NULL)
5411 return NULL;
5412 else
5413 attr = descr;
5415 res = PyObject_CallFunctionObjArgs(attr, name, NULL);
5416 Py_XDECREF(descr);
5417 return res;
5420 static PyObject *
5421 slot_tp_getattr_hook(PyObject *self, PyObject *name)
5423 PyTypeObject *tp = Py_TYPE(self);
5424 PyObject *getattr, *getattribute, *res;
5425 static PyObject *getattribute_str = NULL;
5426 static PyObject *getattr_str = NULL;
5428 if (getattr_str == NULL) {
5429 getattr_str = PyString_InternFromString("__getattr__");
5430 if (getattr_str == NULL)
5431 return NULL;
5433 if (getattribute_str == NULL) {
5434 getattribute_str =
5435 PyString_InternFromString("__getattribute__");
5436 if (getattribute_str == NULL)
5437 return NULL;
5439 /* speed hack: we could use lookup_maybe, but that would resolve the
5440 method fully for each attribute lookup for classes with
5441 __getattr__, even when the attribute is present. So we use
5442 _PyType_Lookup and create the method only when needed, with
5443 call_attribute. */
5444 getattr = _PyType_Lookup(tp, getattr_str);
5445 if (getattr == NULL) {
5446 /* No __getattr__ hook: use a simpler dispatcher */
5447 tp->tp_getattro = slot_tp_getattro;
5448 return slot_tp_getattro(self, name);
5450 Py_INCREF(getattr);
5451 /* speed hack: we could use lookup_maybe, but that would resolve the
5452 method fully for each attribute lookup for classes with
5453 __getattr__, even when self has the default __getattribute__
5454 method. So we use _PyType_Lookup and create the method only when
5455 needed, with call_attribute. */
5456 getattribute = _PyType_Lookup(tp, getattribute_str);
5457 if (getattribute == NULL ||
5458 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
5459 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
5460 (void *)PyObject_GenericGetAttr))
5461 res = PyObject_GenericGetAttr(self, name);
5462 else {
5463 Py_INCREF(getattribute);
5464 res = call_attribute(self, getattribute, name);
5465 Py_DECREF(getattribute);
5467 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
5468 PyErr_Clear();
5469 res = call_attribute(self, getattr, name);
5471 Py_DECREF(getattr);
5472 return res;
5475 static int
5476 slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
5478 PyObject *res;
5479 static PyObject *delattr_str, *setattr_str;
5481 if (value == NULL)
5482 res = call_method(self, "__delattr__", &delattr_str,
5483 "(O)", name);
5484 else
5485 res = call_method(self, "__setattr__", &setattr_str,
5486 "(OO)", name, value);
5487 if (res == NULL)
5488 return -1;
5489 Py_DECREF(res);
5490 return 0;
5493 static char *name_op[] = {
5494 "__lt__",
5495 "__le__",
5496 "__eq__",
5497 "__ne__",
5498 "__gt__",
5499 "__ge__",
5502 static PyObject *
5503 half_richcompare(PyObject *self, PyObject *other, int op)
5505 PyObject *func, *args, *res;
5506 static PyObject *op_str[6];
5508 func = lookup_method(self, name_op[op], &op_str[op]);
5509 if (func == NULL) {
5510 PyErr_Clear();
5511 Py_INCREF(Py_NotImplemented);
5512 return Py_NotImplemented;
5514 args = PyTuple_Pack(1, other);
5515 if (args == NULL)
5516 res = NULL;
5517 else {
5518 res = PyObject_Call(func, args, NULL);
5519 Py_DECREF(args);
5521 Py_DECREF(func);
5522 return res;
5525 static PyObject *
5526 slot_tp_richcompare(PyObject *self, PyObject *other, int op)
5528 PyObject *res;
5530 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
5531 res = half_richcompare(self, other, op);
5532 if (res != Py_NotImplemented)
5533 return res;
5534 Py_DECREF(res);
5536 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
5537 res = half_richcompare(other, self, _Py_SwappedOp[op]);
5538 if (res != Py_NotImplemented) {
5539 return res;
5541 Py_DECREF(res);
5543 Py_INCREF(Py_NotImplemented);
5544 return Py_NotImplemented;
5547 static PyObject *
5548 slot_tp_iter(PyObject *self)
5550 PyObject *func, *res;
5551 static PyObject *iter_str, *getitem_str;
5553 func = lookup_method(self, "__iter__", &iter_str);
5554 if (func != NULL) {
5555 PyObject *args;
5556 args = res = PyTuple_New(0);
5557 if (args != NULL) {
5558 res = PyObject_Call(func, args, NULL);
5559 Py_DECREF(args);
5561 Py_DECREF(func);
5562 return res;
5564 PyErr_Clear();
5565 func = lookup_method(self, "__getitem__", &getitem_str);
5566 if (func == NULL) {
5567 PyErr_Format(PyExc_TypeError,
5568 "'%.200s' object is not iterable",
5569 Py_TYPE(self)->tp_name);
5570 return NULL;
5572 Py_DECREF(func);
5573 return PySeqIter_New(self);
5576 static PyObject *
5577 slot_tp_iternext(PyObject *self)
5579 static PyObject *next_str;
5580 return call_method(self, "next", &next_str, "()");
5583 static PyObject *
5584 slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5586 PyTypeObject *tp = Py_TYPE(self);
5587 PyObject *get;
5588 static PyObject *get_str = NULL;
5590 if (get_str == NULL) {
5591 get_str = PyString_InternFromString("__get__");
5592 if (get_str == NULL)
5593 return NULL;
5595 get = _PyType_Lookup(tp, get_str);
5596 if (get == NULL) {
5597 /* Avoid further slowdowns */
5598 if (tp->tp_descr_get == slot_tp_descr_get)
5599 tp->tp_descr_get = NULL;
5600 Py_INCREF(self);
5601 return self;
5603 if (obj == NULL)
5604 obj = Py_None;
5605 if (type == NULL)
5606 type = Py_None;
5607 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
5610 static int
5611 slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5613 PyObject *res;
5614 static PyObject *del_str, *set_str;
5616 if (value == NULL)
5617 res = call_method(self, "__delete__", &del_str,
5618 "(O)", target);
5619 else
5620 res = call_method(self, "__set__", &set_str,
5621 "(OO)", target, value);
5622 if (res == NULL)
5623 return -1;
5624 Py_DECREF(res);
5625 return 0;
5628 static int
5629 slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5631 static PyObject *init_str;
5632 PyObject *meth = lookup_method(self, "__init__", &init_str);
5633 PyObject *res;
5635 if (meth == NULL)
5636 return -1;
5637 res = PyObject_Call(meth, args, kwds);
5638 Py_DECREF(meth);
5639 if (res == NULL)
5640 return -1;
5641 if (res != Py_None) {
5642 PyErr_Format(PyExc_TypeError,
5643 "__init__() should return None, not '%.200s'",
5644 Py_TYPE(res)->tp_name);
5645 Py_DECREF(res);
5646 return -1;
5648 Py_DECREF(res);
5649 return 0;
5652 static PyObject *
5653 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5655 static PyObject *new_str;
5656 PyObject *func;
5657 PyObject *newargs, *x;
5658 Py_ssize_t i, n;
5660 if (new_str == NULL) {
5661 new_str = PyString_InternFromString("__new__");
5662 if (new_str == NULL)
5663 return NULL;
5665 func = PyObject_GetAttr((PyObject *)type, new_str);
5666 if (func == NULL)
5667 return NULL;
5668 assert(PyTuple_Check(args));
5669 n = PyTuple_GET_SIZE(args);
5670 newargs = PyTuple_New(n+1);
5671 if (newargs == NULL)
5672 return NULL;
5673 Py_INCREF(type);
5674 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5675 for (i = 0; i < n; i++) {
5676 x = PyTuple_GET_ITEM(args, i);
5677 Py_INCREF(x);
5678 PyTuple_SET_ITEM(newargs, i+1, x);
5680 x = PyObject_Call(func, newargs, kwds);
5681 Py_DECREF(newargs);
5682 Py_DECREF(func);
5683 return x;
5686 static void
5687 slot_tp_del(PyObject *self)
5689 static PyObject *del_str = NULL;
5690 PyObject *del, *res;
5691 PyObject *error_type, *error_value, *error_traceback;
5693 /* Temporarily resurrect the object. */
5694 assert(self->ob_refcnt == 0);
5695 self->ob_refcnt = 1;
5697 /* Save the current exception, if any. */
5698 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5700 /* Execute __del__ method, if any. */
5701 del = lookup_maybe(self, "__del__", &del_str);
5702 if (del != NULL) {
5703 res = PyEval_CallObject(del, NULL);
5704 if (res == NULL)
5705 PyErr_WriteUnraisable(del);
5706 else
5707 Py_DECREF(res);
5708 Py_DECREF(del);
5711 /* Restore the saved exception. */
5712 PyErr_Restore(error_type, error_value, error_traceback);
5714 /* Undo the temporary resurrection; can't use DECREF here, it would
5715 * cause a recursive call.
5717 assert(self->ob_refcnt > 0);
5718 if (--self->ob_refcnt == 0)
5719 return; /* this is the normal path out */
5721 /* __del__ resurrected it! Make it look like the original Py_DECREF
5722 * never happened.
5725 Py_ssize_t refcnt = self->ob_refcnt;
5726 _Py_NewReference(self);
5727 self->ob_refcnt = refcnt;
5729 assert(!PyType_IS_GC(Py_TYPE(self)) ||
5730 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
5731 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5732 * we need to undo that. */
5733 _Py_DEC_REFTOTAL;
5734 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5735 * chain, so no more to do there.
5736 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5737 * _Py_NewReference bumped tp_allocs: both of those need to be
5738 * undone.
5740 #ifdef COUNT_ALLOCS
5741 --Py_TYPE(self)->tp_frees;
5742 --Py_TYPE(self)->tp_allocs;
5743 #endif
5747 /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
5748 functions. The offsets here are relative to the 'PyHeapTypeObject'
5749 structure, which incorporates the additional structures used for numbers,
5750 sequences and mappings.
5751 Note that multiple names may map to the same slot (e.g. __eq__,
5752 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
5753 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5754 terminated with an all-zero entry. (This table is further initialized and
5755 sorted in init_slotdefs() below.) */
5757 typedef struct wrapperbase slotdef;
5759 #undef TPSLOT
5760 #undef FLSLOT
5761 #undef ETSLOT
5762 #undef SQSLOT
5763 #undef MPSLOT
5764 #undef NBSLOT
5765 #undef UNSLOT
5766 #undef IBSLOT
5767 #undef BINSLOT
5768 #undef RBINSLOT
5770 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5771 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5772 PyDoc_STR(DOC)}
5773 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5774 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5775 PyDoc_STR(DOC), FLAGS}
5776 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5777 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5778 PyDoc_STR(DOC)}
5779 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5780 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5781 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5782 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5783 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5784 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5785 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5786 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5787 "x." NAME "() <==> " DOC)
5788 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5789 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5790 "x." NAME "(y) <==> x" DOC "y")
5791 #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5792 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5793 "x." NAME "(y) <==> x" DOC "y")
5794 #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5795 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5796 "x." NAME "(y) <==> y" DOC "x")
5797 #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5798 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5799 "x." NAME "(y) <==> " DOC)
5800 #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5801 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5802 "x." NAME "(y) <==> " DOC)
5804 static slotdef slotdefs[] = {
5805 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
5806 "x.__len__() <==> len(x)"),
5807 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5808 The logic in abstract.c always falls back to nb_add/nb_multiply in
5809 this case. Defining both the nb_* and the sq_* slots to call the
5810 user-defined methods has unexpected side-effects, as shown by
5811 test_descr.notimplemented() */
5812 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
5813 "x.__add__(y) <==> x+y"),
5814 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
5815 "x.__mul__(n) <==> x*n"),
5816 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
5817 "x.__rmul__(n) <==> n*x"),
5818 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5819 "x.__getitem__(y) <==> x[y]"),
5820 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
5821 "x.__getslice__(i, j) <==> x[i:j]\n\
5823 Use of negative indices is not supported."),
5824 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
5825 "x.__setitem__(i, y) <==> x[i]=y"),
5826 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
5827 "x.__delitem__(y) <==> del x[y]"),
5828 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
5829 wrap_ssizessizeobjargproc,
5830 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
5832 Use of negative indices is not supported."),
5833 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
5834 "x.__delslice__(i, j) <==> del x[i:j]\n\
5836 Use of negative indices is not supported."),
5837 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5838 "x.__contains__(y) <==> y in x"),
5839 SQSLOT("__iadd__", sq_inplace_concat, NULL,
5840 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
5841 SQSLOT("__imul__", sq_inplace_repeat, NULL,
5842 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
5844 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
5845 "x.__len__() <==> len(x)"),
5846 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
5847 wrap_binaryfunc,
5848 "x.__getitem__(y) <==> x[y]"),
5849 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
5850 wrap_objobjargproc,
5851 "x.__setitem__(i, y) <==> x[i]=y"),
5852 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
5853 wrap_delitem,
5854 "x.__delitem__(y) <==> del x[y]"),
5856 BINSLOT("__add__", nb_add, slot_nb_add,
5857 "+"),
5858 RBINSLOT("__radd__", nb_add, slot_nb_add,
5859 "+"),
5860 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5861 "-"),
5862 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5863 "-"),
5864 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5865 "*"),
5866 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5867 "*"),
5868 BINSLOT("__div__", nb_divide, slot_nb_divide,
5869 "/"),
5870 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5871 "/"),
5872 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5873 "%"),
5874 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5875 "%"),
5876 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
5877 "divmod(x, y)"),
5878 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
5879 "divmod(y, x)"),
5880 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5881 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5882 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5883 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5884 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5885 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5886 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5887 "abs(x)"),
5888 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
5889 "x != 0"),
5890 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5891 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5892 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5893 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5894 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5895 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5896 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5897 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5898 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5899 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5900 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5901 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5902 "x.__coerce__(y) <==> coerce(x, y)"),
5903 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5904 "int(x)"),
5905 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5906 "long(x)"),
5907 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5908 "float(x)"),
5909 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5910 "oct(x)"),
5911 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5912 "hex(x)"),
5913 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
5914 "x[y:z] <==> x[y.__index__():z.__index__()]"),
5915 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5916 wrap_binaryfunc, "+"),
5917 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5918 wrap_binaryfunc, "-"),
5919 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5920 wrap_binaryfunc, "*"),
5921 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5922 wrap_binaryfunc, "/"),
5923 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5924 wrap_binaryfunc, "%"),
5925 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
5926 wrap_binaryfunc, "**"),
5927 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5928 wrap_binaryfunc, "<<"),
5929 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5930 wrap_binaryfunc, ">>"),
5931 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5932 wrap_binaryfunc, "&"),
5933 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5934 wrap_binaryfunc, "^"),
5935 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5936 wrap_binaryfunc, "|"),
5937 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5938 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5939 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5940 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5941 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5942 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5943 IBSLOT("__itruediv__", nb_inplace_true_divide,
5944 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
5946 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5947 "x.__str__() <==> str(x)"),
5948 TPSLOT("__str__", tp_print, NULL, NULL, ""),
5949 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5950 "x.__repr__() <==> repr(x)"),
5951 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
5952 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5953 "x.__cmp__(y) <==> cmp(x,y)"),
5954 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5955 "x.__hash__() <==> hash(x)"),
5956 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5957 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
5958 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
5959 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5960 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5961 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5962 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5963 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5964 "x.__setattr__('name', value) <==> x.name = value"),
5965 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5966 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5967 "x.__delattr__('name') <==> del x.name"),
5968 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5969 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5970 "x.__lt__(y) <==> x<y"),
5971 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5972 "x.__le__(y) <==> x<=y"),
5973 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5974 "x.__eq__(y) <==> x==y"),
5975 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5976 "x.__ne__(y) <==> x!=y"),
5977 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5978 "x.__gt__(y) <==> x>y"),
5979 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5980 "x.__ge__(y) <==> x>=y"),
5981 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5982 "x.__iter__() <==> iter(x)"),
5983 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5984 "x.next() -> the next value, or raise StopIteration"),
5985 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5986 "descr.__get__(obj[, type]) -> value"),
5987 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5988 "descr.__set__(obj, value)"),
5989 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5990 wrap_descr_delete, "descr.__delete__(obj)"),
5991 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
5992 "x.__init__(...) initializes x; "
5993 "see x.__class__.__doc__ for signature",
5994 PyWrapperFlag_KEYWORDS),
5995 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
5996 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
5997 {NULL}
6000 /* Given a type pointer and an offset gotten from a slotdef entry, return a
6001 pointer to the actual slot. This is not quite the same as simply adding
6002 the offset to the type pointer, since it takes care to indirect through the
6003 proper indirection pointer (as_buffer, etc.); it returns NULL if the
6004 indirection pointer is NULL. */
6005 static void **
6006 slotptr(PyTypeObject *type, int ioffset)
6008 char *ptr;
6009 long offset = ioffset;
6011 /* Note: this depends on the order of the members of PyHeapTypeObject! */
6012 assert(offset >= 0);
6013 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6014 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6015 ptr = (char *)type->tp_as_sequence;
6016 offset -= offsetof(PyHeapTypeObject, as_sequence);
6018 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6019 ptr = (char *)type->tp_as_mapping;
6020 offset -= offsetof(PyHeapTypeObject, as_mapping);
6022 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6023 ptr = (char *)type->tp_as_number;
6024 offset -= offsetof(PyHeapTypeObject, as_number);
6026 else {
6027 ptr = (char *)type;
6029 if (ptr != NULL)
6030 ptr += offset;
6031 return (void **)ptr;
6034 /* Length of array of slotdef pointers used to store slots with the
6035 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
6036 the same __name__, for any __name__. Since that's a static property, it is
6037 appropriate to declare fixed-size arrays for this. */
6038 #define MAX_EQUIV 10
6040 /* Return a slot pointer for a given name, but ONLY if the attribute has
6041 exactly one slot function. The name must be an interned string. */
6042 static void **
6043 resolve_slotdups(PyTypeObject *type, PyObject *name)
6045 /* XXX Maybe this could be optimized more -- but is it worth it? */
6047 /* pname and ptrs act as a little cache */
6048 static PyObject *pname;
6049 static slotdef *ptrs[MAX_EQUIV];
6050 slotdef *p, **pp;
6051 void **res, **ptr;
6053 if (pname != name) {
6054 /* Collect all slotdefs that match name into ptrs. */
6055 pname = name;
6056 pp = ptrs;
6057 for (p = slotdefs; p->name_strobj; p++) {
6058 if (p->name_strobj == name)
6059 *pp++ = p;
6061 *pp = NULL;
6064 /* Look in all matching slots of the type; if exactly one of these has
6065 a filled-in slot, return its value. Otherwise return NULL. */
6066 res = NULL;
6067 for (pp = ptrs; *pp; pp++) {
6068 ptr = slotptr(type, (*pp)->offset);
6069 if (ptr == NULL || *ptr == NULL)
6070 continue;
6071 if (res != NULL)
6072 return NULL;
6073 res = ptr;
6075 return res;
6078 /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
6079 does some incredibly complex thinking and then sticks something into the
6080 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
6081 interests, and then stores a generic wrapper or a specific function into
6082 the slot.) Return a pointer to the next slotdef with a different offset,
6083 because that's convenient for fixup_slot_dispatchers(). */
6084 static slotdef *
6085 update_one_slot(PyTypeObject *type, slotdef *p)
6087 PyObject *descr;
6088 PyWrapperDescrObject *d;
6089 void *generic = NULL, *specific = NULL;
6090 int use_generic = 0;
6091 int offset = p->offset;
6092 void **ptr = slotptr(type, offset);
6094 if (ptr == NULL) {
6095 do {
6096 ++p;
6097 } while (p->offset == offset);
6098 return p;
6100 do {
6101 descr = _PyType_Lookup(type, p->name_strobj);
6102 if (descr == NULL) {
6103 if (ptr == (void**)&type->tp_iternext) {
6104 specific = _PyObject_NextNotImplemented;
6106 continue;
6108 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
6109 void **tptr = resolve_slotdups(type, p->name_strobj);
6110 if (tptr == NULL || tptr == ptr)
6111 generic = p->function;
6112 d = (PyWrapperDescrObject *)descr;
6113 if (d->d_base->wrapper == p->wrapper &&
6114 PyType_IsSubtype(type, d->d_type))
6116 if (specific == NULL ||
6117 specific == d->d_wrapped)
6118 specific = d->d_wrapped;
6119 else
6120 use_generic = 1;
6123 else if (Py_TYPE(descr) == &PyCFunction_Type &&
6124 PyCFunction_GET_FUNCTION(descr) ==
6125 (PyCFunction)tp_new_wrapper &&
6126 ptr == (void**)&type->tp_new)
6128 /* The __new__ wrapper is not a wrapper descriptor,
6129 so must be special-cased differently.
6130 If we don't do this, creating an instance will
6131 always use slot_tp_new which will look up
6132 __new__ in the MRO which will call tp_new_wrapper
6133 which will look through the base classes looking
6134 for a static base and call its tp_new (usually
6135 PyType_GenericNew), after performing various
6136 sanity checks and constructing a new argument
6137 list. Cut all that nonsense short -- this speeds
6138 up instance creation tremendously. */
6139 specific = (void *)type->tp_new;
6140 /* XXX I'm not 100% sure that there isn't a hole
6141 in this reasoning that requires additional
6142 sanity checks. I'll buy the first person to
6143 point out a bug in this reasoning a beer. */
6145 else if (descr == Py_None &&
6146 ptr == (void**)&type->tp_hash) {
6147 /* We specifically allow __hash__ to be set to None
6148 to prevent inheritance of the default
6149 implementation from object.__hash__ */
6150 specific = PyObject_HashNotImplemented;
6152 else {
6153 use_generic = 1;
6154 generic = p->function;
6156 } while ((++p)->offset == offset);
6157 if (specific && !use_generic)
6158 *ptr = specific;
6159 else
6160 *ptr = generic;
6161 return p;
6164 /* In the type, update the slots whose slotdefs are gathered in the pp array.
6165 This is a callback for update_subclasses(). */
6166 static int
6167 update_slots_callback(PyTypeObject *type, void *data)
6169 slotdef **pp = (slotdef **)data;
6171 for (; *pp; pp++)
6172 update_one_slot(type, *pp);
6173 return 0;
6176 /* Comparison function for qsort() to compare slotdefs by their offset, and
6177 for equal offset by their address (to force a stable sort). */
6178 static int
6179 slotdef_cmp(const void *aa, const void *bb)
6181 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
6182 int c = a->offset - b->offset;
6183 if (c != 0)
6184 return c;
6185 else
6186 /* Cannot use a-b, as this gives off_t,
6187 which may lose precision when converted to int. */
6188 return (a > b) ? 1 : (a < b) ? -1 : 0;
6191 /* Initialize the slotdefs table by adding interned string objects for the
6192 names and sorting the entries. */
6193 static void
6194 init_slotdefs(void)
6196 slotdef *p;
6197 static int initialized = 0;
6199 if (initialized)
6200 return;
6201 for (p = slotdefs; p->name; p++) {
6202 p->name_strobj = PyString_InternFromString(p->name);
6203 if (!p->name_strobj)
6204 Py_FatalError("Out of memory interning slotdef names");
6206 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
6207 slotdef_cmp);
6208 initialized = 1;
6211 /* Update the slots after assignment to a class (type) attribute. */
6212 static int
6213 update_slot(PyTypeObject *type, PyObject *name)
6215 slotdef *ptrs[MAX_EQUIV];
6216 slotdef *p;
6217 slotdef **pp;
6218 int offset;
6220 /* Clear the VALID_VERSION flag of 'type' and all its
6221 subclasses. This could possibly be unified with the
6222 update_subclasses() recursion below, but carefully:
6223 they each have their own conditions on which to stop
6224 recursing into subclasses. */
6225 PyType_Modified(type);
6227 init_slotdefs();
6228 pp = ptrs;
6229 for (p = slotdefs; p->name; p++) {
6230 /* XXX assume name is interned! */
6231 if (p->name_strobj == name)
6232 *pp++ = p;
6234 *pp = NULL;
6235 for (pp = ptrs; *pp; pp++) {
6236 p = *pp;
6237 offset = p->offset;
6238 while (p > slotdefs && (p-1)->offset == offset)
6239 --p;
6240 *pp = p;
6242 if (ptrs[0] == NULL)
6243 return 0; /* Not an attribute that affects any slots */
6244 return update_subclasses(type, name,
6245 update_slots_callback, (void *)ptrs);
6248 /* Store the proper functions in the slot dispatches at class (type)
6249 definition time, based upon which operations the class overrides in its
6250 dict. */
6251 static void
6252 fixup_slot_dispatchers(PyTypeObject *type)
6254 slotdef *p;
6256 init_slotdefs();
6257 for (p = slotdefs; p->name; )
6258 p = update_one_slot(type, p);
6261 static void
6262 update_all_slots(PyTypeObject* type)
6264 slotdef *p;
6266 init_slotdefs();
6267 for (p = slotdefs; p->name; p++) {
6268 /* update_slot returns int but can't actually fail */
6269 update_slot(type, p->name_strobj);
6273 /* recurse_down_subclasses() and update_subclasses() are mutually
6274 recursive functions to call a callback for all subclasses,
6275 but refraining from recursing into subclasses that define 'name'. */
6277 static int
6278 update_subclasses(PyTypeObject *type, PyObject *name,
6279 update_callback callback, void *data)
6281 if (callback(type, data) < 0)
6282 return -1;
6283 return recurse_down_subclasses(type, name, callback, data);
6286 static int
6287 recurse_down_subclasses(PyTypeObject *type, PyObject *name,
6288 update_callback callback, void *data)
6290 PyTypeObject *subclass;
6291 PyObject *ref, *subclasses, *dict;
6292 Py_ssize_t i, n;
6294 subclasses = type->tp_subclasses;
6295 if (subclasses == NULL)
6296 return 0;
6297 assert(PyList_Check(subclasses));
6298 n = PyList_GET_SIZE(subclasses);
6299 for (i = 0; i < n; i++) {
6300 ref = PyList_GET_ITEM(subclasses, i);
6301 assert(PyWeakref_CheckRef(ref));
6302 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
6303 assert(subclass != NULL);
6304 if ((PyObject *)subclass == Py_None)
6305 continue;
6306 assert(PyType_Check(subclass));
6307 /* Avoid recursing down into unaffected classes */
6308 dict = subclass->tp_dict;
6309 if (dict != NULL && PyDict_Check(dict) &&
6310 PyDict_GetItem(dict, name) != NULL)
6311 continue;
6312 if (update_subclasses(subclass, name, callback, data) < 0)
6313 return -1;
6315 return 0;
6318 /* This function is called by PyType_Ready() to populate the type's
6319 dictionary with method descriptors for function slots. For each
6320 function slot (like tp_repr) that's defined in the type, one or more
6321 corresponding descriptors are added in the type's tp_dict dictionary
6322 under the appropriate name (like __repr__). Some function slots
6323 cause more than one descriptor to be added (for example, the nb_add
6324 slot adds both __add__ and __radd__ descriptors) and some function
6325 slots compete for the same descriptor (for example both sq_item and
6326 mp_subscript generate a __getitem__ descriptor).
6328 In the latter case, the first slotdef entry encoutered wins. Since
6329 slotdef entries are sorted by the offset of the slot in the
6330 PyHeapTypeObject, this gives us some control over disambiguating
6331 between competing slots: the members of PyHeapTypeObject are listed
6332 from most general to least general, so the most general slot is
6333 preferred. In particular, because as_mapping comes before as_sequence,
6334 for a type that defines both mp_subscript and sq_item, mp_subscript
6335 wins.
6337 This only adds new descriptors and doesn't overwrite entries in
6338 tp_dict that were previously defined. The descriptors contain a
6339 reference to the C function they must call, so that it's safe if they
6340 are copied into a subtype's __dict__ and the subtype has a different
6341 C function in its slot -- calling the method defined by the
6342 descriptor will call the C function that was used to create it,
6343 rather than the C function present in the slot when it is called.
6344 (This is important because a subtype may have a C function in the
6345 slot that calls the method from the dictionary, and we want to avoid
6346 infinite recursion here.) */
6348 static int
6349 add_operators(PyTypeObject *type)
6351 PyObject *dict = type->tp_dict;
6352 slotdef *p;
6353 PyObject *descr;
6354 void **ptr;
6356 init_slotdefs();
6357 for (p = slotdefs; p->name; p++) {
6358 if (p->wrapper == NULL)
6359 continue;
6360 ptr = slotptr(type, p->offset);
6361 if (!ptr || !*ptr)
6362 continue;
6363 if (PyDict_GetItem(dict, p->name_strobj))
6364 continue;
6365 if (*ptr == PyObject_HashNotImplemented) {
6366 /* Classes may prevent the inheritance of the tp_hash
6367 slot by storing PyObject_HashNotImplemented in it. Make it
6368 visible as a None value for the __hash__ attribute. */
6369 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6370 return -1;
6372 else {
6373 descr = PyDescr_NewWrapper(type, p, *ptr);
6374 if (descr == NULL)
6375 return -1;
6376 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
6377 return -1;
6378 Py_DECREF(descr);
6381 if (type->tp_new != NULL) {
6382 if (add_tp_new_wrapper(type) < 0)
6383 return -1;
6385 return 0;
6389 /* Cooperative 'super' */
6391 typedef struct {
6392 PyObject_HEAD
6393 PyTypeObject *type;
6394 PyObject *obj;
6395 PyTypeObject *obj_type;
6396 } superobject;
6398 static PyMemberDef super_members[] = {
6399 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
6400 "the class invoking super()"},
6401 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
6402 "the instance invoking super(); may be None"},
6403 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
6404 "the type of the instance invoking super(); may be None"},
6408 static void
6409 super_dealloc(PyObject *self)
6411 superobject *su = (superobject *)self;
6413 _PyObject_GC_UNTRACK(self);
6414 Py_XDECREF(su->obj);
6415 Py_XDECREF(su->type);
6416 Py_XDECREF(su->obj_type);
6417 Py_TYPE(self)->tp_free(self);
6420 static PyObject *
6421 super_repr(PyObject *self)
6423 superobject *su = (superobject *)self;
6425 if (su->obj_type)
6426 return PyString_FromFormat(
6427 "<super: <class '%s'>, <%s object>>",
6428 su->type ? su->type->tp_name : "NULL",
6429 su->obj_type->tp_name);
6430 else
6431 return PyString_FromFormat(
6432 "<super: <class '%s'>, NULL>",
6433 su->type ? su->type->tp_name : "NULL");
6436 static PyObject *
6437 super_getattro(PyObject *self, PyObject *name)
6439 superobject *su = (superobject *)self;
6440 int skip = su->obj_type == NULL;
6442 if (!skip) {
6443 /* We want __class__ to return the class of the super object
6444 (i.e. super, or a subclass), not the class of su->obj. */
6445 skip = (PyString_Check(name) &&
6446 PyString_GET_SIZE(name) == 9 &&
6447 strcmp(PyString_AS_STRING(name), "__class__") == 0);
6450 if (!skip) {
6451 PyObject *mro, *res, *tmp, *dict;
6452 PyTypeObject *starttype;
6453 descrgetfunc f;
6454 Py_ssize_t i, n;
6456 starttype = su->obj_type;
6457 mro = starttype->tp_mro;
6459 if (mro == NULL)
6460 n = 0;
6461 else {
6462 assert(PyTuple_Check(mro));
6463 n = PyTuple_GET_SIZE(mro);
6465 for (i = 0; i < n; i++) {
6466 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
6467 break;
6469 i++;
6470 res = NULL;
6471 for (; i < n; i++) {
6472 tmp = PyTuple_GET_ITEM(mro, i);
6473 if (PyType_Check(tmp))
6474 dict = ((PyTypeObject *)tmp)->tp_dict;
6475 else if (PyClass_Check(tmp))
6476 dict = ((PyClassObject *)tmp)->cl_dict;
6477 else
6478 continue;
6479 res = PyDict_GetItem(dict, name);
6480 if (res != NULL) {
6481 Py_INCREF(res);
6482 f = Py_TYPE(res)->tp_descr_get;
6483 if (f != NULL) {
6484 tmp = f(res,
6485 /* Only pass 'obj' param if
6486 this is instance-mode super
6487 (See SF ID #743627)
6489 (su->obj == (PyObject *)
6490 su->obj_type
6491 ? (PyObject *)NULL
6492 : su->obj),
6493 (PyObject *)starttype);
6494 Py_DECREF(res);
6495 res = tmp;
6497 return res;
6501 return PyObject_GenericGetAttr(self, name);
6504 static PyTypeObject *
6505 supercheck(PyTypeObject *type, PyObject *obj)
6507 /* Check that a super() call makes sense. Return a type object.
6509 obj can be a new-style class, or an instance of one:
6511 - If it is a class, it must be a subclass of 'type'. This case is
6512 used for class methods; the return value is obj.
6514 - If it is an instance, it must be an instance of 'type'. This is
6515 the normal case; the return value is obj.__class__.
6517 But... when obj is an instance, we want to allow for the case where
6518 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
6519 This will allow using super() with a proxy for obj.
6522 /* Check for first bullet above (special case) */
6523 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
6524 Py_INCREF(obj);
6525 return (PyTypeObject *)obj;
6528 /* Normal case */
6529 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
6530 Py_INCREF(Py_TYPE(obj));
6531 return Py_TYPE(obj);
6533 else {
6534 /* Try the slow way */
6535 static PyObject *class_str = NULL;
6536 PyObject *class_attr;
6538 if (class_str == NULL) {
6539 class_str = PyString_FromString("__class__");
6540 if (class_str == NULL)
6541 return NULL;
6544 class_attr = PyObject_GetAttr(obj, class_str);
6546 if (class_attr != NULL &&
6547 PyType_Check(class_attr) &&
6548 (PyTypeObject *)class_attr != Py_TYPE(obj))
6550 int ok = PyType_IsSubtype(
6551 (PyTypeObject *)class_attr, type);
6552 if (ok)
6553 return (PyTypeObject *)class_attr;
6556 if (class_attr == NULL)
6557 PyErr_Clear();
6558 else
6559 Py_DECREF(class_attr);
6562 PyErr_SetString(PyExc_TypeError,
6563 "super(type, obj): "
6564 "obj must be an instance or subtype of type");
6565 return NULL;
6568 static PyObject *
6569 super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6571 superobject *su = (superobject *)self;
6572 superobject *newobj;
6574 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6575 /* Not binding to an object, or already bound */
6576 Py_INCREF(self);
6577 return self;
6579 if (Py_TYPE(su) != &PySuper_Type)
6580 /* If su is an instance of a (strict) subclass of super,
6581 call its type */
6582 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
6583 su->type, obj, NULL);
6584 else {
6585 /* Inline the common case */
6586 PyTypeObject *obj_type = supercheck(su->type, obj);
6587 if (obj_type == NULL)
6588 return NULL;
6589 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
6590 NULL, NULL);
6591 if (newobj == NULL)
6592 return NULL;
6593 Py_INCREF(su->type);
6594 Py_INCREF(obj);
6595 newobj->type = su->type;
6596 newobj->obj = obj;
6597 newobj->obj_type = obj_type;
6598 return (PyObject *)newobj;
6602 static int
6603 super_init(PyObject *self, PyObject *args, PyObject *kwds)
6605 superobject *su = (superobject *)self;
6606 PyTypeObject *type;
6607 PyObject *obj = NULL;
6608 PyTypeObject *obj_type = NULL;
6610 if (!_PyArg_NoKeywords("super", kwds))
6611 return -1;
6612 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6613 return -1;
6614 if (obj == Py_None)
6615 obj = NULL;
6616 if (obj != NULL) {
6617 obj_type = supercheck(type, obj);
6618 if (obj_type == NULL)
6619 return -1;
6620 Py_INCREF(obj);
6622 Py_INCREF(type);
6623 su->type = type;
6624 su->obj = obj;
6625 su->obj_type = obj_type;
6626 return 0;
6629 PyDoc_STRVAR(super_doc,
6630 "super(type) -> unbound super object\n"
6631 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
6632 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
6633 "Typical use to call a cooperative superclass method:\n"
6634 "class C(B):\n"
6635 " def meth(self, arg):\n"
6636 " super(C, self).meth(arg)");
6638 static int
6639 super_traverse(PyObject *self, visitproc visit, void *arg)
6641 superobject *su = (superobject *)self;
6643 Py_VISIT(su->obj);
6644 Py_VISIT(su->type);
6645 Py_VISIT(su->obj_type);
6647 return 0;
6650 PyTypeObject PySuper_Type = {
6651 PyVarObject_HEAD_INIT(&PyType_Type, 0)
6652 "super", /* tp_name */
6653 sizeof(superobject), /* tp_basicsize */
6654 0, /* tp_itemsize */
6655 /* methods */
6656 super_dealloc, /* tp_dealloc */
6657 0, /* tp_print */
6658 0, /* tp_getattr */
6659 0, /* tp_setattr */
6660 0, /* tp_compare */
6661 super_repr, /* tp_repr */
6662 0, /* tp_as_number */
6663 0, /* tp_as_sequence */
6664 0, /* tp_as_mapping */
6665 0, /* tp_hash */
6666 0, /* tp_call */
6667 0, /* tp_str */
6668 super_getattro, /* tp_getattro */
6669 0, /* tp_setattro */
6670 0, /* tp_as_buffer */
6671 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6672 Py_TPFLAGS_BASETYPE, /* tp_flags */
6673 super_doc, /* tp_doc */
6674 super_traverse, /* tp_traverse */
6675 0, /* tp_clear */
6676 0, /* tp_richcompare */
6677 0, /* tp_weaklistoffset */
6678 0, /* tp_iter */
6679 0, /* tp_iternext */
6680 0, /* tp_methods */
6681 super_members, /* tp_members */
6682 0, /* tp_getset */
6683 0, /* tp_base */
6684 0, /* tp_dict */
6685 super_descr_get, /* tp_descr_get */
6686 0, /* tp_descr_set */
6687 0, /* tp_dictoffset */
6688 super_init, /* tp_init */
6689 PyType_GenericAlloc, /* tp_alloc */
6690 PyType_GenericNew, /* tp_new */
6691 PyObject_GC_Del, /* tp_free */