1/* Type object implementation */
2
3#include "Python.h"
4#include "frameobject.h"
5#include "structmember.h"
6
7#include <ctype.h>
8
9
10/* Support type attribute cache */
11
12/* The cache can keep references to the names alive for longer than
13   they normally would.  This is why the maximum size is limited to
14   MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
15   strings are used as attribute names. */
16#define MCACHE_MAX_ATTR_SIZE    100
17#define MCACHE_SIZE_EXP         12
18#define MCACHE_HASH(version, name_hash)                                 \
19        (((unsigned int)(version) ^ (unsigned int)(name_hash))          \
20         & ((1 << MCACHE_SIZE_EXP) - 1))
21
22#define MCACHE_HASH_METHOD(type, name)                                  \
23        MCACHE_HASH((type)->tp_version_tag,                     \
24                    ((PyASCIIObject *)(name))->hash)
25#define MCACHE_CACHEABLE_NAME(name)                                     \
26        PyUnicode_CheckExact(name) &&                            \
27        PyUnicode_READY(name) != -1 &&                      \
28        PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
29
30struct method_cache_entry {
31    unsigned int version;
32    PyObject *name;             /* reference to exactly a str or None */
33    PyObject *value;            /* borrowed */
34};
35
36static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
37static unsigned int next_version_tag = 0;
38
39#define MCACHE_STATS 0
40
41#if MCACHE_STATS
42static size_t method_cache_hits = 0;
43static size_t method_cache_misses = 0;
44static size_t method_cache_collisions = 0;
45#endif
46
47/* alphabetical order */
48_Py_IDENTIFIER(__abstractmethods__);
49_Py_IDENTIFIER(__class__);
50_Py_IDENTIFIER(__delitem__);
51_Py_IDENTIFIER(__dict__);
52_Py_IDENTIFIER(__doc__);
53_Py_IDENTIFIER(__getattribute__);
54_Py_IDENTIFIER(__getitem__);
55_Py_IDENTIFIER(__hash__);
56_Py_IDENTIFIER(__init_subclass__);
57_Py_IDENTIFIER(__len__);
58_Py_IDENTIFIER(__module__);
59_Py_IDENTIFIER(__name__);
60_Py_IDENTIFIER(__new__);
61_Py_IDENTIFIER(__set_name__);
62_Py_IDENTIFIER(__setitem__);
63_Py_IDENTIFIER(builtins);
64
65static PyObject *
66slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
67
68static void
69clear_slotdefs(void);
70
71/*
72 * finds the beginning of the docstring's introspection signature.
73 * if present, returns a pointer pointing to the first '('.
74 * otherwise returns NULL.
75 *
76 * doesn't guarantee that the signature is valid, only that it
77 * has a valid prefix.  (the signature must also pass skip_signature.)
78 */
79static const char *
80find_signature(const char *name, const char *doc)
81{
82    const char *dot;
83    size_t length;
84
85    if (!doc)
86        return NULL;
87
88    assert(name != NULL);
89
90    /* for dotted names like classes, only use the last component */
91    dot = strrchr(name, '.');
92    if (dot)
93        name = dot + 1;
94
95    length = strlen(name);
96    if (strncmp(doc, name, length))
97        return NULL;
98    doc += length;
99    if (*doc != '(')
100        return NULL;
101    return doc;
102}
103
104#define SIGNATURE_END_MARKER         ")\n--\n\n"
105#define SIGNATURE_END_MARKER_LENGTH  6
106/*
107 * skips past the end of the docstring's instrospection signature.
108 * (assumes doc starts with a valid signature prefix.)
109 */
110static const char *
111skip_signature(const char *doc)
112{
113    while (*doc) {
114        if ((*doc == *SIGNATURE_END_MARKER) &&
115            !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH))
116            return doc + SIGNATURE_END_MARKER_LENGTH;
117        if ((*doc == '\n') && (doc[1] == '\n'))
118            return NULL;
119        doc++;
120    }
121    return NULL;
122}
123
124static const char *
125_PyType_DocWithoutSignature(const char *name, const char *internal_doc)
126{
127    const char *doc = find_signature(name, internal_doc);
128
129    if (doc) {
130        doc = skip_signature(doc);
131        if (doc)
132            return doc;
133        }
134    return internal_doc;
135}
136
137PyObject *
138_PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
139{
140    const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
141
142    if (!doc || *doc == '\0') {
143        Py_INCREF(Py_None);
144        return Py_None;
145    }
146
147    return PyUnicode_FromString(doc);
148}
149
150PyObject *
151_PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc)
152{
153    const char *start = find_signature(name, internal_doc);
154    const char *end;
155
156    if (start)
157        end = skip_signature(start);
158    else
159        end = NULL;
160    if (!end) {
161        Py_INCREF(Py_None);
162        return Py_None;
163    }
164
165    /* back "end" up until it points just past the final ')' */
166    end -= SIGNATURE_END_MARKER_LENGTH - 1;
167    assert((end - start) >= 2); /* should be "()" at least */
168    assert(end[-1] == ')');
169    assert(end[0] == '\n');
170    return PyUnicode_FromStringAndSize(start, end - start);
171}
172
173unsigned int
174PyType_ClearCache(void)
175{
176    Py_ssize_t i;
177    unsigned int cur_version_tag = next_version_tag - 1;
178
179#if MCACHE_STATS
180    size_t total = method_cache_hits + method_cache_collisions + method_cache_misses;
181    fprintf(stderr, "-- Method cache hits        = %zd (%d%%)\n",
182            method_cache_hits, (int) (100.0 * method_cache_hits / total));
183    fprintf(stderr, "-- Method cache true misses = %zd (%d%%)\n",
184            method_cache_misses, (int) (100.0 * method_cache_misses / total));
185    fprintf(stderr, "-- Method cache collisions  = %zd (%d%%)\n",
186            method_cache_collisions, (int) (100.0 * method_cache_collisions / total));
187    fprintf(stderr, "-- Method cache size        = %zd KB\n",
188            sizeof(method_cache) / 1024);
189#endif
190
191    for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
192        method_cache[i].version = 0;
193        Py_CLEAR(method_cache[i].name);
194        method_cache[i].value = NULL;
195    }
196    next_version_tag = 0;
197    /* mark all version tags as invalid */
198    PyType_Modified(&PyBaseObject_Type);
199    return cur_version_tag;
200}
201
202void
203_PyType_Fini(void)
204{
205    PyType_ClearCache();
206    clear_slotdefs();
207}
208
209void
210PyType_Modified(PyTypeObject *type)
211{
212    /* Invalidate any cached data for the specified type and all
213       subclasses.  This function is called after the base
214       classes, mro, or attributes of the type are altered.
215
216       Invariants:
217
218       - Py_TPFLAGS_VALID_VERSION_TAG is never set if
219         Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
220         objects coming from non-recompiled extension modules)
221
222       - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
223         it must first be set on all super types.
224
225       This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
226       type (so it must first clear it on all subclasses).  The
227       tp_version_tag value is meaningless unless this flag is set.
228       We don't assign new version tags eagerly, but only as
229       needed.
230     */
231    PyObject *raw, *ref;
232    Py_ssize_t i;
233
234    if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
235        return;
236
237    raw = type->tp_subclasses;
238    if (raw != NULL) {
239        assert(PyDict_CheckExact(raw));
240        i = 0;
241        while (PyDict_Next(raw, &i, NULL, &ref)) {
242            assert(PyWeakref_CheckRef(ref));
243            ref = PyWeakref_GET_OBJECT(ref);
244            if (ref != Py_None) {
245                PyType_Modified((PyTypeObject *)ref);
246            }
247        }
248    }
249    type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
250}
251
252static void
253type_mro_modified(PyTypeObject *type, PyObject *bases) {
254    /*
255       Check that all base classes or elements of the MRO of type are
256       able to be cached.  This function is called after the base
257       classes or mro of the type are altered.
258
259       Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
260       has a custom MRO that includes a type which is not officially
261       super type.
262
263       Called from mro_internal, which will subsequently be called on
264       each subclass when their mro is recursively updated.
265     */
266    Py_ssize_t i, n;
267    int clear = 0;
268
269    if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
270        return;
271
272    n = PyTuple_GET_SIZE(bases);
273    for (i = 0; i < n; i++) {
274        PyObject *b = PyTuple_GET_ITEM(bases, i);
275        PyTypeObject *cls;
276
277        assert(PyType_Check(b));
278        cls = (PyTypeObject *)b;
279
280        if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
281            !PyType_IsSubtype(type, cls)) {
282            clear = 1;
283            break;
284        }
285    }
286
287    if (clear)
288        type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
289                            Py_TPFLAGS_VALID_VERSION_TAG);
290}
291
292static int
293assign_version_tag(PyTypeObject *type)
294{
295    /* Ensure that the tp_version_tag is valid and set
296       Py_TPFLAGS_VALID_VERSION_TAG.  To respect the invariant, this
297       must first be done on all super classes.  Return 0 if this
298       cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
299    */
300    Py_ssize_t i, n;
301    PyObject *bases;
302
303    if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
304        return 1;
305    if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
306        return 0;
307    if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
308        return 0;
309
310    type->tp_version_tag = next_version_tag++;
311    /* for stress-testing: next_version_tag &= 0xFF; */
312
313    if (type->tp_version_tag == 0) {
314        /* wrap-around or just starting Python - clear the whole
315           cache by filling names with references to Py_None.
316           Values are also set to NULL for added protection, as they
317           are borrowed reference */
318        for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
319            method_cache[i].value = NULL;
320            Py_INCREF(Py_None);
321            Py_XSETREF(method_cache[i].name, Py_None);
322        }
323        /* mark all version tags as invalid */
324        PyType_Modified(&PyBaseObject_Type);
325        return 1;
326    }
327    bases = type->tp_bases;
328    n = PyTuple_GET_SIZE(bases);
329    for (i = 0; i < n; i++) {
330        PyObject *b = PyTuple_GET_ITEM(bases, i);
331        assert(PyType_Check(b));
332        if (!assign_version_tag((PyTypeObject *)b))
333            return 0;
334    }
335    type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
336    return 1;
337}
338
339
340static PyMemberDef type_members[] = {
341    {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY},
342    {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY},
343    {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
344    {"__weakrefoffset__", T_LONG,
345     offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
346    {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
347    {"__dictoffset__", T_LONG,
348     offsetof(PyTypeObject, tp_dictoffset), READONLY},
349    {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
350    {0}
351};
352
353static int
354check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name)
355{
356    if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
357        PyErr_Format(PyExc_TypeError,
358                     "can't set %s.%s", type->tp_name, name);
359        return 0;
360    }
361    if (!value) {
362        PyErr_Format(PyExc_TypeError,
363                     "can't delete %s.%s", type->tp_name, name);
364        return 0;
365    }
366    return 1;
367}
368
369static PyObject *
370type_name(PyTypeObject *type, void *context)
371{
372    const char *s;
373
374    if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
375        PyHeapTypeObject* et = (PyHeapTypeObject*)type;
376
377        Py_INCREF(et->ht_name);
378        return et->ht_name;
379    }
380    else {
381        s = strrchr(type->tp_name, '.');
382        if (s == NULL)
383            s = type->tp_name;
384        else
385            s++;
386        return PyUnicode_FromString(s);
387    }
388}
389
390static PyObject *
391type_qualname(PyTypeObject *type, void *context)
392{
393    if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
394        PyHeapTypeObject* et = (PyHeapTypeObject*)type;
395        Py_INCREF(et->ht_qualname);
396        return et->ht_qualname;
397    }
398    else {
399        return type_name(type, context);
400    }
401}
402
403static int
404type_set_name(PyTypeObject *type, PyObject *value, void *context)
405{
406    const char *tp_name;
407    Py_ssize_t name_size;
408
409    if (!check_set_special_type_attr(type, value, "__name__"))
410        return -1;
411    if (!PyUnicode_Check(value)) {
412        PyErr_Format(PyExc_TypeError,
413                     "can only assign string to %s.__name__, not '%s'",
414                     type->tp_name, Py_TYPE(value)->tp_name);
415        return -1;
416    }
417
418    tp_name = PyUnicode_AsUTF8AndSize(value, &name_size);
419    if (tp_name == NULL)
420        return -1;
421    if (strlen(tp_name) != (size_t)name_size) {
422        PyErr_SetString(PyExc_ValueError,
423                        "type name must not contain null characters");
424        return -1;
425    }
426
427    type->tp_name = tp_name;
428    Py_INCREF(value);
429    Py_SETREF(((PyHeapTypeObject*)type)->ht_name, value);
430
431    return 0;
432}
433
434static int
435type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
436{
437    PyHeapTypeObject* et;
438
439    if (!check_set_special_type_attr(type, value, "__qualname__"))
440        return -1;
441    if (!PyUnicode_Check(value)) {
442        PyErr_Format(PyExc_TypeError,
443                     "can only assign string to %s.__qualname__, not '%s'",
444                     type->tp_name, Py_TYPE(value)->tp_name);
445        return -1;
446    }
447
448    et = (PyHeapTypeObject*)type;
449    Py_INCREF(value);
450    Py_SETREF(et->ht_qualname, value);
451    return 0;
452}
453
454static PyObject *
455type_module(PyTypeObject *type, void *context)
456{
457    PyObject *mod;
458
459    if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
460        mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
461        if (mod == NULL) {
462            PyErr_Format(PyExc_AttributeError, "__module__");
463            return NULL;
464        }
465        Py_INCREF(mod);
466    }
467    else {
468        const char *s = strrchr(type->tp_name, '.');
469        if (s != NULL) {
470            mod = PyUnicode_FromStringAndSize(
471                type->tp_name, (Py_ssize_t)(s - type->tp_name));
472            if (mod != NULL)
473                PyUnicode_InternInPlace(&mod);
474        }
475        else {
476            mod = _PyUnicode_FromId(&PyId_builtins);
477            Py_XINCREF(mod);
478        }
479    }
480    return mod;
481}
482
483static int
484type_set_module(PyTypeObject *type, PyObject *value, void *context)
485{
486    if (!check_set_special_type_attr(type, value, "__module__"))
487        return -1;
488
489    PyType_Modified(type);
490
491    return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
492}
493
494static PyObject *
495type_abstractmethods(PyTypeObject *type, void *context)
496{
497    PyObject *mod = NULL;
498    /* type itself has an __abstractmethods__ descriptor (this). Don't return
499       that. */
500    if (type != &PyType_Type)
501        mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
502    if (!mod) {
503        PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
504        if (message)
505            PyErr_SetObject(PyExc_AttributeError, message);
506        return NULL;
507    }
508    Py_INCREF(mod);
509    return mod;
510}
511
512static int
513type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
514{
515    /* __abstractmethods__ should only be set once on a type, in
516       abc.ABCMeta.__new__, so this function doesn't do anything
517       special to update subclasses.
518    */
519    int abstract, res;
520    if (value != NULL) {
521        abstract = PyObject_IsTrue(value);
522        if (abstract < 0)
523            return -1;
524        res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value);
525    }
526    else {
527        abstract = 0;
528        res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__);
529        if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
530            PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
531            if (message)
532                PyErr_SetObject(PyExc_AttributeError, message);
533            return -1;
534        }
535    }
536    if (res == 0) {
537        PyType_Modified(type);
538        if (abstract)
539            type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
540        else
541            type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
542    }
543    return res;
544}
545
546static PyObject *
547type_get_bases(PyTypeObject *type, void *context)
548{
549    Py_INCREF(type->tp_bases);
550    return type->tp_bases;
551}
552
553static PyTypeObject *best_base(PyObject *);
554static int mro_internal(PyTypeObject *, PyObject **);
555static int type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
556static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, const char *);
557static int add_subclass(PyTypeObject*, PyTypeObject*);
558static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
559static void remove_subclass(PyTypeObject *, PyTypeObject *);
560static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
561static void update_all_slots(PyTypeObject *);
562
563typedef int (*update_callback)(PyTypeObject *, void *);
564static int update_subclasses(PyTypeObject *type, PyObject *name,
565                             update_callback callback, void *data);
566static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
567                                   update_callback callback, void *data);
568static PyObject *type_subclasses(PyTypeObject *type, PyObject *ignored);
569
570static int
571mro_hierarchy(PyTypeObject *type, PyObject *temp)
572{
573    int res;
574    PyObject *new_mro, *old_mro;
575    PyObject *tuple;
576    PyObject *subclasses;
577    Py_ssize_t i, n;
578
579    res = mro_internal(type, &old_mro);
580    if (res <= 0)
581        /* error / reentrance */
582        return res;
583    new_mro = type->tp_mro;
584
585    if (old_mro != NULL)
586        tuple = PyTuple_Pack(3, type, new_mro, old_mro);
587    else
588        tuple = PyTuple_Pack(2, type, new_mro);
589
590    if (tuple != NULL)
591        res = PyList_Append(temp, tuple);
592    else
593        res = -1;
594    Py_XDECREF(tuple);
595
596    if (res < 0) {
597        type->tp_mro = old_mro;
598        Py_DECREF(new_mro);
599        return -1;
600    }
601    Py_XDECREF(old_mro);
602
603    /* Obtain a copy of subclasses list to iterate over.
604
605       Otherwise type->tp_subclasses might be altered
606       in the middle of the loop, for example, through a custom mro(),
607       by invoking type_set_bases on some subclass of the type
608       which in turn calls remove_subclass/add_subclass on this type.
609
610       Finally, this makes things simple avoiding the need to deal
611       with dictionary iterators and weak references.
612    */
613    subclasses = type_subclasses(type, NULL);
614    if (subclasses == NULL)
615        return -1;
616    n = PyList_GET_SIZE(subclasses);
617    for (i = 0; i < n; i++) {
618        PyTypeObject *subclass;
619        subclass = (PyTypeObject *)PyList_GET_ITEM(subclasses, i);
620        res = mro_hierarchy(subclass, temp);
621        if (res < 0)
622            break;
623    }
624    Py_DECREF(subclasses);
625
626    return res;
627}
628
629static int
630type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context)
631{
632    int res = 0;
633    PyObject *temp;
634    PyObject *old_bases;
635    PyTypeObject *new_base, *old_base;
636    Py_ssize_t i;
637
638    if (!check_set_special_type_attr(type, new_bases, "__bases__"))
639        return -1;
640    if (!PyTuple_Check(new_bases)) {
641        PyErr_Format(PyExc_TypeError,
642             "can only assign tuple to %s.__bases__, not %s",
643                 type->tp_name, Py_TYPE(new_bases)->tp_name);
644        return -1;
645    }
646    if (PyTuple_GET_SIZE(new_bases) == 0) {
647        PyErr_Format(PyExc_TypeError,
648             "can only assign non-empty tuple to %s.__bases__, not ()",
649                 type->tp_name);
650        return -1;
651    }
652    for (i = 0; i < PyTuple_GET_SIZE(new_bases); i++) {
653        PyObject *ob;
654        PyTypeObject *base;
655
656        ob = PyTuple_GET_ITEM(new_bases, i);
657        if (!PyType_Check(ob)) {
658            PyErr_Format(PyExc_TypeError,
659                         "%s.__bases__ must be tuple of classes, not '%s'",
660                         type->tp_name, Py_TYPE(ob)->tp_name);
661            return -1;
662        }
663
664        base = (PyTypeObject*)ob;
665        if (PyType_IsSubtype(base, type) ||
666            /* In case of reentering here again through a custom mro()
667               the above check is not enough since it relies on
668               base->tp_mro which would gonna be updated inside
669               mro_internal only upon returning from the mro().
670
671               However, base->tp_base has already been assigned (see
672               below), which in turn may cause an inheritance cycle
673               through tp_base chain.  And this is definitely
674               not what you want to ever happen.  */
675            (base->tp_mro != NULL && type_is_subtype_base_chain(base, type))) {
676
677            PyErr_SetString(PyExc_TypeError,
678                            "a __bases__ item causes an inheritance cycle");
679            return -1;
680        }
681    }
682
683    new_base = best_base(new_bases);
684    if (new_base == NULL)
685        return -1;
686
687    if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
688        return -1;
689
690    Py_INCREF(new_bases);
691    Py_INCREF(new_base);
692
693    old_bases = type->tp_bases;
694    old_base = type->tp_base;
695
696    type->tp_bases = new_bases;
697    type->tp_base = new_base;
698
699    temp = PyList_New(0);
700    if (temp == NULL)
701        goto bail;
702    if (mro_hierarchy(type, temp) < 0)
703        goto undo;
704    Py_DECREF(temp);
705
706    /* Take no action in case if type->tp_bases has been replaced
707       through reentrance.  */
708    if (type->tp_bases == new_bases) {
709        /* any base that was in __bases__ but now isn't, we
710           need to remove |type| from its tp_subclasses.
711           conversely, any class now in __bases__ that wasn't
712           needs to have |type| added to its subclasses. */
713
714        /* for now, sod that: just remove from all old_bases,
715           add to all new_bases */
716        remove_all_subclasses(type, old_bases);
717        res = add_all_subclasses(type, new_bases);
718        update_all_slots(type);
719    }
720
721    Py_DECREF(old_bases);
722    Py_DECREF(old_base);
723
724    return res;
725
726  undo:
727    for (i = PyList_GET_SIZE(temp) - 1; i >= 0; i--) {
728        PyTypeObject *cls;
729        PyObject *new_mro, *old_mro = NULL;
730
731        PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
732                          "", 2, 3, &cls, &new_mro, &old_mro);
733        /* Do not rollback if cls has a newer version of MRO.  */
734        if (cls->tp_mro == new_mro) {
735            Py_XINCREF(old_mro);
736            cls->tp_mro = old_mro;
737            Py_DECREF(new_mro);
738        }
739    }
740    Py_DECREF(temp);
741
742  bail:
743    if (type->tp_bases == new_bases) {
744        assert(type->tp_base == new_base);
745
746        type->tp_bases = old_bases;
747        type->tp_base = old_base;
748
749        Py_DECREF(new_bases);
750        Py_DECREF(new_base);
751    }
752    else {
753        Py_DECREF(old_bases);
754        Py_DECREF(old_base);
755    }
756
757    return -1;
758}
759
760static PyObject *
761type_dict(PyTypeObject *type, void *context)
762{
763    if (type->tp_dict == NULL) {
764        Py_INCREF(Py_None);
765        return Py_None;
766    }
767    return PyDictProxy_New(type->tp_dict);
768}
769
770static PyObject *
771type_get_doc(PyTypeObject *type, void *context)
772{
773    PyObject *result;
774    if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) {
775        return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc);
776    }
777    result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__);
778    if (result == NULL) {
779        result = Py_None;
780        Py_INCREF(result);
781    }
782    else if (Py_TYPE(result)->tp_descr_get) {
783        result = Py_TYPE(result)->tp_descr_get(result, NULL,
784                                               (PyObject *)type);
785    }
786    else {
787        Py_INCREF(result);
788    }
789    return result;
790}
791
792static PyObject *
793type_get_text_signature(PyTypeObject *type, void *context)
794{
795    return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc);
796}
797
798static int
799type_set_doc(PyTypeObject *type, PyObject *value, void *context)
800{
801    if (!check_set_special_type_attr(type, value, "__doc__"))
802        return -1;
803    PyType_Modified(type);
804    return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value);
805}
806
807static PyObject *
808type___instancecheck__(PyObject *type, PyObject *inst)
809{
810    switch (_PyObject_RealIsInstance(inst, type)) {
811    case -1:
812        return NULL;
813    case 0:
814        Py_RETURN_FALSE;
815    default:
816        Py_RETURN_TRUE;
817    }
818}
819
820
821static PyObject *
822type___subclasscheck__(PyObject *type, PyObject *inst)
823{
824    switch (_PyObject_RealIsSubclass(inst, type)) {
825    case -1:
826        return NULL;
827    case 0:
828        Py_RETURN_FALSE;
829    default:
830        Py_RETURN_TRUE;
831    }
832}
833
834
835static PyGetSetDef type_getsets[] = {
836    {"__name__", (getter)type_name, (setter)type_set_name, NULL},
837    {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL},
838    {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
839    {"__module__", (getter)type_module, (setter)type_set_module, NULL},
840    {"__abstractmethods__", (getter)type_abstractmethods,
841     (setter)type_set_abstractmethods, NULL},
842    {"__dict__",  (getter)type_dict,  NULL, NULL},
843    {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL},
844    {"__text_signature__", (getter)type_get_text_signature, NULL, NULL},
845    {0}
846};
847
848static PyObject *
849type_repr(PyTypeObject *type)
850{
851    PyObject *mod, *name, *rtn;
852
853    mod = type_module(type, NULL);
854    if (mod == NULL)
855        PyErr_Clear();
856    else if (!PyUnicode_Check(mod)) {
857        Py_DECREF(mod);
858        mod = NULL;
859    }
860    name = type_qualname(type, NULL);
861    if (name == NULL) {
862        Py_XDECREF(mod);
863        return NULL;
864    }
865
866    if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
867        rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
868    else
869        rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
870
871    Py_XDECREF(mod);
872    Py_DECREF(name);
873    return rtn;
874}
875
876static PyObject *
877type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
878{
879    PyObject *obj;
880
881    if (type->tp_new == NULL) {
882        PyErr_Format(PyExc_TypeError,
883                     "cannot create '%.100s' instances",
884                     type->tp_name);
885        return NULL;
886    }
887
888#ifdef Py_DEBUG
889    /* type_call() must not be called with an exception set,
890       because it may clear it (directly or indirectly) and so the
891       caller loses its exception */
892    assert(!PyErr_Occurred());
893#endif
894
895    obj = type->tp_new(type, args, kwds);
896    obj = _Py_CheckFunctionResult((PyObject*)type, obj, NULL);
897    if (obj == NULL)
898        return NULL;
899
900    /* Ugly exception: when the call was type(something),
901       don't call tp_init on the result. */
902    if (type == &PyType_Type &&
903        PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
904        (kwds == NULL ||
905         (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
906        return obj;
907
908    /* If the returned object is not an instance of type,
909       it won't be initialized. */
910    if (!PyType_IsSubtype(Py_TYPE(obj), type))
911        return obj;
912
913    type = Py_TYPE(obj);
914    if (type->tp_init != NULL) {
915        int res = type->tp_init(obj, args, kwds);
916        if (res < 0) {
917            assert(PyErr_Occurred());
918            Py_DECREF(obj);
919            obj = NULL;
920        }
921        else {
922            assert(!PyErr_Occurred());
923        }
924    }
925    return obj;
926}
927
928PyObject *
929PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
930{
931    PyObject *obj;
932    const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
933    /* note that we need to add one, for the sentinel */
934
935    if (PyType_IS_GC(type))
936        obj = _PyObject_GC_Malloc(size);
937    else
938        obj = (PyObject *)PyObject_MALLOC(size);
939
940    if (obj == NULL)
941        return PyErr_NoMemory();
942
943    memset(obj, '\0', size);
944
945    if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
946        Py_INCREF(type);
947
948    if (type->tp_itemsize == 0)
949        (void)PyObject_INIT(obj, type);
950    else
951        (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
952
953    if (PyType_IS_GC(type))
954        _PyObject_GC_TRACK(obj);
955    return obj;
956}
957
958PyObject *
959PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
960{
961    return type->tp_alloc(type, 0);
962}
963
964/* Helpers for subtyping */
965
966static int
967traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
968{
969    Py_ssize_t i, n;
970    PyMemberDef *mp;
971
972    n = Py_SIZE(type);
973    mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
974    for (i = 0; i < n; i++, mp++) {
975        if (mp->type == T_OBJECT_EX) {
976            char *addr = (char *)self + mp->offset;
977            PyObject *obj = *(PyObject **)addr;
978            if (obj != NULL) {
979                int err = visit(obj, arg);
980                if (err)
981                    return err;
982            }
983        }
984    }
985    return 0;
986}
987
988static int
989subtype_traverse(PyObject *self, visitproc visit, void *arg)
990{
991    PyTypeObject *type, *base;
992    traverseproc basetraverse;
993
994    /* Find the nearest base with a different tp_traverse,
995       and traverse slots while we're at it */
996    type = Py_TYPE(self);
997    base = type;
998    while ((basetraverse = base->tp_traverse) == subtype_traverse) {
999        if (Py_SIZE(base)) {
1000            int err = traverse_slots(base, self, visit, arg);
1001            if (err)
1002                return err;
1003        }
1004        base = base->tp_base;
1005        assert(base);
1006    }
1007
1008    if (type->tp_dictoffset != base->tp_dictoffset) {
1009        PyObject **dictptr = _PyObject_GetDictPtr(self);
1010        if (dictptr && *dictptr)
1011            Py_VISIT(*dictptr);
1012    }
1013
1014    if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1015        /* For a heaptype, the instances count as references
1016           to the type.          Traverse the type so the collector
1017           can find cycles involving this link. */
1018        Py_VISIT(type);
1019
1020    if (basetraverse)
1021        return basetraverse(self, visit, arg);
1022    return 0;
1023}
1024
1025static void
1026clear_slots(PyTypeObject *type, PyObject *self)
1027{
1028    Py_ssize_t i, n;
1029    PyMemberDef *mp;
1030
1031    n = Py_SIZE(type);
1032    mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
1033    for (i = 0; i < n; i++, mp++) {
1034        if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
1035            char *addr = (char *)self + mp->offset;
1036            PyObject *obj = *(PyObject **)addr;
1037            if (obj != NULL) {
1038                *(PyObject **)addr = NULL;
1039                Py_DECREF(obj);
1040            }
1041        }
1042    }
1043}
1044
1045static int
1046subtype_clear(PyObject *self)
1047{
1048    PyTypeObject *type, *base;
1049    inquiry baseclear;
1050
1051    /* Find the nearest base with a different tp_clear
1052       and clear slots while we're at it */
1053    type = Py_TYPE(self);
1054    base = type;
1055    while ((baseclear = base->tp_clear) == subtype_clear) {
1056        if (Py_SIZE(base))
1057            clear_slots(base, self);
1058        base = base->tp_base;
1059        assert(base);
1060    }
1061
1062    /* Clear the instance dict (if any), to break cycles involving only
1063       __dict__ slots (as in the case 'self.__dict__ is self'). */
1064    if (type->tp_dictoffset != base->tp_dictoffset) {
1065        PyObject **dictptr = _PyObject_GetDictPtr(self);
1066        if (dictptr && *dictptr)
1067            Py_CLEAR(*dictptr);
1068    }
1069
1070    if (baseclear)
1071        return baseclear(self);
1072    return 0;
1073}
1074
1075static void
1076subtype_dealloc(PyObject *self)
1077{
1078    PyTypeObject *type, *base;
1079    destructor basedealloc;
1080    PyThreadState *tstate = PyThreadState_GET();
1081    int has_finalizer;
1082
1083    /* Extract the type; we expect it to be a heap type */
1084    type = Py_TYPE(self);
1085    assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1086
1087    /* Test whether the type has GC exactly once */
1088
1089    if (!PyType_IS_GC(type)) {
1090        /* It's really rare to find a dynamic type that doesn't have
1091           GC; it can only happen when deriving from 'object' and not
1092           adding any slots or instance variables.  This allows
1093           certain simplifications: there's no need to call
1094           clear_slots(), or DECREF the dict, or clear weakrefs. */
1095
1096        /* Maybe call finalizer; exit early if resurrected */
1097        if (type->tp_finalize) {
1098            if (PyObject_CallFinalizerFromDealloc(self) < 0)
1099                return;
1100        }
1101        if (type->tp_del) {
1102            type->tp_del(self);
1103            if (self->ob_refcnt > 0)
1104                return;
1105        }
1106
1107        /* Find the nearest base with a different tp_dealloc */
1108        base = type;
1109        while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1110            assert(Py_SIZE(base) == 0);
1111            base = base->tp_base;
1112            assert(base);
1113        }
1114
1115        /* Extract the type again; tp_del may have changed it */
1116        type = Py_TYPE(self);
1117
1118        /* Call the base tp_dealloc() */
1119        assert(basedealloc);
1120        basedealloc(self);
1121
1122        /* Can't reference self beyond this point */
1123        Py_DECREF(type);
1124
1125        /* Done */
1126        return;
1127    }
1128
1129    /* We get here only if the type has GC */
1130
1131    /* UnTrack and re-Track around the trashcan macro, alas */
1132    /* See explanation at end of function for full disclosure */
1133    PyObject_GC_UnTrack(self);
1134    ++_PyTrash_delete_nesting;
1135    ++ tstate->trash_delete_nesting;
1136    Py_TRASHCAN_SAFE_BEGIN(self);
1137    --_PyTrash_delete_nesting;
1138    -- tstate->trash_delete_nesting;
1139
1140    /* Find the nearest base with a different tp_dealloc */
1141    base = type;
1142    while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
1143        base = base->tp_base;
1144        assert(base);
1145    }
1146
1147    has_finalizer = type->tp_finalize || type->tp_del;
1148
1149    if (type->tp_finalize) {
1150        _PyObject_GC_TRACK(self);
1151        if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1152            /* Resurrected */
1153            goto endlabel;
1154        }
1155        _PyObject_GC_UNTRACK(self);
1156    }
1157    /*
1158      If we added a weaklist, we clear it. Do this *before* calling tp_del,
1159      clearing slots, or clearing the instance dict.
1160
1161      GC tracking must be off at this point. weakref callbacks (if any, and
1162      whether directly here or indirectly in something we call) may trigger GC,
1163      and if self is tracked at that point, it will look like trash to GC and GC
1164      will try to delete self again.
1165    */
1166    if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1167        PyObject_ClearWeakRefs(self);
1168
1169    if (type->tp_del) {
1170        _PyObject_GC_TRACK(self);
1171        type->tp_del(self);
1172        if (self->ob_refcnt > 0) {
1173            /* Resurrected */
1174            goto endlabel;
1175        }
1176        _PyObject_GC_UNTRACK(self);
1177    }
1178    if (has_finalizer) {
1179        /* New weakrefs could be created during the finalizer call.
1180           If this occurs, clear them out without calling their
1181           finalizers since they might rely on part of the object
1182           being finalized that has already been destroyed. */
1183        if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1184            /* Modeled after GET_WEAKREFS_LISTPTR() */
1185            PyWeakReference **list = (PyWeakReference **) \
1186                PyObject_GET_WEAKREFS_LISTPTR(self);
1187            while (*list)
1188                _PyWeakref_ClearRef(*list);
1189        }
1190    }
1191
1192    /*  Clear slots up to the nearest base with a different tp_dealloc */
1193    base = type;
1194    while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
1195        if (Py_SIZE(base))
1196            clear_slots(base, self);
1197        base = base->tp_base;
1198        assert(base);
1199    }
1200
1201    /* If we added a dict, DECREF it */
1202    if (type->tp_dictoffset && !base->tp_dictoffset) {
1203        PyObject **dictptr = _PyObject_GetDictPtr(self);
1204        if (dictptr != NULL) {
1205            PyObject *dict = *dictptr;
1206            if (dict != NULL) {
1207                Py_DECREF(dict);
1208                *dictptr = NULL;
1209            }
1210        }
1211    }
1212
1213    /* Extract the type again; tp_del may have changed it */
1214    type = Py_TYPE(self);
1215
1216    /* Call the base tp_dealloc(); first retrack self if
1217     * basedealloc knows about gc.
1218     */
1219    if (PyType_IS_GC(base))
1220        _PyObject_GC_TRACK(self);
1221    assert(basedealloc);
1222    basedealloc(self);
1223
1224    /* Can't reference self beyond this point. It's possible tp_del switched
1225       our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about
1226       reference counting. */
1227    if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
1228      Py_DECREF(type);
1229
1230  endlabel:
1231    ++_PyTrash_delete_nesting;
1232    ++ tstate->trash_delete_nesting;
1233    Py_TRASHCAN_SAFE_END(self);
1234    --_PyTrash_delete_nesting;
1235    -- tstate->trash_delete_nesting;
1236
1237    /* Explanation of the weirdness around the trashcan macros:
1238
1239       Q. What do the trashcan macros do?
1240
1241       A. Read the comment titled "Trashcan mechanism" in object.h.
1242          For one, this explains why there must be a call to GC-untrack
1243          before the trashcan begin macro.      Without understanding the
1244          trashcan code, the answers to the following questions don't make
1245          sense.
1246
1247       Q. Why do we GC-untrack before the trashcan and then immediately
1248          GC-track again afterward?
1249
1250       A. In the case that the base class is GC-aware, the base class
1251          probably GC-untracks the object.      If it does that using the
1252          UNTRACK macro, this will crash when the object is already
1253          untracked.  Because we don't know what the base class does, the
1254          only safe thing is to make sure the object is tracked when we
1255          call the base class dealloc.  But...  The trashcan begin macro
1256          requires that the object is *untracked* before it is called.  So
1257          the dance becomes:
1258
1259         GC untrack
1260         trashcan begin
1261         GC track
1262
1263       Q. Why did the last question say "immediately GC-track again"?
1264          It's nowhere near immediately.
1265
1266       A. Because the code *used* to re-track immediately.      Bad Idea.
1267          self has a refcount of 0, and if gc ever gets its hands on it
1268          (which can happen if any weakref callback gets invoked), it
1269          looks like trash to gc too, and gc also tries to delete self
1270          then.  But we're already deleting self.  Double deallocation is
1271          a subtle disaster.
1272
1273       Q. Why the bizarre (net-zero) manipulation of
1274          _PyTrash_delete_nesting around the trashcan macros?
1275
1276       A. Some base classes (e.g. list) also use the trashcan mechanism.
1277          The following scenario used to be possible:
1278
1279          - suppose the trashcan level is one below the trashcan limit
1280
1281          - subtype_dealloc() is called
1282
1283          - the trashcan limit is not yet reached, so the trashcan level
1284        is incremented and the code between trashcan begin and end is
1285        executed
1286
1287          - this destroys much of the object's contents, including its
1288        slots and __dict__
1289
1290          - basedealloc() is called; this is really list_dealloc(), or
1291        some other type which also uses the trashcan macros
1292
1293          - the trashcan limit is now reached, so the object is put on the
1294        trashcan's to-be-deleted-later list
1295
1296          - basedealloc() returns
1297
1298          - subtype_dealloc() decrefs the object's type
1299
1300          - subtype_dealloc() returns
1301
1302          - later, the trashcan code starts deleting the objects from its
1303        to-be-deleted-later list
1304
1305          - subtype_dealloc() is called *AGAIN* for the same object
1306
1307          - at the very least (if the destroyed slots and __dict__ don't
1308        cause problems) the object's type gets decref'ed a second
1309        time, which is *BAD*!!!
1310
1311          The remedy is to make sure that if the code between trashcan
1312          begin and end in subtype_dealloc() is called, the code between
1313          trashcan begin and end in basedealloc() will also be called.
1314          This is done by decrementing the level after passing into the
1315          trashcan block, and incrementing it just before leaving the
1316          block.
1317
1318          But now it's possible that a chain of objects consisting solely
1319          of objects whose deallocator is subtype_dealloc() will defeat
1320          the trashcan mechanism completely: the decremented level means
1321          that the effective level never reaches the limit.      Therefore, we
1322          *increment* the level *before* entering the trashcan block, and
1323          matchingly decrement it after leaving.  This means the trashcan
1324          code will trigger a little early, but that's no big deal.
1325
1326       Q. Are there any live examples of code in need of all this
1327          complexity?
1328
1329       A. Yes.  See SF bug 668433 for code that crashed (when Python was
1330          compiled in debug mode) before the trashcan level manipulations
1331          were added.  For more discussion, see SF patches 581742, 575073
1332          and bug 574207.
1333    */
1334}
1335
1336static PyTypeObject *solid_base(PyTypeObject *type);
1337
1338/* type test with subclassing support */
1339
1340static int
1341type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
1342{
1343    do {
1344        if (a == b)
1345            return 1;
1346        a = a->tp_base;
1347    } while (a != NULL);
1348
1349    return (b == &PyBaseObject_Type);
1350}
1351
1352int
1353PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
1354{
1355    PyObject *mro;
1356
1357    mro = a->tp_mro;
1358    if (mro != NULL) {
1359        /* Deal with multiple inheritance without recursion
1360           by walking the MRO tuple */
1361        Py_ssize_t i, n;
1362        assert(PyTuple_Check(mro));
1363        n = PyTuple_GET_SIZE(mro);
1364        for (i = 0; i < n; i++) {
1365            if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
1366                return 1;
1367        }
1368        return 0;
1369    }
1370    else
1371        /* a is not completely initilized yet; follow tp_base */
1372        return type_is_subtype_base_chain(a, b);
1373}
1374
1375/* Internal routines to do a method lookup in the type
1376   without looking in the instance dictionary
1377   (so we can't use PyObject_GetAttr) but still binding
1378   it to the instance.  The arguments are the object,
1379   the method name as a C string, and the address of a
1380   static variable used to cache the interned Python string.
1381
1382   Two variants:
1383
1384   - lookup_maybe() returns NULL without raising an exception
1385     when the _PyType_Lookup() call fails;
1386
1387   - lookup_method() always raises an exception upon errors.
1388
1389   - _PyObject_LookupSpecial() exported for the benefit of other places.
1390*/
1391
1392static PyObject *
1393lookup_maybe(PyObject *self, _Py_Identifier *attrid)
1394{
1395    PyObject *res;
1396
1397    res = _PyType_LookupId(Py_TYPE(self), attrid);
1398    if (res != NULL) {
1399        descrgetfunc f;
1400        if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
1401            Py_INCREF(res);
1402        else
1403            res = f(res, self, (PyObject *)(Py_TYPE(self)));
1404    }
1405    return res;
1406}
1407
1408static PyObject *
1409lookup_method(PyObject *self, _Py_Identifier *attrid)
1410{
1411    PyObject *res = lookup_maybe(self, attrid);
1412    if (res == NULL && !PyErr_Occurred())
1413        PyErr_SetObject(PyExc_AttributeError, attrid->object);
1414    return res;
1415}
1416
1417PyObject *
1418_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
1419{
1420    return lookup_maybe(self, attrid);
1421}
1422
1423/* A variation of PyObject_CallMethod that uses lookup_method()
1424   instead of PyObject_GetAttrString().  This uses the same convention
1425   as lookup_method to cache the interned name string object. */
1426
1427static PyObject *
1428call_method(PyObject *o, _Py_Identifier *nameid, const char *format, ...)
1429{
1430    va_list va;
1431    PyObject *func = NULL, *retval;
1432
1433    func = lookup_maybe(o, nameid);
1434    if (func == NULL) {
1435        if (!PyErr_Occurred())
1436            PyErr_SetObject(PyExc_AttributeError, nameid->object);
1437        return NULL;
1438    }
1439
1440    if (format && *format) {
1441        PyObject *args;
1442
1443        va_start(va, format);
1444        args = Py_VaBuildValue(format, va);
1445        va_end(va);
1446
1447        if (args == NULL) {
1448            Py_DECREF(func);
1449            return NULL;
1450        }
1451        assert(PyTuple_Check(args));
1452
1453        retval = PyObject_Call(func, args, NULL);
1454        Py_DECREF(args);
1455    }
1456    else {
1457        retval = _PyObject_CallNoArg(func);
1458    }
1459
1460    Py_DECREF(func);
1461
1462    return retval;
1463}
1464
1465/* Clone of call_method() that returns NotImplemented when the lookup fails. */
1466
1467static PyObject *
1468call_maybe(PyObject *o, _Py_Identifier *nameid, const char *format, ...)
1469{
1470    va_list va;
1471    PyObject *func = NULL, *retval;
1472
1473    func = lookup_maybe(o, nameid);
1474    if (func == NULL) {
1475        if (!PyErr_Occurred())
1476            Py_RETURN_NOTIMPLEMENTED;
1477        return NULL;
1478    }
1479
1480    if (format && *format) {
1481        PyObject *args;
1482
1483        va_start(va, format);
1484        args = Py_VaBuildValue(format, va);
1485        va_end(va);
1486
1487        if (args == NULL) {
1488            Py_DECREF(func);
1489            return NULL;
1490        }
1491        assert(PyTuple_Check(args));
1492
1493        retval = PyObject_Call(func, args, NULL);
1494        Py_DECREF(args);
1495    }
1496    else {
1497        retval = _PyObject_CallNoArg(func);
1498    }
1499
1500    Py_DECREF(func);
1501
1502    return retval;
1503}
1504
1505/*
1506    Method resolution order algorithm C3 described in
1507    "A Monotonic Superclass Linearization for Dylan",
1508    by Kim Barrett, Bob Cassel, Paul Haahr,
1509    David A. Moon, Keith Playford, and P. Tucker Withington.
1510    (OOPSLA 1996)
1511
1512    Some notes about the rules implied by C3:
1513
1514    No duplicate bases.
1515    It isn't legal to repeat a class in a list of base classes.
1516
1517    The next three properties are the 3 constraints in "C3".
1518
1519    Local precedence order.
1520    If A precedes B in C's MRO, then A will precede B in the MRO of all
1521    subclasses of C.
1522
1523    Monotonicity.
1524    The MRO of a class must be an extension without reordering of the
1525    MRO of each of its superclasses.
1526
1527    Extended Precedence Graph (EPG).
1528    Linearization is consistent if there is a path in the EPG from
1529    each class to all its successors in the linearization.  See
1530    the paper for definition of EPG.
1531 */
1532
1533static int
1534tail_contains(PyObject *list, int whence, PyObject *o) {
1535    Py_ssize_t j, size;
1536    size = PyList_GET_SIZE(list);
1537
1538    for (j = whence+1; j < size; j++) {
1539        if (PyList_GET_ITEM(list, j) == o)
1540            return 1;
1541    }
1542    return 0;
1543}
1544
1545static PyObject *
1546class_name(PyObject *cls)
1547{
1548    PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
1549    if (name == NULL) {
1550        PyErr_Clear();
1551        name = PyObject_Repr(cls);
1552    }
1553    if (name == NULL)
1554        return NULL;
1555    if (!PyUnicode_Check(name)) {
1556        Py_DECREF(name);
1557        return NULL;
1558    }
1559    return name;
1560}
1561
1562static int
1563check_duplicates(PyObject *list)
1564{
1565    Py_ssize_t i, j, n;
1566    /* Let's use a quadratic time algorithm,
1567       assuming that the bases lists is short.
1568    */
1569    n = PyList_GET_SIZE(list);
1570    for (i = 0; i < n; i++) {
1571        PyObject *o = PyList_GET_ITEM(list, i);
1572        for (j = i + 1; j < n; j++) {
1573            if (PyList_GET_ITEM(list, j) == o) {
1574                o = class_name(o);
1575                if (o != NULL) {
1576                    PyErr_Format(PyExc_TypeError,
1577                                 "duplicate base class %U",
1578                                 o);
1579                    Py_DECREF(o);
1580                } else {
1581                    PyErr_SetString(PyExc_TypeError,
1582                                 "duplicate base class");
1583                }
1584                return -1;
1585            }
1586        }
1587    }
1588    return 0;
1589}
1590
1591/* Raise a TypeError for an MRO order disagreement.
1592
1593   It's hard to produce a good error message.  In the absence of better
1594   insight into error reporting, report the classes that were candidates
1595   to be put next into the MRO.  There is some conflict between the
1596   order in which they should be put in the MRO, but it's hard to
1597   diagnose what constraint can't be satisfied.
1598*/
1599
1600static void
1601set_mro_error(PyObject *to_merge, int *remain)
1602{
1603    Py_ssize_t i, n, off, to_merge_size;
1604    char buf[1000];
1605    PyObject *k, *v;
1606    PyObject *set = PyDict_New();
1607    if (!set) return;
1608
1609    to_merge_size = PyList_GET_SIZE(to_merge);
1610    for (i = 0; i < to_merge_size; i++) {
1611        PyObject *L = PyList_GET_ITEM(to_merge, i);
1612        if (remain[i] < PyList_GET_SIZE(L)) {
1613            PyObject *c = PyList_GET_ITEM(L, remain[i]);
1614            if (PyDict_SetItem(set, c, Py_None) < 0) {
1615                Py_DECREF(set);
1616                return;
1617            }
1618        }
1619    }
1620    n = PyDict_Size(set);
1621
1622    off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1623consistent method resolution\norder (MRO) for bases");
1624    i = 0;
1625    while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1626        PyObject *name = class_name(k);
1627        char *name_str;
1628        if (name != NULL) {
1629            name_str = PyUnicode_AsUTF8(name);
1630            if (name_str == NULL)
1631                name_str = "?";
1632        } else
1633            name_str = "?";
1634        off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
1635        Py_XDECREF(name);
1636        if (--n && (size_t)(off+1) < sizeof(buf)) {
1637            buf[off++] = ',';
1638            buf[off] = '\0';
1639        }
1640    }
1641    PyErr_SetString(PyExc_TypeError, buf);
1642    Py_DECREF(set);
1643}
1644
1645static int
1646pmerge(PyObject *acc, PyObject* to_merge)
1647{
1648    int res = 0;
1649    Py_ssize_t i, j, to_merge_size, empty_cnt;
1650    int *remain;
1651
1652    to_merge_size = PyList_GET_SIZE(to_merge);
1653
1654    /* remain stores an index into each sublist of to_merge.
1655       remain[i] is the index of the next base in to_merge[i]
1656       that is not included in acc.
1657    */
1658    remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1659    if (remain == NULL) {
1660        PyErr_NoMemory();
1661        return -1;
1662    }
1663    for (i = 0; i < to_merge_size; i++)
1664        remain[i] = 0;
1665
1666  again:
1667    empty_cnt = 0;
1668    for (i = 0; i < to_merge_size; i++) {
1669        PyObject *candidate;
1670
1671        PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1672
1673        if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1674            empty_cnt++;
1675            continue;
1676        }
1677
1678        /* Choose next candidate for MRO.
1679
1680           The input sequences alone can determine the choice.
1681           If not, choose the class which appears in the MRO
1682           of the earliest direct superclass of the new class.
1683        */
1684
1685        candidate = PyList_GET_ITEM(cur_list, remain[i]);
1686        for (j = 0; j < to_merge_size; j++) {
1687            PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1688            if (tail_contains(j_lst, remain[j], candidate))
1689                goto skip; /* continue outer loop */
1690        }
1691        res = PyList_Append(acc, candidate);
1692        if (res < 0)
1693            goto out;
1694
1695        for (j = 0; j < to_merge_size; j++) {
1696            PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1697            if (remain[j] < PyList_GET_SIZE(j_lst) &&
1698                PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1699                remain[j]++;
1700            }
1701        }
1702        goto again;
1703      skip: ;
1704    }
1705
1706    if (empty_cnt != to_merge_size) {
1707        set_mro_error(to_merge, remain);
1708        res = -1;
1709    }
1710
1711  out:
1712    PyMem_FREE(remain);
1713
1714    return res;
1715}
1716
1717static PyObject *
1718mro_implementation(PyTypeObject *type)
1719{
1720    PyObject *result = NULL;
1721    PyObject *bases;
1722    PyObject *to_merge, *bases_aslist;
1723    int res;
1724    Py_ssize_t i, n;
1725
1726    if (type->tp_dict == NULL) {
1727        if (PyType_Ready(type) < 0)
1728            return NULL;
1729    }
1730
1731    /* Find a superclass linearization that honors the constraints
1732       of the explicit lists of bases and the constraints implied by
1733       each base class.
1734
1735       to_merge is a list of lists, where each list is a superclass
1736       linearization implied by a base class.  The last element of
1737       to_merge is the declared list of bases.
1738    */
1739
1740    bases = type->tp_bases;
1741    n = PyTuple_GET_SIZE(bases);
1742
1743    to_merge = PyList_New(n+1);
1744    if (to_merge == NULL)
1745        return NULL;
1746
1747    for (i = 0; i < n; i++) {
1748        PyTypeObject *base;
1749        PyObject *base_mro_aslist;
1750
1751        base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1752        if (base->tp_mro == NULL) {
1753            PyErr_Format(PyExc_TypeError,
1754                         "Cannot extend an incomplete type '%.100s'",
1755                         base->tp_name);
1756            goto out;
1757        }
1758
1759        base_mro_aslist = PySequence_List(base->tp_mro);
1760        if (base_mro_aslist == NULL)
1761            goto out;
1762
1763        PyList_SET_ITEM(to_merge, i, base_mro_aslist);
1764    }
1765
1766    bases_aslist = PySequence_List(bases);
1767    if (bases_aslist == NULL)
1768        goto out;
1769    /* This is just a basic sanity check. */
1770    if (check_duplicates(bases_aslist) < 0) {
1771        Py_DECREF(bases_aslist);
1772        goto out;
1773    }
1774    PyList_SET_ITEM(to_merge, n, bases_aslist);
1775
1776    result = Py_BuildValue("[O]", (PyObject *)type);
1777    if (result == NULL)
1778        goto out;
1779
1780    res = pmerge(result, to_merge);
1781    if (res < 0)
1782        Py_CLEAR(result);
1783
1784  out:
1785    Py_DECREF(to_merge);
1786
1787    return result;
1788}
1789
1790static PyObject *
1791mro_external(PyObject *self)
1792{
1793    PyTypeObject *type = (PyTypeObject *)self;
1794
1795    return mro_implementation(type);
1796}
1797
1798static int
1799mro_check(PyTypeObject *type, PyObject *mro)
1800{
1801    PyTypeObject *solid;
1802    Py_ssize_t i, n;
1803
1804    solid = solid_base(type);
1805
1806    n = PyTuple_GET_SIZE(mro);
1807    for (i = 0; i < n; i++) {
1808        PyTypeObject *base;
1809        PyObject *tmp;
1810
1811        tmp = PyTuple_GET_ITEM(mro, i);
1812        if (!PyType_Check(tmp)) {
1813            PyErr_Format(
1814                PyExc_TypeError,
1815                "mro() returned a non-class ('%.500s')",
1816                Py_TYPE(tmp)->tp_name);
1817            return -1;
1818        }
1819
1820        base = (PyTypeObject*)tmp;
1821        if (!PyType_IsSubtype(solid, solid_base(base))) {
1822            PyErr_Format(
1823                PyExc_TypeError,
1824                "mro() returned base with unsuitable layout ('%.500s')",
1825                base->tp_name);
1826            return -1;
1827        }
1828    }
1829
1830    return 0;
1831}
1832
1833/* Lookups an mcls.mro method, invokes it and checks the result (if needed,
1834   in case of a custom mro() implementation).
1835
1836   Keep in mind that during execution of this function type->tp_mro
1837   can be replaced due to possible reentrance (for example,
1838   through type_set_bases):
1839
1840      - when looking up the mcls.mro attribute (it could be
1841        a user-provided descriptor);
1842
1843      - from inside a custom mro() itself;
1844
1845      - through a finalizer of the return value of mro().
1846*/
1847static PyObject *
1848mro_invoke(PyTypeObject *type)
1849{
1850    PyObject *mro_result;
1851    PyObject *new_mro;
1852    int custom = (Py_TYPE(type) != &PyType_Type);
1853
1854    if (custom) {
1855        _Py_IDENTIFIER(mro);
1856        PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro);
1857        if (mro_meth == NULL)
1858            return NULL;
1859        mro_result = PyObject_CallObject(mro_meth, NULL);
1860        Py_DECREF(mro_meth);
1861    }
1862    else {
1863        mro_result = mro_implementation(type);
1864    }
1865    if (mro_result == NULL)
1866        return NULL;
1867
1868    new_mro = PySequence_Tuple(mro_result);
1869    Py_DECREF(mro_result);
1870    if (new_mro == NULL)
1871        return NULL;
1872
1873    if (custom && mro_check(type, new_mro) < 0) {
1874        Py_DECREF(new_mro);
1875        return NULL;
1876    }
1877
1878    return new_mro;
1879}
1880
1881/* Calculates and assigns a new MRO to type->tp_mro.
1882   Return values and invariants:
1883
1884     - Returns 1 if a new MRO value has been set to type->tp_mro due to
1885       this call of mro_internal (no tricky reentrancy and no errors).
1886
1887       In case if p_old_mro argument is not NULL, a previous value
1888       of type->tp_mro is put there, and the ownership of this
1889       reference is transferred to a caller.
1890       Otherwise, the previous value (if any) is decref'ed.
1891
1892     - Returns 0 in case when type->tp_mro gets changed because of
1893       reentering here through a custom mro() (see a comment to mro_invoke).
1894
1895       In this case, a refcount of an old type->tp_mro is adjusted
1896       somewhere deeper in the call stack (by the innermost mro_internal
1897       or its caller) and may become zero upon returning from here.
1898       This also implies that the whole hierarchy of subclasses of the type
1899       has seen the new value and updated their MRO accordingly.
1900
1901     - Returns -1 in case of an error.
1902*/
1903static int
1904mro_internal(PyTypeObject *type, PyObject **p_old_mro)
1905{
1906    PyObject *new_mro, *old_mro;
1907    int reent;
1908
1909    /* Keep a reference to be able to do a reentrancy check below.
1910       Don't let old_mro be GC'ed and its address be reused for
1911       another object, like (suddenly!) a new tp_mro.  */
1912    old_mro = type->tp_mro;
1913    Py_XINCREF(old_mro);
1914    new_mro = mro_invoke(type);  /* might cause reentrance */
1915    reent = (type->tp_mro != old_mro);
1916    Py_XDECREF(old_mro);
1917    if (new_mro == NULL)
1918        return -1;
1919
1920    if (reent) {
1921        Py_DECREF(new_mro);
1922        return 0;
1923    }
1924
1925    type->tp_mro = new_mro;
1926
1927    type_mro_modified(type, type->tp_mro);
1928    /* corner case: the super class might have been hidden
1929       from the custom MRO */
1930    type_mro_modified(type, type->tp_bases);
1931
1932    PyType_Modified(type);
1933
1934    if (p_old_mro != NULL)
1935        *p_old_mro = old_mro;  /* transfer the ownership */
1936    else
1937        Py_XDECREF(old_mro);
1938
1939    return 1;
1940}
1941
1942
1943/* Calculate the best base amongst multiple base classes.
1944   This is the first one that's on the path to the "solid base". */
1945
1946static PyTypeObject *
1947best_base(PyObject *bases)
1948{
1949    Py_ssize_t i, n;
1950    PyTypeObject *base, *winner, *candidate, *base_i;
1951    PyObject *base_proto;
1952
1953    assert(PyTuple_Check(bases));
1954    n = PyTuple_GET_SIZE(bases);
1955    assert(n > 0);
1956    base = NULL;
1957    winner = NULL;
1958    for (i = 0; i < n; i++) {
1959        base_proto = PyTuple_GET_ITEM(bases, i);
1960        if (!PyType_Check(base_proto)) {
1961            PyErr_SetString(
1962                PyExc_TypeError,
1963                "bases must be types");
1964            return NULL;
1965        }
1966        base_i = (PyTypeObject *)base_proto;
1967        if (base_i->tp_dict == NULL) {
1968            if (PyType_Ready(base_i) < 0)
1969                return NULL;
1970        }
1971        if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
1972            PyErr_Format(PyExc_TypeError,
1973                         "type '%.100s' is not an acceptable base type",
1974                         base_i->tp_name);
1975            return NULL;
1976        }
1977        candidate = solid_base(base_i);
1978        if (winner == NULL) {
1979            winner = candidate;
1980            base = base_i;
1981        }
1982        else if (PyType_IsSubtype(winner, candidate))
1983            ;
1984        else if (PyType_IsSubtype(candidate, winner)) {
1985            winner = candidate;
1986            base = base_i;
1987        }
1988        else {
1989            PyErr_SetString(
1990                PyExc_TypeError,
1991                "multiple bases have "
1992                "instance lay-out conflict");
1993            return NULL;
1994        }
1995    }
1996    assert (base != NULL);
1997
1998    return base;
1999}
2000
2001static int
2002extra_ivars(PyTypeObject *type, PyTypeObject *base)
2003{
2004    size_t t_size = type->tp_basicsize;
2005    size_t b_size = base->tp_basicsize;
2006
2007    assert(t_size >= b_size); /* Else type smaller than base! */
2008    if (type->tp_itemsize || base->tp_itemsize) {
2009        /* If itemsize is involved, stricter rules */
2010        return t_size != b_size ||
2011            type->tp_itemsize != base->tp_itemsize;
2012    }
2013    if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
2014        type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
2015        type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2016        t_size -= sizeof(PyObject *);
2017    if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
2018        type->tp_dictoffset + sizeof(PyObject *) == t_size &&
2019        type->tp_flags & Py_TPFLAGS_HEAPTYPE)
2020        t_size -= sizeof(PyObject *);
2021
2022    return t_size != b_size;
2023}
2024
2025static PyTypeObject *
2026solid_base(PyTypeObject *type)
2027{
2028    PyTypeObject *base;
2029
2030    if (type->tp_base)
2031        base = solid_base(type->tp_base);
2032    else
2033        base = &PyBaseObject_Type;
2034    if (extra_ivars(type, base))
2035        return type;
2036    else
2037        return base;
2038}
2039
2040static void object_dealloc(PyObject *);
2041static int object_init(PyObject *, PyObject *, PyObject *);
2042static int update_slot(PyTypeObject *, PyObject *);
2043static void fixup_slot_dispatchers(PyTypeObject *);
2044static int set_names(PyTypeObject *);
2045static int init_subclass(PyTypeObject *, PyObject *);
2046
2047/*
2048 * Helpers for  __dict__ descriptor.  We don't want to expose the dicts
2049 * inherited from various builtin types.  The builtin base usually provides
2050 * its own __dict__ descriptor, so we use that when we can.
2051 */
2052static PyTypeObject *
2053get_builtin_base_with_dict(PyTypeObject *type)
2054{
2055    while (type->tp_base != NULL) {
2056        if (type->tp_dictoffset != 0 &&
2057            !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
2058            return type;
2059        type = type->tp_base;
2060    }
2061    return NULL;
2062}
2063
2064static PyObject *
2065get_dict_descriptor(PyTypeObject *type)
2066{
2067    PyObject *descr;
2068
2069    descr = _PyType_LookupId(type, &PyId___dict__);
2070    if (descr == NULL || !PyDescr_IsData(descr))
2071        return NULL;
2072
2073    return descr;
2074}
2075
2076static void
2077raise_dict_descr_error(PyObject *obj)
2078{
2079    PyErr_Format(PyExc_TypeError,
2080                 "this __dict__ descriptor does not support "
2081                 "'%.200s' objects", Py_TYPE(obj)->tp_name);
2082}
2083
2084static PyObject *
2085subtype_dict(PyObject *obj, void *context)
2086{
2087    PyTypeObject *base;
2088
2089    base = get_builtin_base_with_dict(Py_TYPE(obj));
2090    if (base != NULL) {
2091        descrgetfunc func;
2092        PyObject *descr = get_dict_descriptor(base);
2093        if (descr == NULL) {
2094            raise_dict_descr_error(obj);
2095            return NULL;
2096        }
2097        func = Py_TYPE(descr)->tp_descr_get;
2098        if (func == NULL) {
2099            raise_dict_descr_error(obj);
2100            return NULL;
2101        }
2102        return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
2103    }
2104    return PyObject_GenericGetDict(obj, context);
2105}
2106
2107static int
2108subtype_setdict(PyObject *obj, PyObject *value, void *context)
2109{
2110    PyObject **dictptr;
2111    PyTypeObject *base;
2112
2113    base = get_builtin_base_with_dict(Py_TYPE(obj));
2114    if (base != NULL) {
2115        descrsetfunc func;
2116        PyObject *descr = get_dict_descriptor(base);
2117        if (descr == NULL) {
2118            raise_dict_descr_error(obj);
2119            return -1;
2120        }
2121        func = Py_TYPE(descr)->tp_descr_set;
2122        if (func == NULL) {
2123            raise_dict_descr_error(obj);
2124            return -1;
2125        }
2126        return func(descr, obj, value);
2127    }
2128    /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */
2129    dictptr = _PyObject_GetDictPtr(obj);
2130    if (dictptr == NULL) {
2131        PyErr_SetString(PyExc_AttributeError,
2132                        "This object has no __dict__");
2133        return -1;
2134    }
2135    if (value != NULL && !PyDict_Check(value)) {
2136        PyErr_Format(PyExc_TypeError,
2137                     "__dict__ must be set to a dictionary, "
2138                     "not a '%.200s'", Py_TYPE(value)->tp_name);
2139        return -1;
2140    }
2141    Py_XINCREF(value);
2142    Py_XSETREF(*dictptr, value);
2143    return 0;
2144}
2145
2146static PyObject *
2147subtype_getweakref(PyObject *obj, void *context)
2148{
2149    PyObject **weaklistptr;
2150    PyObject *result;
2151
2152    if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
2153        PyErr_SetString(PyExc_AttributeError,
2154                        "This object has no __weakref__");
2155        return NULL;
2156    }
2157    assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
2158    assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
2159           (size_t)(Py_TYPE(obj)->tp_basicsize));
2160    weaklistptr = (PyObject **)
2161        ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
2162    if (*weaklistptr == NULL)
2163        result = Py_None;
2164    else
2165        result = *weaklistptr;
2166    Py_INCREF(result);
2167    return result;
2168}
2169
2170/* Three variants on the subtype_getsets list. */
2171
2172static PyGetSetDef subtype_getsets_full[] = {
2173    {"__dict__", subtype_dict, subtype_setdict,
2174     PyDoc_STR("dictionary for instance variables (if defined)")},
2175    {"__weakref__", subtype_getweakref, NULL,
2176     PyDoc_STR("list of weak references to the object (if defined)")},
2177    {0}
2178};
2179
2180static PyGetSetDef subtype_getsets_dict_only[] = {
2181    {"__dict__", subtype_dict, subtype_setdict,
2182     PyDoc_STR("dictionary for instance variables (if defined)")},
2183    {0}
2184};
2185
2186static PyGetSetDef subtype_getsets_weakref_only[] = {
2187    {"__weakref__", subtype_getweakref, NULL,
2188     PyDoc_STR("list of weak references to the object (if defined)")},
2189    {0}
2190};
2191
2192static int
2193valid_identifier(PyObject *s)
2194{
2195    if (!PyUnicode_Check(s)) {
2196        PyErr_Format(PyExc_TypeError,
2197                     "__slots__ items must be strings, not '%.200s'",
2198                     Py_TYPE(s)->tp_name);
2199        return 0;
2200    }
2201    if (!PyUnicode_IsIdentifier(s)) {
2202        PyErr_SetString(PyExc_TypeError,
2203                        "__slots__ must be identifiers");
2204        return 0;
2205    }
2206    return 1;
2207}
2208
2209/* Forward */
2210static int
2211object_init(PyObject *self, PyObject *args, PyObject *kwds);
2212
2213static int
2214type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2215{
2216    int res;
2217
2218    assert(args != NULL && PyTuple_Check(args));
2219    assert(kwds == NULL || PyDict_Check(kwds));
2220
2221    if (kwds != NULL && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
2222        PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2223        PyErr_SetString(PyExc_TypeError,
2224                        "type.__init__() takes no keyword arguments");
2225        return -1;
2226    }
2227
2228    if (args != NULL && PyTuple_Check(args) &&
2229        (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2230        PyErr_SetString(PyExc_TypeError,
2231                        "type.__init__() takes 1 or 3 arguments");
2232        return -1;
2233    }
2234
2235    /* Call object.__init__(self) now. */
2236    /* XXX Could call super(type, cls).__init__() but what's the point? */
2237    args = PyTuple_GetSlice(args, 0, 0);
2238    res = object_init(cls, args, NULL);
2239    Py_DECREF(args);
2240    return res;
2241}
2242
2243unsigned long
2244PyType_GetFlags(PyTypeObject *type)
2245{
2246    return type->tp_flags;
2247}
2248
2249/* Determine the most derived metatype. */
2250PyTypeObject *
2251_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases)
2252{
2253    Py_ssize_t i, nbases;
2254    PyTypeObject *winner;
2255    PyObject *tmp;
2256    PyTypeObject *tmptype;
2257
2258    /* Determine the proper metatype to deal with this,
2259       and check for metatype conflicts while we're at it.
2260       Note that if some other metatype wins to contract,
2261       it's possible that its instances are not types. */
2262
2263    nbases = PyTuple_GET_SIZE(bases);
2264    winner = metatype;
2265    for (i = 0; i < nbases; i++) {
2266        tmp = PyTuple_GET_ITEM(bases, i);
2267        tmptype = Py_TYPE(tmp);
2268        if (PyType_IsSubtype(winner, tmptype))
2269            continue;
2270        if (PyType_IsSubtype(tmptype, winner)) {
2271            winner = tmptype;
2272            continue;
2273        }
2274        /* else: */
2275        PyErr_SetString(PyExc_TypeError,
2276                        "metaclass conflict: "
2277                        "the metaclass of a derived class "
2278                        "must be a (non-strict) subclass "
2279                        "of the metaclasses of all its bases");
2280        return NULL;
2281    }
2282    return winner;
2283}
2284
2285static PyObject *
2286type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2287{
2288    PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
2289    PyObject *qualname, *slots = NULL, *tmp, *newslots, *cell;
2290    PyTypeObject *type = NULL, *base, *tmptype, *winner;
2291    PyHeapTypeObject *et;
2292    PyMemberDef *mp;
2293    Py_ssize_t i, nbases, nslots, slotoffset, name_size;
2294    int j, may_add_dict, may_add_weak, add_dict, add_weak;
2295    _Py_IDENTIFIER(__qualname__);
2296    _Py_IDENTIFIER(__slots__);
2297    _Py_IDENTIFIER(__classcell__);
2298
2299    assert(args != NULL && PyTuple_Check(args));
2300    assert(kwds == NULL || PyDict_Check(kwds));
2301
2302    /* Special case: type(x) should return x->ob_type */
2303    /* We only want type itself to accept the one-argument form (#27157)
2304       Note: We don't call PyType_CheckExact as that also allows subclasses */
2305    if (metatype == &PyType_Type) {
2306        const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2307        const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
2308
2309        if (nargs == 1 && nkwds == 0) {
2310            PyObject *x = PyTuple_GET_ITEM(args, 0);
2311            Py_INCREF(Py_TYPE(x));
2312            return (PyObject *) Py_TYPE(x);
2313        }
2314
2315        /* SF bug 475327 -- if that didn't trigger, we need 3
2316           arguments. but PyArg_ParseTupleAndKeywords below may give
2317           a msg saying type() needs exactly 3. */
2318        if (nargs != 3) {
2319            PyErr_SetString(PyExc_TypeError,
2320                            "type() takes 1 or 3 arguments");
2321            return NULL;
2322        }
2323    }
2324
2325    /* Check arguments: (name, bases, dict) */
2326    if (!PyArg_ParseTuple(args, "UO!O!:type.__new__", &name, &PyTuple_Type,
2327                          &bases, &PyDict_Type, &orig_dict))
2328        return NULL;
2329
2330    /* Determine the proper metatype to deal with this: */
2331    winner = _PyType_CalculateMetaclass(metatype, bases);
2332    if (winner == NULL) {
2333        return NULL;
2334    }
2335
2336    if (winner != metatype) {
2337        if (winner->tp_new != type_new) /* Pass it to the winner */
2338            return winner->tp_new(winner, args, kwds);
2339        metatype = winner;
2340    }
2341
2342    /* Adjust for empty tuple bases */
2343    nbases = PyTuple_GET_SIZE(bases);
2344    if (nbases == 0) {
2345        bases = PyTuple_Pack(1, &PyBaseObject_Type);
2346        if (bases == NULL)
2347            goto error;
2348        nbases = 1;
2349    }
2350    else
2351        Py_INCREF(bases);
2352
2353    /* Calculate best base, and check that all bases are type objects */
2354    base = best_base(bases);
2355    if (base == NULL) {
2356        goto error;
2357    }
2358
2359    dict = PyDict_Copy(orig_dict);
2360    if (dict == NULL)
2361        goto error;
2362
2363    /* Check for a __slots__ sequence variable in dict, and count it */
2364    slots = _PyDict_GetItemId(dict, &PyId___slots__);
2365    nslots = 0;
2366    add_dict = 0;
2367    add_weak = 0;
2368    may_add_dict = base->tp_dictoffset == 0;
2369    may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
2370    if (slots == NULL) {
2371        if (may_add_dict) {
2372            add_dict++;
2373        }
2374        if (may_add_weak) {
2375            add_weak++;
2376        }
2377    }
2378    else {
2379        /* Have slots */
2380
2381        /* Make it into a tuple */
2382        if (PyUnicode_Check(slots))
2383            slots = PyTuple_Pack(1, slots);
2384        else
2385            slots = PySequence_Tuple(slots);
2386        if (slots == NULL)
2387            goto error;
2388        assert(PyTuple_Check(slots));
2389
2390        /* Are slots allowed? */
2391        nslots = PyTuple_GET_SIZE(slots);
2392        if (nslots > 0 && base->tp_itemsize != 0) {
2393            PyErr_Format(PyExc_TypeError,
2394                         "nonempty __slots__ "
2395                         "not supported for subtype of '%s'",
2396                         base->tp_name);
2397            goto error;
2398        }
2399
2400        /* Check for valid slot names and two special cases */
2401        for (i = 0; i < nslots; i++) {
2402            PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2403            if (!valid_identifier(tmp))
2404                goto error;
2405            assert(PyUnicode_Check(tmp));
2406            if (_PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) {
2407                if (!may_add_dict || add_dict) {
2408                    PyErr_SetString(PyExc_TypeError,
2409                        "__dict__ slot disallowed: "
2410                        "we already got one");
2411                    goto error;
2412                }
2413                add_dict++;
2414            }
2415            if (_PyUnicode_EqualToASCIIString(tmp, "__weakref__")) {
2416                if (!may_add_weak || add_weak) {
2417                    PyErr_SetString(PyExc_TypeError,
2418                        "__weakref__ slot disallowed: "
2419                        "either we already got one, "
2420                        "or __itemsize__ != 0");
2421                    goto error;
2422                }
2423                add_weak++;
2424            }
2425        }
2426
2427        /* Copy slots into a list, mangle names and sort them.
2428           Sorted names are needed for __class__ assignment.
2429           Convert them back to tuple at the end.
2430        */
2431        newslots = PyList_New(nslots - add_dict - add_weak);
2432        if (newslots == NULL)
2433            goto error;
2434        for (i = j = 0; i < nslots; i++) {
2435            tmp = PyTuple_GET_ITEM(slots, i);
2436            if ((add_dict &&
2437                 _PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) ||
2438                (add_weak &&
2439                 _PyUnicode_EqualToASCIIString(tmp, "__weakref__")))
2440                continue;
2441            tmp =_Py_Mangle(name, tmp);
2442            if (!tmp) {
2443                Py_DECREF(newslots);
2444                goto error;
2445            }
2446            PyList_SET_ITEM(newslots, j, tmp);
2447            if (PyDict_GetItem(dict, tmp)) {
2448                PyErr_Format(PyExc_ValueError,
2449                             "%R in __slots__ conflicts with class variable",
2450                             tmp);
2451                Py_DECREF(newslots);
2452                goto error;
2453            }
2454            j++;
2455        }
2456        assert(j == nslots - add_dict - add_weak);
2457        nslots = j;
2458        Py_CLEAR(slots);
2459        if (PyList_Sort(newslots) == -1) {
2460            Py_DECREF(newslots);
2461            goto error;
2462        }
2463        slots = PyList_AsTuple(newslots);
2464        Py_DECREF(newslots);
2465        if (slots == NULL)
2466            goto error;
2467
2468        /* Secondary bases may provide weakrefs or dict */
2469        if (nbases > 1 &&
2470            ((may_add_dict && !add_dict) ||
2471             (may_add_weak && !add_weak))) {
2472            for (i = 0; i < nbases; i++) {
2473                tmp = PyTuple_GET_ITEM(bases, i);
2474                if (tmp == (PyObject *)base)
2475                    continue; /* Skip primary base */
2476                assert(PyType_Check(tmp));
2477                tmptype = (PyTypeObject *)tmp;
2478                if (may_add_dict && !add_dict &&
2479                    tmptype->tp_dictoffset != 0)
2480                    add_dict++;
2481                if (may_add_weak && !add_weak &&
2482                    tmptype->tp_weaklistoffset != 0)
2483                    add_weak++;
2484                if (may_add_dict && !add_dict)
2485                    continue;
2486                if (may_add_weak && !add_weak)
2487                    continue;
2488                /* Nothing more to check */
2489                break;
2490            }
2491        }
2492    }
2493
2494    /* Allocate the type object */
2495    type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
2496    if (type == NULL)
2497        goto error;
2498
2499    /* Keep name and slots alive in the extended type object */
2500    et = (PyHeapTypeObject *)type;
2501    Py_INCREF(name);
2502    et->ht_name = name;
2503    et->ht_slots = slots;
2504    slots = NULL;
2505
2506    /* Initialize tp_flags */
2507    type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2508        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
2509    if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2510        type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2511
2512    /* Initialize essential fields */
2513    type->tp_as_async = &et->as_async;
2514    type->tp_as_number = &et->as_number;
2515    type->tp_as_sequence = &et->as_sequence;
2516    type->tp_as_mapping = &et->as_mapping;
2517    type->tp_as_buffer = &et->as_buffer;
2518    type->tp_name = PyUnicode_AsUTF8AndSize(name, &name_size);
2519    if (!type->tp_name)
2520        goto error;
2521    if (strlen(type->tp_name) != (size_t)name_size) {
2522        PyErr_SetString(PyExc_ValueError,
2523                        "type name must not contain null characters");
2524        goto error;
2525    }
2526
2527    /* Set tp_base and tp_bases */
2528    type->tp_bases = bases;
2529    bases = NULL;
2530    Py_INCREF(base);
2531    type->tp_base = base;
2532
2533    /* Initialize tp_dict from passed-in dict */
2534    Py_INCREF(dict);
2535    type->tp_dict = dict;
2536
2537    /* Set __module__ in the dict */
2538    if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) {
2539        tmp = PyEval_GetGlobals();
2540        if (tmp != NULL) {
2541            tmp = _PyDict_GetItemId(tmp, &PyId___name__);
2542            if (tmp != NULL) {
2543                if (_PyDict_SetItemId(dict, &PyId___module__,
2544                                      tmp) < 0)
2545                    goto error;
2546            }
2547        }
2548    }
2549
2550    /* Set ht_qualname to dict['__qualname__'] if available, else to
2551       __name__.  The __qualname__ accessor will look for ht_qualname.
2552    */
2553    qualname = _PyDict_GetItemId(dict, &PyId___qualname__);
2554    if (qualname != NULL) {
2555        if (!PyUnicode_Check(qualname)) {
2556            PyErr_Format(PyExc_TypeError,
2557                         "type __qualname__ must be a str, not %s",
2558                         Py_TYPE(qualname)->tp_name);
2559            goto error;
2560        }
2561    }
2562    et->ht_qualname = qualname ? qualname : et->ht_name;
2563    Py_INCREF(et->ht_qualname);
2564    if (qualname != NULL && _PyDict_DelItemId(dict, &PyId___qualname__) < 0)
2565        goto error;
2566
2567    /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2568       and is a string.  The __doc__ accessor will first look for tp_doc;
2569       if that fails, it will still look into __dict__.
2570    */
2571    {
2572        PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
2573        if (doc != NULL && PyUnicode_Check(doc)) {
2574            Py_ssize_t len;
2575            char *doc_str;
2576            char *tp_doc;
2577
2578            doc_str = PyUnicode_AsUTF8(doc);
2579            if (doc_str == NULL)
2580                goto error;
2581            /* Silently truncate the docstring if it contains null bytes. */
2582            len = strlen(doc_str);
2583            tp_doc = (char *)PyObject_MALLOC(len + 1);
2584            if (tp_doc == NULL) {
2585                PyErr_NoMemory();
2586                goto error;
2587            }
2588            memcpy(tp_doc, doc_str, len + 1);
2589            type->tp_doc = tp_doc;
2590        }
2591    }
2592
2593    /* Special-case __new__: if it's a plain function,
2594       make it a static function */
2595    tmp = _PyDict_GetItemId(dict, &PyId___new__);
2596    if (tmp != NULL && PyFunction_Check(tmp)) {
2597        tmp = PyStaticMethod_New(tmp);
2598        if (tmp == NULL)
2599            goto error;
2600        if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) {
2601            Py_DECREF(tmp);
2602            goto error;
2603        }
2604        Py_DECREF(tmp);
2605    }
2606
2607    /* Special-case __init_subclass__: if it's a plain function,
2608       make it a classmethod */
2609    tmp = _PyDict_GetItemId(dict, &PyId___init_subclass__);
2610    if (tmp != NULL && PyFunction_Check(tmp)) {
2611        tmp = PyClassMethod_New(tmp);
2612        if (tmp == NULL)
2613            goto error;
2614        if (_PyDict_SetItemId(dict, &PyId___init_subclass__, tmp) < 0) {
2615            Py_DECREF(tmp);
2616            goto error;
2617        }
2618        Py_DECREF(tmp);
2619    }
2620
2621    /* Add descriptors for custom slots from __slots__, or for __dict__ */
2622    mp = PyHeapType_GET_MEMBERS(et);
2623    slotoffset = base->tp_basicsize;
2624    if (et->ht_slots != NULL) {
2625        for (i = 0; i < nslots; i++, mp++) {
2626            mp->name = PyUnicode_AsUTF8(
2627                PyTuple_GET_ITEM(et->ht_slots, i));
2628            if (mp->name == NULL)
2629                goto error;
2630            mp->type = T_OBJECT_EX;
2631            mp->offset = slotoffset;
2632
2633            /* __dict__ and __weakref__ are already filtered out */
2634            assert(strcmp(mp->name, "__dict__") != 0);
2635            assert(strcmp(mp->name, "__weakref__") != 0);
2636
2637            slotoffset += sizeof(PyObject *);
2638        }
2639    }
2640    if (add_dict) {
2641        if (base->tp_itemsize)
2642            type->tp_dictoffset = -(long)sizeof(PyObject *);
2643        else
2644            type->tp_dictoffset = slotoffset;
2645        slotoffset += sizeof(PyObject *);
2646    }
2647    if (add_weak) {
2648        assert(!base->tp_itemsize);
2649        type->tp_weaklistoffset = slotoffset;
2650        slotoffset += sizeof(PyObject *);
2651    }
2652    type->tp_basicsize = slotoffset;
2653    type->tp_itemsize = base->tp_itemsize;
2654    type->tp_members = PyHeapType_GET_MEMBERS(et);
2655
2656    if (type->tp_weaklistoffset && type->tp_dictoffset)
2657        type->tp_getset = subtype_getsets_full;
2658    else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2659        type->tp_getset = subtype_getsets_weakref_only;
2660    else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2661        type->tp_getset = subtype_getsets_dict_only;
2662    else
2663        type->tp_getset = NULL;
2664
2665    /* Special case some slots */
2666    if (type->tp_dictoffset != 0 || nslots > 0) {
2667        if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2668            type->tp_getattro = PyObject_GenericGetAttr;
2669        if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2670            type->tp_setattro = PyObject_GenericSetAttr;
2671    }
2672    type->tp_dealloc = subtype_dealloc;
2673
2674    /* Enable GC unless this class is not adding new instance variables and
2675       the base class did not use GC. */
2676    if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) ||
2677        type->tp_basicsize > base->tp_basicsize)
2678        type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2679
2680    /* Always override allocation strategy to use regular heap */
2681    type->tp_alloc = PyType_GenericAlloc;
2682    if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2683        type->tp_free = PyObject_GC_Del;
2684        type->tp_traverse = subtype_traverse;
2685        type->tp_clear = subtype_clear;
2686    }
2687    else
2688        type->tp_free = PyObject_Del;
2689
2690    /* store type in class' cell if one is supplied */
2691    cell = _PyDict_GetItemId(dict, &PyId___classcell__);
2692    if (cell != NULL) {
2693        /* At least one method requires a reference to its defining class */
2694        if (!PyCell_Check(cell)) {
2695            PyErr_Format(PyExc_TypeError,
2696                         "__classcell__ must be a nonlocal cell, not %.200R",
2697                         Py_TYPE(cell));
2698            goto error;
2699        }
2700        PyCell_Set(cell, (PyObject *) type);
2701        _PyDict_DelItemId(dict, &PyId___classcell__);
2702        PyErr_Clear();
2703    }
2704
2705    /* Initialize the rest */
2706    if (PyType_Ready(type) < 0)
2707        goto error;
2708
2709    /* Put the proper slots in place */
2710    fixup_slot_dispatchers(type);
2711
2712    if (type->tp_dictoffset) {
2713        et->ht_cached_keys = _PyDict_NewKeysForClass();
2714    }
2715
2716    if (set_names(type) < 0)
2717        goto error;
2718
2719    if (init_subclass(type, kwds) < 0)
2720        goto error;
2721
2722    Py_DECREF(dict);
2723    return (PyObject *)type;
2724
2725error:
2726    Py_XDECREF(dict);
2727    Py_XDECREF(bases);
2728    Py_XDECREF(slots);
2729    Py_XDECREF(type);
2730    return NULL;
2731}
2732
2733static const short slotoffsets[] = {
2734    -1, /* invalid slot */
2735#include "typeslots.inc"
2736};
2737
2738PyObject *
2739PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
2740{
2741    PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2742    PyTypeObject *type, *base;
2743    PyObject *modname;
2744    char *s;
2745    char *res_start = (char*)res;
2746    PyType_Slot *slot;
2747
2748    /* Set the type name and qualname */
2749    s = strrchr(spec->name, '.');
2750    if (s == NULL)
2751        s = (char*)spec->name;
2752    else
2753        s++;
2754
2755    if (res == NULL)
2756        return NULL;
2757    type = &res->ht_type;
2758    /* The flags must be initialized early, before the GC traverses us */
2759    type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
2760    res->ht_name = PyUnicode_FromString(s);
2761    if (!res->ht_name)
2762        goto fail;
2763    res->ht_qualname = res->ht_name;
2764    Py_INCREF(res->ht_qualname);
2765    type->tp_name = spec->name;
2766    if (!type->tp_name)
2767        goto fail;
2768
2769    /* Adjust for empty tuple bases */
2770    if (!bases) {
2771        base = &PyBaseObject_Type;
2772        /* See whether Py_tp_base(s) was specified */
2773        for (slot = spec->slots; slot->slot; slot++) {
2774            if (slot->slot == Py_tp_base)
2775                base = slot->pfunc;
2776            else if (slot->slot == Py_tp_bases) {
2777                bases = slot->pfunc;
2778                Py_INCREF(bases);
2779            }
2780        }
2781        if (!bases)
2782            bases = PyTuple_Pack(1, base);
2783        if (!bases)
2784            goto fail;
2785    }
2786    else
2787        Py_INCREF(bases);
2788
2789    /* Calculate best base, and check that all bases are type objects */
2790    base = best_base(bases);
2791    if (base == NULL) {
2792        goto fail;
2793    }
2794    if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2795        PyErr_Format(PyExc_TypeError,
2796                     "type '%.100s' is not an acceptable base type",
2797                     base->tp_name);
2798        goto fail;
2799    }
2800
2801    /* Initialize essential fields */
2802    type->tp_as_async = &res->as_async;
2803    type->tp_as_number = &res->as_number;
2804    type->tp_as_sequence = &res->as_sequence;
2805    type->tp_as_mapping = &res->as_mapping;
2806    type->tp_as_buffer = &res->as_buffer;
2807    /* Set tp_base and tp_bases */
2808    type->tp_bases = bases;
2809    bases = NULL;
2810    Py_INCREF(base);
2811    type->tp_base = base;
2812
2813    type->tp_basicsize = spec->basicsize;
2814    type->tp_itemsize = spec->itemsize;
2815
2816    for (slot = spec->slots; slot->slot; slot++) {
2817        if (slot->slot < 0
2818            || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
2819            PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
2820            goto fail;
2821        }
2822        if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
2823            /* Processed above */
2824            continue;
2825        *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
2826
2827        /* need to make a copy of the docstring slot, which usually
2828           points to a static string literal */
2829        if (slot->slot == Py_tp_doc) {
2830            const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
2831            size_t len = strlen(old_doc)+1;
2832            char *tp_doc = PyObject_MALLOC(len);
2833            if (tp_doc == NULL) {
2834                PyErr_NoMemory();
2835                goto fail;
2836            }
2837            memcpy(tp_doc, old_doc, len);
2838            type->tp_doc = tp_doc;
2839        }
2840    }
2841    if (type->tp_dealloc == NULL) {
2842        /* It's a heap type, so needs the heap types' dealloc.
2843           subtype_dealloc will call the base type's tp_dealloc, if
2844           necessary. */
2845        type->tp_dealloc = subtype_dealloc;
2846    }
2847
2848    if (PyType_Ready(type) < 0)
2849        goto fail;
2850
2851    if (type->tp_dictoffset) {
2852        res->ht_cached_keys = _PyDict_NewKeysForClass();
2853    }
2854
2855    /* Set type.__module__ */
2856    s = strrchr(spec->name, '.');
2857    if (s != NULL) {
2858        int err;
2859        modname = PyUnicode_FromStringAndSize(
2860                spec->name, (Py_ssize_t)(s - spec->name));
2861        if (modname == NULL) {
2862            goto fail;
2863        }
2864        err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
2865        Py_DECREF(modname);
2866        if (err != 0)
2867            goto fail;
2868    } else {
2869        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
2870                "builtin type %.200s has no __module__ attribute",
2871                spec->name))
2872            goto fail;
2873    }
2874
2875    return (PyObject*)res;
2876
2877 fail:
2878    Py_DECREF(res);
2879    return NULL;
2880}
2881
2882PyObject *
2883PyType_FromSpec(PyType_Spec *spec)
2884{
2885    return PyType_FromSpecWithBases(spec, NULL);
2886}
2887
2888void *
2889PyType_GetSlot(PyTypeObject *type, int slot)
2890{
2891    if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
2892        PyErr_BadInternalCall();
2893        return NULL;
2894    }
2895    if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
2896        /* Extension module requesting slot from a future version */
2897        return NULL;
2898    }
2899    return  *(void**)(((char*)type) + slotoffsets[slot]);
2900}
2901
2902/* Internal API to look for a name through the MRO.
2903   This returns a borrowed reference, and doesn't set an exception! */
2904PyObject *
2905_PyType_Lookup(PyTypeObject *type, PyObject *name)
2906{
2907    Py_ssize_t i, n;
2908    PyObject *mro, *res, *base, *dict;
2909    unsigned int h;
2910
2911    if (MCACHE_CACHEABLE_NAME(name) &&
2912        PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
2913        /* fast path */
2914        h = MCACHE_HASH_METHOD(type, name);
2915        if (method_cache[h].version == type->tp_version_tag &&
2916            method_cache[h].name == name) {
2917#if MCACHE_STATS
2918            method_cache_hits++;
2919#endif
2920            return method_cache[h].value;
2921        }
2922    }
2923
2924    /* Look in tp_dict of types in MRO */
2925    mro = type->tp_mro;
2926
2927    if (mro == NULL) {
2928        if ((type->tp_flags & Py_TPFLAGS_READYING) == 0 &&
2929            PyType_Ready(type) < 0) {
2930            /* It's not ideal to clear the error condition,
2931               but this function is documented as not setting
2932               an exception, and I don't want to change that.
2933               When PyType_Ready() can't proceed, it won't
2934               set the "ready" flag, so future attempts to ready
2935               the same type will call it again -- hopefully
2936               in a context that propagates the exception out.
2937            */
2938            PyErr_Clear();
2939            return NULL;
2940        }
2941        mro = type->tp_mro;
2942        if (mro == NULL) {
2943            return NULL;
2944        }
2945    }
2946
2947    res = NULL;
2948    /* keep a strong reference to mro because type->tp_mro can be replaced
2949       during PyDict_GetItem(dict, name)  */
2950    Py_INCREF(mro);
2951    assert(PyTuple_Check(mro));
2952    n = PyTuple_GET_SIZE(mro);
2953    for (i = 0; i < n; i++) {
2954        base = PyTuple_GET_ITEM(mro, i);
2955        assert(PyType_Check(base));
2956        dict = ((PyTypeObject *)base)->tp_dict;
2957        assert(dict && PyDict_Check(dict));
2958        res = PyDict_GetItem(dict, name);
2959        if (res != NULL)
2960            break;
2961    }
2962    Py_DECREF(mro);
2963
2964    if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
2965        h = MCACHE_HASH_METHOD(type, name);
2966        method_cache[h].version = type->tp_version_tag;
2967        method_cache[h].value = res;  /* borrowed */
2968        Py_INCREF(name);
2969        assert(((PyASCIIObject *)(name))->hash != -1);
2970#if MCACHE_STATS
2971        if (method_cache[h].name != Py_None && method_cache[h].name != name)
2972            method_cache_collisions++;
2973        else
2974            method_cache_misses++;
2975#endif
2976        Py_SETREF(method_cache[h].name, name);
2977    }
2978    return res;
2979}
2980
2981PyObject *
2982_PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2983{
2984    PyObject *oname;
2985    oname = _PyUnicode_FromId(name);   /* borrowed */
2986    if (oname == NULL)
2987        return NULL;
2988    return _PyType_Lookup(type, oname);
2989}
2990
2991/* This is similar to PyObject_GenericGetAttr(),
2992   but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2993static PyObject *
2994type_getattro(PyTypeObject *type, PyObject *name)
2995{
2996    PyTypeObject *metatype = Py_TYPE(type);
2997    PyObject *meta_attribute, *attribute;
2998    descrgetfunc meta_get;
2999
3000    if (!PyUnicode_Check(name)) {
3001        PyErr_Format(PyExc_TypeError,
3002                     "attribute name must be string, not '%.200s'",
3003                     name->ob_type->tp_name);
3004        return NULL;
3005    }
3006
3007    /* Initialize this type (we'll assume the metatype is initialized) */
3008    if (type->tp_dict == NULL) {
3009        if (PyType_Ready(type) < 0)
3010            return NULL;
3011    }
3012
3013    /* No readable descriptor found yet */
3014    meta_get = NULL;
3015
3016    /* Look for the attribute in the metatype */
3017    meta_attribute = _PyType_Lookup(metatype, name);
3018
3019    if (meta_attribute != NULL) {
3020        meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
3021
3022        if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
3023            /* Data descriptors implement tp_descr_set to intercept
3024             * writes. Assume the attribute is not overridden in
3025             * type's tp_dict (and bases): call the descriptor now.
3026             */
3027            return meta_get(meta_attribute, (PyObject *)type,
3028                            (PyObject *)metatype);
3029        }
3030        Py_INCREF(meta_attribute);
3031    }
3032
3033    /* No data descriptor found on metatype. Look in tp_dict of this
3034     * type and its bases */
3035    attribute = _PyType_Lookup(type, name);
3036    if (attribute != NULL) {
3037        /* Implement descriptor functionality, if any */
3038        descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
3039
3040        Py_XDECREF(meta_attribute);
3041
3042        if (local_get != NULL) {
3043            /* NULL 2nd argument indicates the descriptor was
3044             * found on the target object itself (or a base)  */
3045            return local_get(attribute, (PyObject *)NULL,
3046                             (PyObject *)type);
3047        }
3048
3049        Py_INCREF(attribute);
3050        return attribute;
3051    }
3052
3053    /* No attribute found in local __dict__ (or bases): use the
3054     * descriptor from the metatype, if any */
3055    if (meta_get != NULL) {
3056        PyObject *res;
3057        res = meta_get(meta_attribute, (PyObject *)type,
3058                       (PyObject *)metatype);
3059        Py_DECREF(meta_attribute);
3060        return res;
3061    }
3062
3063    /* If an ordinary attribute was found on the metatype, return it now */
3064    if (meta_attribute != NULL) {
3065        return meta_attribute;
3066    }
3067
3068    /* Give up */
3069    PyErr_Format(PyExc_AttributeError,
3070                 "type object '%.50s' has no attribute '%U'",
3071                 type->tp_name, name);
3072    return NULL;
3073}
3074
3075static int
3076type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
3077{
3078    if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3079        PyErr_Format(
3080            PyExc_TypeError,
3081            "can't set attributes of built-in/extension type '%s'",
3082            type->tp_name);
3083        return -1;
3084    }
3085    if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
3086        return -1;
3087    return update_slot(type, name);
3088}
3089
3090extern void
3091_PyDictKeys_DecRef(PyDictKeysObject *keys);
3092
3093static void
3094type_dealloc(PyTypeObject *type)
3095{
3096    PyHeapTypeObject *et;
3097    PyObject *tp, *val, *tb;
3098
3099    /* Assert this is a heap-allocated type object */
3100    assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
3101    _PyObject_GC_UNTRACK(type);
3102    PyErr_Fetch(&tp, &val, &tb);
3103    remove_all_subclasses(type, type->tp_bases);
3104    PyErr_Restore(tp, val, tb);
3105    PyObject_ClearWeakRefs((PyObject *)type);
3106    et = (PyHeapTypeObject *)type;
3107    Py_XDECREF(type->tp_base);
3108    Py_XDECREF(type->tp_dict);
3109    Py_XDECREF(type->tp_bases);
3110    Py_XDECREF(type->tp_mro);
3111    Py_XDECREF(type->tp_cache);
3112    Py_XDECREF(type->tp_subclasses);
3113    /* A type's tp_doc is heap allocated, unlike the tp_doc slots
3114     * of most other objects.  It's okay to cast it to char *.
3115     */
3116    PyObject_Free((char *)type->tp_doc);
3117    Py_XDECREF(et->ht_name);
3118    Py_XDECREF(et->ht_qualname);
3119    Py_XDECREF(et->ht_slots);
3120    if (et->ht_cached_keys)
3121        _PyDictKeys_DecRef(et->ht_cached_keys);
3122    Py_TYPE(type)->tp_free((PyObject *)type);
3123}
3124
3125static PyObject *
3126type_subclasses(PyTypeObject *type, PyObject *args_ignored)
3127{
3128    PyObject *list, *raw, *ref;
3129    Py_ssize_t i;
3130
3131    list = PyList_New(0);
3132    if (list == NULL)
3133        return NULL;
3134    raw = type->tp_subclasses;
3135    if (raw == NULL)
3136        return list;
3137    assert(PyDict_CheckExact(raw));
3138    i = 0;
3139    while (PyDict_Next(raw, &i, NULL, &ref)) {
3140        assert(PyWeakref_CheckRef(ref));
3141        ref = PyWeakref_GET_OBJECT(ref);
3142        if (ref != Py_None) {
3143            if (PyList_Append(list, ref) < 0) {
3144                Py_DECREF(list);
3145                return NULL;
3146            }
3147        }
3148    }
3149    return list;
3150}
3151
3152static PyObject *
3153type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
3154{
3155    return PyDict_New();
3156}
3157
3158/*
3159   Merge the __dict__ of aclass into dict, and recursively also all
3160   the __dict__s of aclass's base classes.  The order of merging isn't
3161   defined, as it's expected that only the final set of dict keys is
3162   interesting.
3163   Return 0 on success, -1 on error.
3164*/
3165
3166static int
3167merge_class_dict(PyObject *dict, PyObject *aclass)
3168{
3169    PyObject *classdict;
3170    PyObject *bases;
3171    _Py_IDENTIFIER(__bases__);
3172
3173    assert(PyDict_Check(dict));
3174    assert(aclass);
3175
3176    /* Merge in the type's dict (if any). */
3177    classdict = _PyObject_GetAttrId(aclass, &PyId___dict__);
3178    if (classdict == NULL)
3179        PyErr_Clear();
3180    else {
3181        int status = PyDict_Update(dict, classdict);
3182        Py_DECREF(classdict);
3183        if (status < 0)
3184            return -1;
3185    }
3186
3187    /* Recursively merge in the base types' (if any) dicts. */
3188    bases = _PyObject_GetAttrId(aclass, &PyId___bases__);
3189    if (bases == NULL)
3190        PyErr_Clear();
3191    else {
3192        /* We have no guarantee that bases is a real tuple */
3193        Py_ssize_t i, n;
3194        n = PySequence_Size(bases); /* This better be right */
3195        if (n < 0)
3196            PyErr_Clear();
3197        else {
3198            for (i = 0; i < n; i++) {
3199                int status;
3200                PyObject *base = PySequence_GetItem(bases, i);
3201                if (base == NULL) {
3202                    Py_DECREF(bases);
3203                    return -1;
3204                }
3205                status = merge_class_dict(dict, base);
3206                Py_DECREF(base);
3207                if (status < 0) {
3208                    Py_DECREF(bases);
3209                    return -1;
3210                }
3211            }
3212        }
3213        Py_DECREF(bases);
3214    }
3215    return 0;
3216}
3217
3218/* __dir__ for type objects: returns __dict__ and __bases__.
3219   We deliberately don't suck up its __class__, as methods belonging to the
3220   metaclass would probably be more confusing than helpful.
3221*/
3222static PyObject *
3223type_dir(PyObject *self, PyObject *args)
3224{
3225    PyObject *result = NULL;
3226    PyObject *dict = PyDict_New();
3227
3228    if (dict != NULL && merge_class_dict(dict, self) == 0)
3229        result = PyDict_Keys(dict);
3230
3231    Py_XDECREF(dict);
3232    return result;
3233}
3234
3235static PyObject*
3236type_sizeof(PyObject *self, PyObject *args_unused)
3237{
3238    Py_ssize_t size;
3239    PyTypeObject *type = (PyTypeObject*)self;
3240    if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
3241        PyHeapTypeObject* et = (PyHeapTypeObject*)type;
3242        size = sizeof(PyHeapTypeObject);
3243        if (et->ht_cached_keys)
3244            size += _PyDict_KeysSize(et->ht_cached_keys);
3245    }
3246    else
3247        size = sizeof(PyTypeObject);
3248    return PyLong_FromSsize_t(size);
3249}
3250
3251static PyMethodDef type_methods[] = {
3252    {"mro", (PyCFunction)mro_external, METH_NOARGS,
3253     PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
3254    {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
3255     PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
3256    {"__prepare__", (PyCFunction)type_prepare,
3257     METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3258     PyDoc_STR("__prepare__() -> dict\n"
3259               "used to create the namespace for the class statement")},
3260    {"__instancecheck__", type___instancecheck__, METH_O,
3261     PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
3262    {"__subclasscheck__", type___subclasscheck__, METH_O,
3263     PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
3264    {"__dir__", type_dir, METH_NOARGS,
3265     PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")},
3266    {"__sizeof__",      type_sizeof,       METH_NOARGS,
3267     "__sizeof__() -> int\nreturn memory consumption of the type object"},
3268    {0}
3269};
3270
3271PyDoc_STRVAR(type_doc,
3272/* this text signature cannot be accurate yet.  will fix.  --larry */
3273"type(object_or_name, bases, dict)\n"
3274"type(object) -> the object's type\n"
3275"type(name, bases, dict) -> a new type");
3276
3277static int
3278type_traverse(PyTypeObject *type, visitproc visit, void *arg)
3279{
3280    /* Because of type_is_gc(), the collector only calls this
3281       for heaptypes. */
3282    if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3283        char msg[200];
3284        sprintf(msg, "type_traverse() called for non-heap type '%.100s'",
3285                type->tp_name);
3286        Py_FatalError(msg);
3287    }
3288
3289    Py_VISIT(type->tp_dict);
3290    Py_VISIT(type->tp_cache);
3291    Py_VISIT(type->tp_mro);
3292    Py_VISIT(type->tp_bases);
3293    Py_VISIT(type->tp_base);
3294
3295    /* There's no need to visit type->tp_subclasses or
3296       ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
3297       in cycles; tp_subclasses is a list of weak references,
3298       and slots is a tuple of strings. */
3299
3300    return 0;
3301}
3302
3303static int
3304type_clear(PyTypeObject *type)
3305{
3306    PyDictKeysObject *cached_keys;
3307    /* Because of type_is_gc(), the collector only calls this
3308       for heaptypes. */
3309    assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
3310
3311    /* We need to invalidate the method cache carefully before clearing
3312       the dict, so that other objects caught in a reference cycle
3313       don't start calling destroyed methods.
3314
3315       Otherwise, the only field we need to clear is tp_mro, which is
3316       part of a hard cycle (its first element is the class itself) that
3317       won't be broken otherwise (it's a tuple and tuples don't have a
3318       tp_clear handler).  None of the other fields need to be
3319       cleared, and here's why:
3320
3321       tp_cache:
3322           Not used; if it were, it would be a dict.
3323
3324       tp_bases, tp_base:
3325           If these are involved in a cycle, there must be at least
3326           one other, mutable object in the cycle, e.g. a base
3327           class's dict; the cycle will be broken that way.
3328
3329       tp_subclasses:
3330           A dict of weak references can't be part of a cycle; and
3331           dicts have their own tp_clear.
3332
3333       slots (in PyHeapTypeObject):
3334           A tuple of strings can't be part of a cycle.
3335    */
3336
3337    PyType_Modified(type);
3338    cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys;
3339    if (cached_keys != NULL) {
3340        ((PyHeapTypeObject *)type)->ht_cached_keys = NULL;
3341        _PyDictKeys_DecRef(cached_keys);
3342    }
3343    if (type->tp_dict)
3344        PyDict_Clear(type->tp_dict);
3345    Py_CLEAR(type->tp_mro);
3346
3347    return 0;
3348}
3349
3350static int
3351type_is_gc(PyTypeObject *type)
3352{
3353    return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
3354}
3355
3356PyTypeObject PyType_Type = {
3357    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3358    "type",                                     /* tp_name */
3359    sizeof(PyHeapTypeObject),                   /* tp_basicsize */
3360    sizeof(PyMemberDef),                        /* tp_itemsize */
3361    (destructor)type_dealloc,                   /* tp_dealloc */
3362    0,                                          /* tp_print */
3363    0,                                          /* tp_getattr */
3364    0,                                          /* tp_setattr */
3365    0,                                          /* tp_reserved */
3366    (reprfunc)type_repr,                        /* tp_repr */
3367    0,                                          /* tp_as_number */
3368    0,                                          /* tp_as_sequence */
3369    0,                                          /* tp_as_mapping */
3370    0,                                          /* tp_hash */
3371    (ternaryfunc)type_call,                     /* tp_call */
3372    0,                                          /* tp_str */
3373    (getattrofunc)type_getattro,                /* tp_getattro */
3374    (setattrofunc)type_setattro,                /* tp_setattro */
3375    0,                                          /* tp_as_buffer */
3376    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3377        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS,         /* tp_flags */
3378    type_doc,                                   /* tp_doc */
3379    (traverseproc)type_traverse,                /* tp_traverse */
3380    (inquiry)type_clear,                        /* tp_clear */
3381    0,                                          /* tp_richcompare */
3382    offsetof(PyTypeObject, tp_weaklist),        /* tp_weaklistoffset */
3383    0,                                          /* tp_iter */
3384    0,                                          /* tp_iternext */
3385    type_methods,                               /* tp_methods */
3386    type_members,                               /* tp_members */
3387    type_getsets,                               /* tp_getset */
3388    0,                                          /* tp_base */
3389    0,                                          /* tp_dict */
3390    0,                                          /* tp_descr_get */
3391    0,                                          /* tp_descr_set */
3392    offsetof(PyTypeObject, tp_dict),            /* tp_dictoffset */
3393    type_init,                                  /* tp_init */
3394    0,                                          /* tp_alloc */
3395    type_new,                                   /* tp_new */
3396    PyObject_GC_Del,                            /* tp_free */
3397    (inquiry)type_is_gc,                        /* tp_is_gc */
3398};
3399
3400
3401/* The base type of all types (eventually)... except itself. */
3402
3403/* You may wonder why object.__new__() only complains about arguments
3404   when object.__init__() is not overridden, and vice versa.
3405
3406   Consider the use cases:
3407
3408   1. When neither is overridden, we want to hear complaints about
3409      excess (i.e., any) arguments, since their presence could
3410      indicate there's a bug.
3411
3412   2. When defining an Immutable type, we are likely to override only
3413      __new__(), since __init__() is called too late to initialize an
3414      Immutable object.  Since __new__() defines the signature for the
3415      type, it would be a pain to have to override __init__() just to
3416      stop it from complaining about excess arguments.
3417
3418   3. When defining a Mutable type, we are likely to override only
3419      __init__().  So here the converse reasoning applies: we don't
3420      want to have to override __new__() just to stop it from
3421      complaining.
3422
3423   4. When __init__() is overridden, and the subclass __init__() calls
3424      object.__init__(), the latter should complain about excess
3425      arguments; ditto for __new__().
3426
3427   Use cases 2 and 3 make it unattractive to unconditionally check for
3428   excess arguments.  The best solution that addresses all four use
3429   cases is as follows: __init__() complains about excess arguments
3430   unless __new__() is overridden and __init__() is not overridden
3431   (IOW, if __init__() is overridden or __new__() is not overridden);
3432   symmetrically, __new__() complains about excess arguments unless
3433   __init__() is overridden and __new__() is not overridden
3434   (IOW, if __new__() is overridden or __init__() is not overridden).
3435
3436   However, for backwards compatibility, this breaks too much code.
3437   Therefore, in 2.6, we'll *warn* about excess arguments when both
3438   methods are overridden; for all other cases we'll use the above
3439   rules.
3440
3441*/
3442
3443/* Forward */
3444static PyObject *
3445object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3446
3447static int
3448excess_args(PyObject *args, PyObject *kwds)
3449{
3450    return PyTuple_GET_SIZE(args) ||
3451        (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
3452}
3453
3454static int
3455object_init(PyObject *self, PyObject *args, PyObject *kwds)
3456{
3457    int err = 0;
3458    PyTypeObject *type = Py_TYPE(self);
3459    if (excess_args(args, kwds) &&
3460        (type->tp_new == object_new || type->tp_init != object_init)) {
3461        PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters");
3462        err = -1;
3463    }
3464    return err;
3465}
3466
3467static PyObject *
3468object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3469{
3470    if (excess_args(args, kwds) &&
3471        (type->tp_init == object_init || type->tp_new != object_new)) {
3472        PyErr_SetString(PyExc_TypeError, "object() takes no parameters");
3473        return NULL;
3474    }
3475
3476    if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
3477        PyObject *abstract_methods = NULL;
3478        PyObject *builtins;
3479        PyObject *sorted;
3480        PyObject *sorted_methods = NULL;
3481        PyObject *joined = NULL;
3482        PyObject *comma;
3483        _Py_static_string(comma_id, ", ");
3484        _Py_IDENTIFIER(sorted);
3485
3486        /* Compute ", ".join(sorted(type.__abstractmethods__))
3487           into joined. */
3488        abstract_methods = type_abstractmethods(type, NULL);
3489        if (abstract_methods == NULL)
3490            goto error;
3491        builtins = PyEval_GetBuiltins();
3492        if (builtins == NULL)
3493            goto error;
3494        sorted = _PyDict_GetItemId(builtins, &PyId_sorted);
3495        if (sorted == NULL)
3496            goto error;
3497        sorted_methods = PyObject_CallFunctionObjArgs(sorted,
3498                                                      abstract_methods,
3499                                                      NULL);
3500        if (sorted_methods == NULL)
3501            goto error;
3502        comma = _PyUnicode_FromId(&comma_id);
3503        if (comma == NULL)
3504            goto error;
3505        joined = PyUnicode_Join(comma, sorted_methods);
3506        if (joined == NULL)
3507            goto error;
3508
3509        PyErr_Format(PyExc_TypeError,
3510                     "Can't instantiate abstract class %s "
3511                     "with abstract methods %U",
3512                     type->tp_name,
3513                     joined);
3514    error:
3515        Py_XDECREF(joined);
3516        Py_XDECREF(sorted_methods);
3517        Py_XDECREF(abstract_methods);
3518        return NULL;
3519    }
3520    return type->tp_alloc(type, 0);
3521}
3522
3523static void
3524object_dealloc(PyObject *self)
3525{
3526    Py_TYPE(self)->tp_free(self);
3527}
3528
3529static PyObject *
3530object_repr(PyObject *self)
3531{
3532    PyTypeObject *type;
3533    PyObject *mod, *name, *rtn;
3534
3535    type = Py_TYPE(self);
3536    mod = type_module(type, NULL);
3537    if (mod == NULL)
3538        PyErr_Clear();
3539    else if (!PyUnicode_Check(mod)) {
3540        Py_DECREF(mod);
3541        mod = NULL;
3542    }
3543    name = type_qualname(type, NULL);
3544    if (name == NULL) {
3545        Py_XDECREF(mod);
3546        return NULL;
3547    }
3548    if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
3549        rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3550    else
3551        rtn = PyUnicode_FromFormat("<%s object at %p>",
3552                                  type->tp_name, self);
3553    Py_XDECREF(mod);
3554    Py_DECREF(name);
3555    return rtn;
3556}
3557
3558static PyObject *
3559object_str(PyObject *self)
3560{
3561    unaryfunc f;
3562
3563    f = Py_TYPE(self)->tp_repr;
3564    if (f == NULL)
3565        f = object_repr;
3566    return f(self);
3567}
3568
3569static PyObject *
3570object_richcompare(PyObject *self, PyObject *other, int op)
3571{
3572    PyObject *res;
3573
3574    switch (op) {
3575
3576    case Py_EQ:
3577        /* Return NotImplemented instead of False, so if two
3578           objects are compared, both get a chance at the
3579           comparison.  See issue #1393. */
3580        res = (self == other) ? Py_True : Py_NotImplemented;
3581        Py_INCREF(res);
3582        break;
3583
3584    case Py_NE:
3585        /* By default, __ne__() delegates to __eq__() and inverts the result,
3586           unless the latter returns NotImplemented. */
3587        if (self->ob_type->tp_richcompare == NULL) {
3588            res = Py_NotImplemented;
3589            Py_INCREF(res);
3590            break;
3591        }
3592        res = (*self->ob_type->tp_richcompare)(self, other, Py_EQ);
3593        if (res != NULL && res != Py_NotImplemented) {
3594            int ok = PyObject_IsTrue(res);
3595            Py_DECREF(res);
3596            if (ok < 0)
3597                res = NULL;
3598            else {
3599                if (ok)
3600                    res = Py_False;
3601                else
3602                    res = Py_True;
3603                Py_INCREF(res);
3604            }
3605        }
3606        break;
3607
3608    default:
3609        res = Py_NotImplemented;
3610        Py_INCREF(res);
3611        break;
3612    }
3613
3614    return res;
3615}
3616
3617static PyObject *
3618object_get_class(PyObject *self, void *closure)
3619{
3620    Py_INCREF(Py_TYPE(self));
3621    return (PyObject *)(Py_TYPE(self));
3622}
3623
3624static int
3625compatible_with_tp_base(PyTypeObject *child)
3626{
3627    PyTypeObject *parent = child->tp_base;
3628    return (parent != NULL &&
3629            child->tp_basicsize == parent->tp_basicsize &&
3630            child->tp_itemsize == parent->tp_itemsize &&
3631            child->tp_dictoffset == parent->tp_dictoffset &&
3632            child->tp_weaklistoffset == parent->tp_weaklistoffset &&
3633            ((child->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3634             (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) &&
3635            (child->tp_dealloc == subtype_dealloc ||
3636             child->tp_dealloc == parent->tp_dealloc));
3637}
3638
3639static int
3640same_slots_added(PyTypeObject *a, PyTypeObject *b)
3641{
3642    PyTypeObject *base = a->tp_base;
3643    Py_ssize_t size;
3644    PyObject *slots_a, *slots_b;
3645
3646    assert(base == b->tp_base);
3647    size = base->tp_basicsize;
3648    if (a->tp_dictoffset == size && b->tp_dictoffset == size)
3649        size += sizeof(PyObject *);
3650    if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
3651        size += sizeof(PyObject *);
3652
3653    /* Check slots compliance */
3654    if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3655        !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3656        return 0;
3657    }
3658    slots_a = ((PyHeapTypeObject *)a)->ht_slots;
3659    slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3660    if (slots_a && slots_b) {
3661        if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3662            return 0;
3663        size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3664    }
3665    return size == a->tp_basicsize && size == b->tp_basicsize;
3666}
3667
3668static int
3669compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr)
3670{
3671    PyTypeObject *newbase, *oldbase;
3672
3673    if (newto->tp_free != oldto->tp_free) {
3674        PyErr_Format(PyExc_TypeError,
3675                     "%s assignment: "
3676                     "'%s' deallocator differs from '%s'",
3677                     attr,
3678                     newto->tp_name,
3679                     oldto->tp_name);
3680        return 0;
3681    }
3682    /*
3683     It's tricky to tell if two arbitrary types are sufficiently compatible as
3684     to be interchangeable; e.g., even if they have the same tp_basicsize, they
3685     might have totally different struct fields. It's much easier to tell if a
3686     type and its supertype are compatible; e.g., if they have the same
3687     tp_basicsize, then that means they have identical fields. So to check
3688     whether two arbitrary types are compatible, we first find the highest
3689     supertype that each is compatible with, and then if those supertypes are
3690     compatible then the original types must also be compatible.
3691    */
3692    newbase = newto;
3693    oldbase = oldto;
3694    while (compatible_with_tp_base(newbase))
3695        newbase = newbase->tp_base;
3696    while (compatible_with_tp_base(oldbase))
3697        oldbase = oldbase->tp_base;
3698    if (newbase != oldbase &&
3699        (newbase->tp_base != oldbase->tp_base ||
3700         !same_slots_added(newbase, oldbase))) {
3701        PyErr_Format(PyExc_TypeError,
3702                     "%s assignment: "
3703                     "'%s' object layout differs from '%s'",
3704                     attr,
3705                     newto->tp_name,
3706                     oldto->tp_name);
3707        return 0;
3708    }
3709
3710    return 1;
3711}
3712
3713static int
3714object_set_class(PyObject *self, PyObject *value, void *closure)
3715{
3716    PyTypeObject *oldto = Py_TYPE(self);
3717    PyTypeObject *newto;
3718
3719    if (value == NULL) {
3720        PyErr_SetString(PyExc_TypeError,
3721                        "can't delete __class__ attribute");
3722        return -1;
3723    }
3724    if (!PyType_Check(value)) {
3725        PyErr_Format(PyExc_TypeError,
3726          "__class__ must be set to a class, not '%s' object",
3727          Py_TYPE(value)->tp_name);
3728        return -1;
3729    }
3730    newto = (PyTypeObject *)value;
3731    /* In versions of CPython prior to 3.5, the code in
3732       compatible_for_assignment was not set up to correctly check for memory
3733       layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
3734       disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
3735       HEAPTYPE.
3736
3737       During the 3.5 development cycle, we fixed the code in
3738       compatible_for_assignment to correctly check compatibility between
3739       arbitrary types, and started allowing __class__ assignment in all cases
3740       where the old and new types did in fact have compatible slots and
3741       memory layout (regardless of whether they were implemented as HEAPTYPEs
3742       or not).
3743
3744       Just before 3.5 was released, though, we discovered that this led to
3745       problems with immutable types like int, where the interpreter assumes
3746       they are immutable and interns some values. Formerly this wasn't a
3747       problem, because they really were immutable -- in particular, all the
3748       types where the interpreter applied this interning trick happened to
3749       also be statically allocated, so the old HEAPTYPE rules were
3750       "accidentally" stopping them from allowing __class__ assignment. But
3751       with the changes to __class__ assignment, we started allowing code like
3752
3753         class MyInt(int):
3754             ...
3755         # Modifies the type of *all* instances of 1 in the whole program,
3756         # including future instances (!), because the 1 object is interned.
3757         (1).__class__ = MyInt
3758
3759       (see https://bugs.python.org/issue24912).
3760
3761       In theory the proper fix would be to identify which classes rely on
3762       this invariant and somehow disallow __class__ assignment only for them,
3763       perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
3764       "blacklisting" approach). But in practice, since this problem wasn't
3765       noticed late in the 3.5 RC cycle, we're taking the conservative
3766       approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
3767       to have, plus a "whitelist". For now, the whitelist consists only of
3768       ModuleType subtypes, since those are the cases that motivated the patch
3769       in the first place -- see https://bugs.python.org/issue22986 -- and
3770       since module objects are mutable we can be sure that they are
3771       definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
3772       ModuleType subtype -> ModuleType subtype.
3773
3774       So far as we know, all the code beyond the following 'if' statement
3775       will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
3776       needed only to protect that subset of non-HEAPTYPE classes for which
3777       the interpreter has baked in the assumption that all instances are
3778       truly immutable.
3779    */
3780    if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
3781          PyType_IsSubtype(oldto, &PyModule_Type)) &&
3782        (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3783         !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
3784        PyErr_Format(PyExc_TypeError,
3785                     "__class__ assignment only supported for heap types "
3786                     "or ModuleType subclasses");
3787        return -1;
3788    }
3789
3790    if (compatible_for_assignment(oldto, newto, "__class__")) {
3791        if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3792            Py_INCREF(newto);
3793        Py_TYPE(self) = newto;
3794        if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3795            Py_DECREF(oldto);
3796        return 0;
3797    }
3798    else {
3799        return -1;
3800    }
3801}
3802
3803static PyGetSetDef object_getsets[] = {
3804    {"__class__", object_get_class, object_set_class,
3805     PyDoc_STR("the object's class")},
3806    {0}
3807};
3808
3809
3810/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
3811   We fall back to helpers in copyreg for:
3812   - pickle protocols < 2
3813   - calculating the list of slot names (done only once per class)
3814   - the __newobj__ function (which is used as a token but never called)
3815*/
3816
3817static PyObject *
3818import_copyreg(void)
3819{
3820    PyObject *copyreg_str;
3821    PyObject *copyreg_module;
3822    PyInterpreterState *interp = PyThreadState_GET()->interp;
3823    _Py_IDENTIFIER(copyreg);
3824
3825    copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3826    if (copyreg_str == NULL) {
3827        return NULL;
3828    }
3829    /* Try to fetch cached copy of copyreg from sys.modules first in an
3830       attempt to avoid the import overhead. Previously this was implemented
3831       by storing a reference to the cached module in a static variable, but
3832       this broke when multiple embedded interpreters were in use (see issue
3833       #17408 and #19088). */
3834    copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3835    if (copyreg_module != NULL) {
3836        Py_INCREF(copyreg_module);
3837        return copyreg_module;
3838    }
3839    if (PyErr_Occurred()) {
3840        return NULL;
3841    }
3842    return PyImport_Import(copyreg_str);
3843}
3844
3845static PyObject *
3846_PyType_GetSlotNames(PyTypeObject *cls)
3847{
3848    PyObject *copyreg;
3849    PyObject *slotnames;
3850    _Py_IDENTIFIER(__slotnames__);
3851    _Py_IDENTIFIER(_slotnames);
3852
3853    assert(PyType_Check(cls));
3854
3855    /* Get the slot names from the cache in the class if possible. */
3856    slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__);
3857    if (slotnames != NULL) {
3858        if (slotnames != Py_None && !PyList_Check(slotnames)) {
3859            PyErr_Format(PyExc_TypeError,
3860                         "%.200s.__slotnames__ should be a list or None, "
3861                         "not %.200s",
3862                         cls->tp_name, Py_TYPE(slotnames)->tp_name);
3863            return NULL;
3864        }
3865        Py_INCREF(slotnames);
3866        return slotnames;
3867    }
3868    else {
3869        if (PyErr_Occurred()) {
3870            return NULL;
3871        }
3872        /* The class does not have the slot names cached yet. */
3873    }
3874
3875    copyreg = import_copyreg();
3876    if (copyreg == NULL)
3877        return NULL;
3878
3879    /* Use _slotnames function from the copyreg module to find the slots
3880       by this class and its bases. This function will cache the result
3881       in __slotnames__. */
3882    slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames,
3883                                              cls, NULL);
3884    Py_DECREF(copyreg);
3885    if (slotnames == NULL)
3886        return NULL;
3887
3888    if (slotnames != Py_None && !PyList_Check(slotnames)) {
3889        PyErr_SetString(PyExc_TypeError,
3890                        "copyreg._slotnames didn't return a list or None");
3891        Py_DECREF(slotnames);
3892        return NULL;
3893    }
3894
3895    return slotnames;
3896}
3897
3898static PyObject *
3899_PyObject_GetState(PyObject *obj, int required)
3900{
3901    PyObject *state;
3902    PyObject *getstate;
3903    _Py_IDENTIFIER(__getstate__);
3904
3905    getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
3906    if (getstate == NULL) {
3907        PyObject *slotnames;
3908
3909        if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3910            return NULL;
3911        }
3912        PyErr_Clear();
3913
3914        if (required && obj->ob_type->tp_itemsize) {
3915            PyErr_Format(PyExc_TypeError,
3916                         "can't pickle %.200s objects",
3917                         Py_TYPE(obj)->tp_name);
3918            return NULL;
3919        }
3920
3921        {
3922            PyObject **dict;
3923            dict = _PyObject_GetDictPtr(obj);
3924            /* It is possible that the object's dict is not initialized
3925               yet. In this case, we will return None for the state.
3926               We also return None if the dict is empty to make the behavior
3927               consistent regardless whether the dict was initialized or not.
3928               This make unit testing easier. */
3929            if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3930                state = *dict;
3931            }
3932            else {
3933                state = Py_None;
3934            }
3935            Py_INCREF(state);
3936        }
3937
3938        slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3939        if (slotnames == NULL) {
3940            Py_DECREF(state);
3941            return NULL;
3942        }
3943
3944        assert(slotnames == Py_None || PyList_Check(slotnames));
3945        if (required) {
3946            Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize;
3947            if (obj->ob_type->tp_dictoffset)
3948                basicsize += sizeof(PyObject *);
3949            if (obj->ob_type->tp_weaklistoffset)
3950                basicsize += sizeof(PyObject *);
3951            if (slotnames != Py_None)
3952                basicsize += sizeof(PyObject *) * Py_SIZE(slotnames);
3953            if (obj->ob_type->tp_basicsize > basicsize) {
3954                Py_DECREF(slotnames);
3955                Py_DECREF(state);
3956                PyErr_Format(PyExc_TypeError,
3957                             "can't pickle %.200s objects",
3958                             Py_TYPE(obj)->tp_name);
3959                return NULL;
3960            }
3961        }
3962
3963        if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3964            PyObject *slots;
3965            Py_ssize_t slotnames_size, i;
3966
3967            slots = PyDict_New();
3968            if (slots == NULL) {
3969                Py_DECREF(slotnames);
3970                Py_DECREF(state);
3971                return NULL;
3972            }
3973
3974            slotnames_size = Py_SIZE(slotnames);
3975            for (i = 0; i < slotnames_size; i++) {
3976                PyObject *name, *value;
3977
3978                name = PyList_GET_ITEM(slotnames, i);
3979                Py_INCREF(name);
3980                value = PyObject_GetAttr(obj, name);
3981                if (value == NULL) {
3982                    Py_DECREF(name);
3983                    if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3984                        goto error;
3985                    }
3986                    /* It is not an error if the attribute is not present. */
3987                    PyErr_Clear();
3988                }
3989                else {
3990                    int err = PyDict_SetItem(slots, name, value);
3991                    Py_DECREF(name);
3992                    Py_DECREF(value);
3993                    if (err) {
3994                        goto error;
3995                    }
3996                }
3997
3998                /* The list is stored on the class so it may mutate while we
3999                   iterate over it */
4000                if (slotnames_size != Py_SIZE(slotnames)) {
4001                    PyErr_Format(PyExc_RuntimeError,
4002                                 "__slotsname__ changed size during iteration");
4003                    goto error;
4004                }
4005
4006                /* We handle errors within the loop here. */
4007                if (0) {
4008                  error:
4009                    Py_DECREF(slotnames);
4010                    Py_DECREF(slots);
4011                    Py_DECREF(state);
4012                    return NULL;
4013                }
4014            }
4015
4016            /* If we found some slot attributes, pack them in a tuple along
4017               the original attribute dictionary. */
4018            if (PyDict_Size(slots) > 0) {
4019                PyObject *state2;
4020
4021                state2 = PyTuple_Pack(2, state, slots);
4022                Py_DECREF(state);
4023                if (state2 == NULL) {
4024                    Py_DECREF(slotnames);
4025                    Py_DECREF(slots);
4026                    return NULL;
4027                }
4028                state = state2;
4029            }
4030            Py_DECREF(slots);
4031        }
4032        Py_DECREF(slotnames);
4033    }
4034    else { /* getstate != NULL */
4035        state = PyObject_CallObject(getstate, NULL);
4036        Py_DECREF(getstate);
4037        if (state == NULL)
4038            return NULL;
4039    }
4040
4041    return state;
4042}
4043
4044static int
4045_PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
4046{
4047    PyObject *getnewargs, *getnewargs_ex;
4048    _Py_IDENTIFIER(__getnewargs_ex__);
4049    _Py_IDENTIFIER(__getnewargs__);
4050
4051    if (args == NULL || kwargs == NULL) {
4052        PyErr_BadInternalCall();
4053        return -1;
4054    }
4055
4056    /* We first attempt to fetch the arguments for __new__ by calling
4057       __getnewargs_ex__ on the object. */
4058    getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__);
4059    if (getnewargs_ex != NULL) {
4060        PyObject *newargs = PyObject_CallObject(getnewargs_ex, NULL);
4061        Py_DECREF(getnewargs_ex);
4062        if (newargs == NULL) {
4063            return -1;
4064        }
4065        if (!PyTuple_Check(newargs)) {
4066            PyErr_Format(PyExc_TypeError,
4067                         "__getnewargs_ex__ should return a tuple, "
4068                         "not '%.200s'", Py_TYPE(newargs)->tp_name);
4069            Py_DECREF(newargs);
4070            return -1;
4071        }
4072        if (Py_SIZE(newargs) != 2) {
4073            PyErr_Format(PyExc_ValueError,
4074                         "__getnewargs_ex__ should return a tuple of "
4075                         "length 2, not %zd", Py_SIZE(newargs));
4076            Py_DECREF(newargs);
4077            return -1;
4078        }
4079        *args = PyTuple_GET_ITEM(newargs, 0);
4080        Py_INCREF(*args);
4081        *kwargs = PyTuple_GET_ITEM(newargs, 1);
4082        Py_INCREF(*kwargs);
4083        Py_DECREF(newargs);
4084
4085        /* XXX We should perhaps allow None to be passed here. */
4086        if (!PyTuple_Check(*args)) {
4087            PyErr_Format(PyExc_TypeError,
4088                         "first item of the tuple returned by "
4089                         "__getnewargs_ex__ must be a tuple, not '%.200s'",
4090                         Py_TYPE(*args)->tp_name);
4091            Py_CLEAR(*args);
4092            Py_CLEAR(*kwargs);
4093            return -1;
4094        }
4095        if (!PyDict_Check(*kwargs)) {
4096            PyErr_Format(PyExc_TypeError,
4097                         "second item of the tuple returned by "
4098                         "__getnewargs_ex__ must be a dict, not '%.200s'",
4099                         Py_TYPE(*kwargs)->tp_name);
4100            Py_CLEAR(*args);
4101            Py_CLEAR(*kwargs);
4102            return -1;
4103        }
4104        return 0;
4105    } else if (PyErr_Occurred()) {
4106        return -1;
4107    }
4108
4109    /* The object does not have __getnewargs_ex__ so we fallback on using
4110       __getnewargs__ instead. */
4111    getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__);
4112    if (getnewargs != NULL) {
4113        *args = PyObject_CallObject(getnewargs, NULL);
4114        Py_DECREF(getnewargs);
4115        if (*args == NULL) {
4116            return -1;
4117        }
4118        if (!PyTuple_Check(*args)) {
4119            PyErr_Format(PyExc_TypeError,
4120                         "__getnewargs__ should return a tuple, "
4121                         "not '%.200s'", Py_TYPE(*args)->tp_name);
4122            Py_CLEAR(*args);
4123            return -1;
4124        }
4125        *kwargs = NULL;
4126        return 0;
4127    } else if (PyErr_Occurred()) {
4128        return -1;
4129    }
4130
4131    /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
4132       mean __new__ does not takes any arguments on this object, or that the
4133       object does not implement the reduce protocol for pickling or
4134       copying. */
4135    *args = NULL;
4136    *kwargs = NULL;
4137    return 0;
4138}
4139
4140static int
4141_PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
4142                       PyObject **dictitems)
4143{
4144    if (listitems == NULL || dictitems == NULL) {
4145        PyErr_BadInternalCall();
4146        return -1;
4147    }
4148
4149    if (!PyList_Check(obj)) {
4150        *listitems = Py_None;
4151        Py_INCREF(*listitems);
4152    }
4153    else {
4154        *listitems = PyObject_GetIter(obj);
4155        if (*listitems == NULL)
4156            return -1;
4157    }
4158
4159    if (!PyDict_Check(obj)) {
4160        *dictitems = Py_None;
4161        Py_INCREF(*dictitems);
4162    }
4163    else {
4164        PyObject *items;
4165        _Py_IDENTIFIER(items);
4166
4167        items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL);
4168        if (items == NULL) {
4169            Py_CLEAR(*listitems);
4170            return -1;
4171        }
4172        *dictitems = PyObject_GetIter(items);
4173        Py_DECREF(items);
4174        if (*dictitems == NULL) {
4175            Py_CLEAR(*listitems);
4176            return -1;
4177        }
4178    }
4179
4180    assert(*listitems != NULL && *dictitems != NULL);
4181
4182    return 0;
4183}
4184
4185static PyObject *
4186reduce_newobj(PyObject *obj)
4187{
4188    PyObject *args = NULL, *kwargs = NULL;
4189    PyObject *copyreg;
4190    PyObject *newobj, *newargs, *state, *listitems, *dictitems;
4191    PyObject *result;
4192    int hasargs;
4193
4194    if (Py_TYPE(obj)->tp_new == NULL) {
4195        PyErr_Format(PyExc_TypeError,
4196                     "can't pickle %.200s objects",
4197                     Py_TYPE(obj)->tp_name);
4198        return NULL;
4199    }
4200    if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
4201        return NULL;
4202
4203    copyreg = import_copyreg();
4204    if (copyreg == NULL) {
4205        Py_XDECREF(args);
4206        Py_XDECREF(kwargs);
4207        return NULL;
4208    }
4209    hasargs = (args != NULL);
4210    if (kwargs == NULL || PyDict_Size(kwargs) == 0) {
4211        _Py_IDENTIFIER(__newobj__);
4212        PyObject *cls;
4213        Py_ssize_t i, n;
4214
4215        Py_XDECREF(kwargs);
4216        newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
4217        Py_DECREF(copyreg);
4218        if (newobj == NULL) {
4219            Py_XDECREF(args);
4220            return NULL;
4221        }
4222        n = args ? PyTuple_GET_SIZE(args) : 0;
4223        newargs = PyTuple_New(n+1);
4224        if (newargs == NULL) {
4225            Py_XDECREF(args);
4226            Py_DECREF(newobj);
4227            return NULL;
4228        }
4229        cls = (PyObject *) Py_TYPE(obj);
4230        Py_INCREF(cls);
4231        PyTuple_SET_ITEM(newargs, 0, cls);
4232        for (i = 0; i < n; i++) {
4233            PyObject *v = PyTuple_GET_ITEM(args, i);
4234            Py_INCREF(v);
4235            PyTuple_SET_ITEM(newargs, i+1, v);
4236        }
4237        Py_XDECREF(args);
4238    }
4239    else if (args != NULL) {
4240        _Py_IDENTIFIER(__newobj_ex__);
4241
4242        newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
4243        Py_DECREF(copyreg);
4244        if (newobj == NULL) {
4245            Py_DECREF(args);
4246            Py_DECREF(kwargs);
4247            return NULL;
4248        }
4249        newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
4250        Py_DECREF(args);
4251        Py_DECREF(kwargs);
4252        if (newargs == NULL) {
4253            Py_DECREF(newobj);
4254            return NULL;
4255        }
4256    }
4257    else {
4258        /* args == NULL */
4259        Py_DECREF(kwargs);
4260        PyErr_BadInternalCall();
4261        return NULL;
4262    }
4263
4264    state = _PyObject_GetState(obj,
4265                !hasargs && !PyList_Check(obj) && !PyDict_Check(obj));
4266    if (state == NULL) {
4267        Py_DECREF(newobj);
4268        Py_DECREF(newargs);
4269        return NULL;
4270    }
4271    if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
4272        Py_DECREF(newobj);
4273        Py_DECREF(newargs);
4274        Py_DECREF(state);
4275        return NULL;
4276    }
4277
4278    result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
4279    Py_DECREF(newobj);
4280    Py_DECREF(newargs);
4281    Py_DECREF(state);
4282    Py_DECREF(listitems);
4283    Py_DECREF(dictitems);
4284    return result;
4285}
4286
4287/*
4288 * There were two problems when object.__reduce__ and object.__reduce_ex__
4289 * were implemented in the same function:
4290 *  - trying to pickle an object with a custom __reduce__ method that
4291 *    fell back to object.__reduce__ in certain circumstances led to
4292 *    infinite recursion at Python level and eventual RecursionError.
4293 *  - Pickling objects that lied about their type by overwriting the
4294 *    __class__ descriptor could lead to infinite recursion at C level
4295 *    and eventual segfault.
4296 *
4297 * Because of backwards compatibility, the two methods still have to
4298 * behave in the same way, even if this is not required by the pickle
4299 * protocol. This common functionality was moved to the _common_reduce
4300 * function.
4301 */
4302static PyObject *
4303_common_reduce(PyObject *self, int proto)
4304{
4305    PyObject *copyreg, *res;
4306
4307    if (proto >= 2)
4308        return reduce_newobj(self);
4309
4310    copyreg = import_copyreg();
4311    if (!copyreg)
4312        return NULL;
4313
4314    res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
4315    Py_DECREF(copyreg);
4316
4317    return res;
4318}
4319
4320static PyObject *
4321object_reduce(PyObject *self, PyObject *args)
4322{
4323    int proto = 0;
4324
4325    if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
4326        return NULL;
4327
4328    return _common_reduce(self, proto);
4329}
4330
4331static PyObject *
4332object_reduce_ex(PyObject *self, PyObject *args)
4333{
4334    static PyObject *objreduce;
4335    PyObject *reduce, *res;
4336    int proto = 0;
4337    _Py_IDENTIFIER(__reduce__);
4338
4339    if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
4340        return NULL;
4341
4342    if (objreduce == NULL) {
4343        objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict,
4344                                      &PyId___reduce__);
4345        if (objreduce == NULL)
4346            return NULL;
4347    }
4348
4349    reduce = _PyObject_GetAttrId(self, &PyId___reduce__);
4350    if (reduce == NULL)
4351        PyErr_Clear();
4352    else {
4353        PyObject *cls, *clsreduce;
4354        int override;
4355
4356        cls = (PyObject *) Py_TYPE(self);
4357        clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__);
4358        if (clsreduce == NULL) {
4359            Py_DECREF(reduce);
4360            return NULL;
4361        }
4362        override = (clsreduce != objreduce);
4363        Py_DECREF(clsreduce);
4364        if (override) {
4365            res = PyObject_CallObject(reduce, NULL);
4366            Py_DECREF(reduce);
4367            return res;
4368        }
4369        else
4370            Py_DECREF(reduce);
4371    }
4372
4373    return _common_reduce(self, proto);
4374}
4375
4376static PyObject *
4377object_subclasshook(PyObject *cls, PyObject *args)
4378{
4379    Py_RETURN_NOTIMPLEMENTED;
4380}
4381
4382PyDoc_STRVAR(object_subclasshook_doc,
4383"Abstract classes can override this to customize issubclass().\n"
4384"\n"
4385"This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4386"It should return True, False or NotImplemented.  If it returns\n"
4387"NotImplemented, the normal algorithm is used.  Otherwise, it\n"
4388"overrides the normal algorithm (and the outcome is cached).\n");
4389
4390static PyObject *
4391object_init_subclass(PyObject *cls, PyObject *arg)
4392{
4393    Py_RETURN_NONE;
4394}
4395
4396PyDoc_STRVAR(object_init_subclass_doc,
4397"This method is called when a class is subclassed.\n"
4398"\n"
4399"The default implementation does nothing. It may be\n"
4400"overridden to extend subclasses.\n");
4401
4402static PyObject *
4403object_format(PyObject *self, PyObject *args)
4404{
4405    PyObject *format_spec;
4406    PyObject *self_as_str = NULL;
4407    PyObject *result = NULL;
4408
4409    if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4410        return NULL;
4411
4412    /* Issue 7994: If we're converting to a string, we
4413       should reject format specifications */
4414    if (PyUnicode_GET_LENGTH(format_spec) > 0) {
4415        PyErr_Format(PyExc_TypeError,
4416                     "unsupported format string passed to %.200s.__format__",
4417                     self->ob_type->tp_name);
4418        return NULL;
4419    }
4420    self_as_str = PyObject_Str(self);
4421    if (self_as_str != NULL) {
4422        result = PyObject_Format(self_as_str, format_spec);
4423        Py_DECREF(self_as_str);
4424    }
4425    return result;
4426}
4427
4428static PyObject *
4429object_sizeof(PyObject *self, PyObject *args)
4430{
4431    Py_ssize_t res, isize;
4432
4433    res = 0;
4434    isize = self->ob_type->tp_itemsize;
4435    if (isize > 0)
4436        res = Py_SIZE(self) * isize;
4437    res += self->ob_type->tp_basicsize;
4438
4439    return PyLong_FromSsize_t(res);
4440}
4441
4442/* __dir__ for generic objects: returns __dict__, __class__,
4443   and recursively up the __class__.__bases__ chain.
4444*/
4445static PyObject *
4446object_dir(PyObject *self, PyObject *args)
4447{
4448    PyObject *result = NULL;
4449    PyObject *dict = NULL;
4450    PyObject *itsclass = NULL;
4451
4452    /* Get __dict__ (which may or may not be a real dict...) */
4453    dict = _PyObject_GetAttrId(self, &PyId___dict__);
4454    if (dict == NULL) {
4455        PyErr_Clear();
4456        dict = PyDict_New();
4457    }
4458    else if (!PyDict_Check(dict)) {
4459        Py_DECREF(dict);
4460        dict = PyDict_New();
4461    }
4462    else {
4463        /* Copy __dict__ to avoid mutating it. */
4464        PyObject *temp = PyDict_Copy(dict);
4465        Py_DECREF(dict);
4466        dict = temp;
4467    }
4468
4469    if (dict == NULL)
4470        goto error;
4471
4472    /* Merge in attrs reachable from its class. */
4473    itsclass = _PyObject_GetAttrId(self, &PyId___class__);
4474    if (itsclass == NULL)
4475        /* XXX(tomer): Perhaps fall back to obj->ob_type if no
4476                       __class__ exists? */
4477        PyErr_Clear();
4478    else if (merge_class_dict(dict, itsclass) != 0)
4479        goto error;
4480
4481    result = PyDict_Keys(dict);
4482    /* fall through */
4483error:
4484    Py_XDECREF(itsclass);
4485    Py_XDECREF(dict);
4486    return result;
4487}
4488
4489static PyMethodDef object_methods[] = {
4490    {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4491     PyDoc_STR("helper for pickle")},
4492    {"__reduce__", object_reduce, METH_VARARGS,
4493     PyDoc_STR("helper for pickle")},
4494    {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4495     object_subclasshook_doc},
4496    {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS,
4497     object_init_subclass_doc},
4498    {"__format__", object_format, METH_VARARGS,
4499     PyDoc_STR("default object formatter")},
4500    {"__sizeof__", object_sizeof, METH_NOARGS,
4501     PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
4502    {"__dir__", object_dir, METH_NOARGS,
4503     PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
4504    {0}
4505};
4506
4507
4508PyTypeObject PyBaseObject_Type = {
4509    PyVarObject_HEAD_INIT(&PyType_Type, 0)
4510    "object",                                   /* tp_name */
4511    sizeof(PyObject),                           /* tp_basicsize */
4512    0,                                          /* tp_itemsize */
4513    object_dealloc,                             /* tp_dealloc */
4514    0,                                          /* tp_print */
4515    0,                                          /* tp_getattr */
4516    0,                                          /* tp_setattr */
4517    0,                                          /* tp_reserved */
4518    object_repr,                                /* tp_repr */
4519    0,                                          /* tp_as_number */
4520    0,                                          /* tp_as_sequence */
4521    0,                                          /* tp_as_mapping */
4522    (hashfunc)_Py_HashPointer,                  /* tp_hash */
4523    0,                                          /* tp_call */
4524    object_str,                                 /* tp_str */
4525    PyObject_GenericGetAttr,                    /* tp_getattro */
4526    PyObject_GenericSetAttr,                    /* tp_setattro */
4527    0,                                          /* tp_as_buffer */
4528    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
4529    PyDoc_STR("object()\n--\n\nThe most base type"),  /* tp_doc */
4530    0,                                          /* tp_traverse */
4531    0,                                          /* tp_clear */
4532    object_richcompare,                         /* tp_richcompare */
4533    0,                                          /* tp_weaklistoffset */
4534    0,                                          /* tp_iter */
4535    0,                                          /* tp_iternext */
4536    object_methods,                             /* tp_methods */
4537    0,                                          /* tp_members */
4538    object_getsets,                             /* tp_getset */
4539    0,                                          /* tp_base */
4540    0,                                          /* tp_dict */
4541    0,                                          /* tp_descr_get */
4542    0,                                          /* tp_descr_set */
4543    0,                                          /* tp_dictoffset */
4544    object_init,                                /* tp_init */
4545    PyType_GenericAlloc,                        /* tp_alloc */
4546    object_new,                                 /* tp_new */
4547    PyObject_Del,                               /* tp_free */
4548};
4549
4550
4551/* Add the methods from tp_methods to the __dict__ in a type object */
4552
4553static int
4554add_methods(PyTypeObject *type, PyMethodDef *meth)
4555{
4556    PyObject *dict = type->tp_dict;
4557
4558    for (; meth->ml_name != NULL; meth++) {
4559        PyObject *descr;
4560        int err;
4561        if (PyDict_GetItemString(dict, meth->ml_name) &&
4562            !(meth->ml_flags & METH_COEXIST))
4563                continue;
4564        if (meth->ml_flags & METH_CLASS) {
4565            if (meth->ml_flags & METH_STATIC) {
4566                PyErr_SetString(PyExc_ValueError,
4567                     "method cannot be both class and static");
4568                return -1;
4569            }
4570            descr = PyDescr_NewClassMethod(type, meth);
4571        }
4572        else if (meth->ml_flags & METH_STATIC) {
4573          PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL);
4574            if (cfunc == NULL)
4575                return -1;
4576            descr = PyStaticMethod_New(cfunc);
4577            Py_DECREF(cfunc);
4578        }
4579        else {
4580            descr = PyDescr_NewMethod(type, meth);
4581        }
4582        if (descr == NULL)
4583            return -1;
4584        err = PyDict_SetItemString(dict, meth->ml_name, descr);
4585        Py_DECREF(descr);
4586        if (err < 0)
4587            return -1;
4588    }
4589    return 0;
4590}
4591
4592static int
4593add_members(PyTypeObject *type, PyMemberDef *memb)
4594{
4595    PyObject *dict = type->tp_dict;
4596
4597    for (; memb->name != NULL; memb++) {
4598        PyObject *descr;
4599        if (PyDict_GetItemString(dict, memb->name))
4600            continue;
4601        descr = PyDescr_NewMember(type, memb);
4602        if (descr == NULL)
4603            return -1;
4604        if (PyDict_SetItemString(dict, memb->name, descr) < 0) {
4605            Py_DECREF(descr);
4606            return -1;
4607        }
4608        Py_DECREF(descr);
4609    }
4610    return 0;
4611}
4612
4613static int
4614add_getset(PyTypeObject *type, PyGetSetDef *gsp)
4615{
4616    PyObject *dict = type->tp_dict;
4617
4618    for (; gsp->name != NULL; gsp++) {
4619        PyObject *descr;
4620        if (PyDict_GetItemString(dict, gsp->name))
4621            continue;
4622        descr = PyDescr_NewGetSet(type, gsp);
4623
4624        if (descr == NULL)
4625            return -1;
4626        if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
4627            Py_DECREF(descr);
4628            return -1;
4629        }
4630        Py_DECREF(descr);
4631    }
4632    return 0;
4633}
4634
4635static void
4636inherit_special(PyTypeObject *type, PyTypeObject *base)
4637{
4638
4639    /* Copying basicsize is connected to the GC flags */
4640    if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4641        (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4642        (!type->tp_traverse && !type->tp_clear)) {
4643        type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4644        if (type->tp_traverse == NULL)
4645            type->tp_traverse = base->tp_traverse;
4646        if (type->tp_clear == NULL)
4647            type->tp_clear = base->tp_clear;
4648    }
4649    {
4650        /* The condition below could use some explanation.
4651           It appears that tp_new is not inherited for static types
4652           whose base class is 'object'; this seems to be a precaution
4653           so that old extension types don't suddenly become
4654           callable (object.__new__ wouldn't insure the invariants
4655           that the extension type's own factory function ensures).
4656           Heap types, of course, are under our control, so they do
4657           inherit tp_new; static extension types that specify some
4658           other built-in type as the default also
4659           inherit object.__new__. */
4660        if (base != &PyBaseObject_Type ||
4661            (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
4662            if (type->tp_new == NULL)
4663                type->tp_new = base->tp_new;
4664        }
4665    }
4666    if (type->tp_basicsize == 0)
4667        type->tp_basicsize = base->tp_basicsize;
4668
4669    /* Copy other non-function slots */
4670
4671#undef COPYVAL
4672#define COPYVAL(SLOT) \
4673    if (type->SLOT == 0) type->SLOT = base->SLOT
4674
4675    COPYVAL(tp_itemsize);
4676    COPYVAL(tp_weaklistoffset);
4677    COPYVAL(tp_dictoffset);
4678
4679    /* Setup fast subclass flags */
4680    if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
4681        type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
4682    else if (PyType_IsSubtype(base, &PyType_Type))
4683        type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
4684    else if (PyType_IsSubtype(base, &PyLong_Type))
4685        type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
4686    else if (PyType_IsSubtype(base, &PyBytes_Type))
4687        type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS;
4688    else if (PyType_IsSubtype(base, &PyUnicode_Type))
4689        type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
4690    else if (PyType_IsSubtype(base, &PyTuple_Type))
4691        type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
4692    else if (PyType_IsSubtype(base, &PyList_Type))
4693        type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
4694    else if (PyType_IsSubtype(base, &PyDict_Type))
4695        type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
4696}
4697
4698static int
4699overrides_hash(PyTypeObject *type)
4700{
4701    PyObject *dict = type->tp_dict;
4702    _Py_IDENTIFIER(__eq__);
4703
4704    assert(dict != NULL);
4705    if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL)
4706        return 1;
4707    if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL)
4708        return 1;
4709    return 0;
4710}
4711
4712static void
4713inherit_slots(PyTypeObject *type, PyTypeObject *base)
4714{
4715    PyTypeObject *basebase;
4716
4717#undef SLOTDEFINED
4718#undef COPYSLOT
4719#undef COPYNUM
4720#undef COPYSEQ
4721#undef COPYMAP
4722#undef COPYBUF
4723
4724#define SLOTDEFINED(SLOT) \
4725    (base->SLOT != 0 && \
4726     (basebase == NULL || base->SLOT != basebase->SLOT))
4727
4728#define COPYSLOT(SLOT) \
4729    if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
4730
4731#define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
4732#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4733#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4734#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
4735#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
4736
4737    /* This won't inherit indirect slots (from tp_as_number etc.)
4738       if type doesn't provide the space. */
4739
4740    if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4741        basebase = base->tp_base;
4742        if (basebase->tp_as_number == NULL)
4743            basebase = NULL;
4744        COPYNUM(nb_add);
4745        COPYNUM(nb_subtract);
4746        COPYNUM(nb_multiply);
4747        COPYNUM(nb_remainder);
4748        COPYNUM(nb_divmod);
4749        COPYNUM(nb_power);
4750        COPYNUM(nb_negative);
4751        COPYNUM(nb_positive);
4752        COPYNUM(nb_absolute);
4753        COPYNUM(nb_bool);
4754        COPYNUM(nb_invert);
4755        COPYNUM(nb_lshift);
4756        COPYNUM(nb_rshift);
4757        COPYNUM(nb_and);
4758        COPYNUM(nb_xor);
4759        COPYNUM(nb_or);
4760        COPYNUM(nb_int);
4761        COPYNUM(nb_float);
4762        COPYNUM(nb_inplace_add);
4763        COPYNUM(nb_inplace_subtract);
4764        COPYNUM(nb_inplace_multiply);
4765        COPYNUM(nb_inplace_remainder);
4766        COPYNUM(nb_inplace_power);
4767        COPYNUM(nb_inplace_lshift);
4768        COPYNUM(nb_inplace_rshift);
4769        COPYNUM(nb_inplace_and);
4770        COPYNUM(nb_inplace_xor);
4771        COPYNUM(nb_inplace_or);
4772        COPYNUM(nb_true_divide);
4773        COPYNUM(nb_floor_divide);
4774        COPYNUM(nb_inplace_true_divide);
4775        COPYNUM(nb_inplace_floor_divide);
4776        COPYNUM(nb_index);
4777        COPYNUM(nb_matrix_multiply);
4778        COPYNUM(nb_inplace_matrix_multiply);
4779    }
4780
4781    if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
4782        basebase = base->tp_base;
4783        if (basebase->tp_as_async == NULL)
4784            basebase = NULL;
4785        COPYASYNC(am_await);
4786        COPYASYNC(am_aiter);
4787        COPYASYNC(am_anext);
4788    }
4789
4790    if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4791        basebase = base->tp_base;
4792        if (basebase->tp_as_sequence == NULL)
4793            basebase = NULL;
4794        COPYSEQ(sq_length);
4795        COPYSEQ(sq_concat);
4796        COPYSEQ(sq_repeat);
4797        COPYSEQ(sq_item);
4798        COPYSEQ(sq_ass_item);
4799        COPYSEQ(sq_contains);
4800        COPYSEQ(sq_inplace_concat);
4801        COPYSEQ(sq_inplace_repeat);
4802    }
4803
4804    if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
4805        basebase = base->tp_base;
4806        if (basebase->tp_as_mapping == NULL)
4807            basebase = NULL;
4808        COPYMAP(mp_length);
4809        COPYMAP(mp_subscript);
4810        COPYMAP(mp_ass_subscript);
4811    }
4812
4813    if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
4814        basebase = base->tp_base;
4815        if (basebase->tp_as_buffer == NULL)
4816            basebase = NULL;
4817        COPYBUF(bf_getbuffer);
4818        COPYBUF(bf_releasebuffer);
4819    }
4820
4821    basebase = base->tp_base;
4822
4823    COPYSLOT(tp_dealloc);
4824    if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
4825        type->tp_getattr = base->tp_getattr;
4826        type->tp_getattro = base->tp_getattro;
4827    }
4828    if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
4829        type->tp_setattr = base->tp_setattr;
4830        type->tp_setattro = base->tp_setattro;
4831    }
4832    /* tp_reserved is ignored */
4833    COPYSLOT(tp_repr);
4834    /* tp_hash see tp_richcompare */
4835    COPYSLOT(tp_call);
4836    COPYSLOT(tp_str);
4837    {
4838        /* Copy comparison-related slots only when
4839           not overriding them anywhere */
4840        if (type->tp_richcompare == NULL &&
4841            type->tp_hash == NULL &&
4842            !overrides_hash(type))
4843        {
4844            type->tp_richcompare = base->tp_richcompare;
4845            type->tp_hash = base->tp_hash;
4846        }
4847    }
4848    {
4849        COPYSLOT(tp_iter);
4850        COPYSLOT(tp_iternext);
4851    }
4852    {
4853        COPYSLOT(tp_descr_get);
4854        COPYSLOT(tp_descr_set);
4855        COPYSLOT(tp_dictoffset);
4856        COPYSLOT(tp_init);
4857        COPYSLOT(tp_alloc);
4858        COPYSLOT(tp_is_gc);
4859        if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) &&
4860            (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) {
4861            COPYSLOT(tp_finalize);
4862        }
4863        if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
4864            (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
4865            /* They agree about gc. */
4866            COPYSLOT(tp_free);
4867        }
4868        else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
4869                 type->tp_free == NULL &&
4870                 base->tp_free == PyObject_Free) {
4871            /* A bit of magic to plug in the correct default
4872             * tp_free function when a derived class adds gc,
4873             * didn't define tp_free, and the base uses the
4874             * default non-gc tp_free.
4875             */
4876            type->tp_free = PyObject_GC_Del;
4877        }
4878        /* else they didn't agree about gc, and there isn't something
4879         * obvious to be done -- the type is on its own.
4880         */
4881    }
4882}
4883
4884static int add_operators(PyTypeObject *);
4885
4886int
4887PyType_Ready(PyTypeObject *type)
4888{
4889    PyObject *dict, *bases;
4890    PyTypeObject *base;
4891    Py_ssize_t i, n;
4892
4893    if (type->tp_flags & Py_TPFLAGS_READY) {
4894        assert(type->tp_dict != NULL);
4895        return 0;
4896    }
4897    assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
4898
4899    type->tp_flags |= Py_TPFLAGS_READYING;
4900
4901#ifdef Py_TRACE_REFS
4902    /* PyType_Ready is the closest thing we have to a choke point
4903     * for type objects, so is the best place I can think of to try
4904     * to get type objects into the doubly-linked list of all objects.
4905     * Still, not all type objects go thru PyType_Ready.
4906     */
4907    _Py_AddToAllObjects((PyObject *)type, 0);
4908#endif
4909
4910    if (type->tp_name == NULL) {
4911        PyErr_Format(PyExc_SystemError,
4912                     "Type does not define the tp_name field.");
4913        goto error;
4914    }
4915
4916    /* Initialize tp_base (defaults to BaseObject unless that's us) */
4917    base = type->tp_base;
4918    if (base == NULL && type != &PyBaseObject_Type) {
4919        base = type->tp_base = &PyBaseObject_Type;
4920        Py_INCREF(base);
4921    }
4922
4923    /* Now the only way base can still be NULL is if type is
4924     * &PyBaseObject_Type.
4925     */
4926
4927    /* Initialize the base class */
4928    if (base != NULL && base->tp_dict == NULL) {
4929        if (PyType_Ready(base) < 0)
4930            goto error;
4931    }
4932
4933    /* Initialize ob_type if NULL.      This means extensions that want to be
4934       compilable separately on Windows can call PyType_Ready() instead of
4935       initializing the ob_type field of their type objects. */
4936    /* The test for base != NULL is really unnecessary, since base is only
4937       NULL when type is &PyBaseObject_Type, and we know its ob_type is
4938       not NULL (it's initialized to &PyType_Type).      But coverity doesn't
4939       know that. */
4940    if (Py_TYPE(type) == NULL && base != NULL)
4941        Py_TYPE(type) = Py_TYPE(base);
4942
4943    /* Initialize tp_bases */
4944    bases = type->tp_bases;
4945    if (bases == NULL) {
4946        if (base == NULL)
4947            bases = PyTuple_New(0);
4948        else
4949            bases = PyTuple_Pack(1, base);
4950        if (bases == NULL)
4951            goto error;
4952        type->tp_bases = bases;
4953    }
4954
4955    /* Initialize tp_dict */
4956    dict = type->tp_dict;
4957    if (dict == NULL) {
4958        dict = PyDict_New();
4959        if (dict == NULL)
4960            goto error;
4961        type->tp_dict = dict;
4962    }
4963
4964    /* Add type-specific descriptors to tp_dict */
4965    if (add_operators(type) < 0)
4966        goto error;
4967    if (type->tp_methods != NULL) {
4968        if (add_methods(type, type->tp_methods) < 0)
4969            goto error;
4970    }
4971    if (type->tp_members != NULL) {
4972        if (add_members(type, type->tp_members) < 0)
4973            goto error;
4974    }
4975    if (type->tp_getset != NULL) {
4976        if (add_getset(type, type->tp_getset) < 0)
4977            goto error;
4978    }
4979
4980    /* Calculate method resolution order */
4981    if (mro_internal(type, NULL) < 0)
4982        goto error;
4983
4984    /* Inherit special flags from dominant base */
4985    if (type->tp_base != NULL)
4986        inherit_special(type, type->tp_base);
4987
4988    /* Initialize tp_dict properly */
4989    bases = type->tp_mro;
4990    assert(bases != NULL);
4991    assert(PyTuple_Check(bases));
4992    n = PyTuple_GET_SIZE(bases);
4993    for (i = 1; i < n; i++) {
4994        PyObject *b = PyTuple_GET_ITEM(bases, i);
4995        if (PyType_Check(b))
4996            inherit_slots(type, (PyTypeObject *)b);
4997    }
4998
4999    /* All bases of statically allocated type should be statically allocated */
5000    if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
5001        for (i = 0; i < n; i++) {
5002            PyObject *b = PyTuple_GET_ITEM(bases, i);
5003            if (PyType_Check(b) &&
5004                (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
5005                PyErr_Format(PyExc_TypeError,
5006                             "type '%.100s' is not dynamically allocated but "
5007                             "its base type '%.100s' is dynamically allocated",
5008                             type->tp_name, ((PyTypeObject *)b)->tp_name);
5009                goto error;
5010            }
5011        }
5012
5013    /* Sanity check for tp_free. */
5014    if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
5015        (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
5016        /* This base class needs to call tp_free, but doesn't have
5017         * one, or its tp_free is for non-gc'ed objects.
5018         */
5019        PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
5020                     "gc and is a base type but has inappropriate "
5021                     "tp_free slot",
5022                     type->tp_name);
5023        goto error;
5024    }
5025
5026    /* if the type dictionary doesn't contain a __doc__, set it from
5027       the tp_doc slot.
5028     */
5029    if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) {
5030        if (type->tp_doc != NULL) {
5031            const char *old_doc = _PyType_DocWithoutSignature(type->tp_name,
5032                type->tp_doc);
5033            PyObject *doc = PyUnicode_FromString(old_doc);
5034            if (doc == NULL)
5035                goto error;
5036            if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) {
5037                Py_DECREF(doc);
5038                goto error;
5039            }
5040            Py_DECREF(doc);
5041        } else {
5042            if (_PyDict_SetItemId(type->tp_dict,
5043                                  &PyId___doc__, Py_None) < 0)
5044                goto error;
5045        }
5046    }
5047
5048    /* Hack for tp_hash and __hash__.
5049       If after all that, tp_hash is still NULL, and __hash__ is not in
5050       tp_dict, set tp_hash to PyObject_HashNotImplemented and
5051       tp_dict['__hash__'] equal to None.
5052       This signals that __hash__ is not inherited.
5053     */
5054    if (type->tp_hash == NULL) {
5055        if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
5056            if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
5057                goto error;
5058            type->tp_hash = PyObject_HashNotImplemented;
5059        }
5060    }
5061
5062    /* Some more special stuff */
5063    base = type->tp_base;
5064    if (base != NULL) {
5065        if (type->tp_as_async == NULL)
5066            type->tp_as_async = base->tp_as_async;
5067        if (type->tp_as_number == NULL)
5068            type->tp_as_number = base->tp_as_number;
5069        if (type->tp_as_sequence == NULL)
5070            type->tp_as_sequence = base->tp_as_sequence;
5071        if (type->tp_as_mapping == NULL)
5072            type->tp_as_mapping = base->tp_as_mapping;
5073        if (type->tp_as_buffer == NULL)
5074            type->tp_as_buffer = base->tp_as_buffer;
5075    }
5076
5077    /* Link into each base class's list of subclasses */
5078    bases = type->tp_bases;
5079    n = PyTuple_GET_SIZE(bases);
5080    for (i = 0; i < n; i++) {
5081        PyObject *b = PyTuple_GET_ITEM(bases, i);
5082        if (PyType_Check(b) &&
5083            add_subclass((PyTypeObject *)b, type) < 0)
5084            goto error;
5085    }
5086
5087    /* All done -- set the ready flag */
5088    assert(type->tp_dict != NULL);
5089    type->tp_flags =
5090        (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
5091    return 0;
5092
5093  error:
5094    type->tp_flags &= ~Py_TPFLAGS_READYING;
5095    return -1;
5096}
5097
5098static int
5099add_subclass(PyTypeObject *base, PyTypeObject *type)
5100{
5101    int result = -1;
5102    PyObject *dict, *key, *newobj;
5103
5104    dict = base->tp_subclasses;
5105    if (dict == NULL) {
5106        base->tp_subclasses = dict = PyDict_New();
5107        if (dict == NULL)
5108            return -1;
5109    }
5110    assert(PyDict_CheckExact(dict));
5111    key = PyLong_FromVoidPtr((void *) type);
5112    if (key == NULL)
5113        return -1;
5114    newobj = PyWeakref_NewRef((PyObject *)type, NULL);
5115    if (newobj != NULL) {
5116        result = PyDict_SetItem(dict, key, newobj);
5117        Py_DECREF(newobj);
5118    }
5119    Py_DECREF(key);
5120    return result;
5121}
5122
5123static int
5124add_all_subclasses(PyTypeObject *type, PyObject *bases)
5125{
5126    int res = 0;
5127
5128    if (bases) {
5129        Py_ssize_t i;
5130        for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5131            PyObject *base = PyTuple_GET_ITEM(bases, i);
5132            if (PyType_Check(base) &&
5133                add_subclass((PyTypeObject*)base, type) < 0)
5134                res = -1;
5135        }
5136    }
5137
5138    return res;
5139}
5140
5141static void
5142remove_subclass(PyTypeObject *base, PyTypeObject *type)
5143{
5144    PyObject *dict, *key;
5145
5146    dict = base->tp_subclasses;
5147    if (dict == NULL) {
5148        return;
5149    }
5150    assert(PyDict_CheckExact(dict));
5151    key = PyLong_FromVoidPtr((void *) type);
5152    if (key == NULL || PyDict_DelItem(dict, key)) {
5153        /* This can happen if the type initialization errored out before
5154           the base subclasses were updated (e.g. a non-str __qualname__
5155           was passed in the type dict). */
5156        PyErr_Clear();
5157    }
5158    Py_XDECREF(key);
5159}
5160
5161static void
5162remove_all_subclasses(PyTypeObject *type, PyObject *bases)
5163{
5164    if (bases) {
5165        Py_ssize_t i;
5166        for (i = 0; i < PyTuple_GET_SIZE(bases); i++) {
5167            PyObject *base = PyTuple_GET_ITEM(bases, i);
5168            if (PyType_Check(base))
5169                remove_subclass((PyTypeObject*) base, type);
5170        }
5171    }
5172}
5173
5174static int
5175check_num_args(PyObject *ob, int n)
5176{
5177    if (!PyTuple_CheckExact(ob)) {
5178        PyErr_SetString(PyExc_SystemError,
5179            "PyArg_UnpackTuple() argument list is not a tuple");
5180        return 0;
5181    }
5182    if (n == PyTuple_GET_SIZE(ob))
5183        return 1;
5184    PyErr_Format(
5185        PyExc_TypeError,
5186        "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
5187    return 0;
5188}
5189
5190/* Generic wrappers for overloadable 'operators' such as __getitem__ */
5191
5192/* There's a wrapper *function* for each distinct function typedef used
5193   for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
5194   wrapper *table* for each distinct operation (e.g. __len__, __add__).
5195   Most tables have only one entry; the tables for binary operators have two
5196   entries, one regular and one with reversed arguments. */
5197
5198static PyObject *
5199wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
5200{
5201    lenfunc func = (lenfunc)wrapped;
5202    Py_ssize_t res;
5203
5204    if (!check_num_args(args, 0))
5205        return NULL;
5206    res = (*func)(self);
5207    if (res == -1 && PyErr_Occurred())
5208        return NULL;
5209    return PyLong_FromLong((long)res);
5210}
5211
5212static PyObject *
5213wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
5214{
5215    inquiry func = (inquiry)wrapped;
5216    int res;
5217
5218    if (!check_num_args(args, 0))
5219        return NULL;
5220    res = (*func)(self);
5221    if (res == -1 && PyErr_Occurred())
5222        return NULL;
5223    return PyBool_FromLong((long)res);
5224}
5225
5226static PyObject *
5227wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
5228{
5229    binaryfunc func = (binaryfunc)wrapped;
5230    PyObject *other;
5231
5232    if (!check_num_args(args, 1))
5233        return NULL;
5234    other = PyTuple_GET_ITEM(args, 0);
5235    return (*func)(self, other);
5236}
5237
5238static PyObject *
5239wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
5240{
5241    binaryfunc func = (binaryfunc)wrapped;
5242    PyObject *other;
5243
5244    if (!check_num_args(args, 1))
5245        return NULL;
5246    other = PyTuple_GET_ITEM(args, 0);
5247    return (*func)(self, other);
5248}
5249
5250static PyObject *
5251wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5252{
5253    binaryfunc func = (binaryfunc)wrapped;
5254    PyObject *other;
5255
5256    if (!check_num_args(args, 1))
5257        return NULL;
5258    other = PyTuple_GET_ITEM(args, 0);
5259    return (*func)(other, self);
5260}
5261
5262static PyObject *
5263wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
5264{
5265    ternaryfunc func = (ternaryfunc)wrapped;
5266    PyObject *other;
5267    PyObject *third = Py_None;
5268
5269    /* Note: This wrapper only works for __pow__() */
5270
5271    if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5272        return NULL;
5273    return (*func)(self, other, third);
5274}
5275
5276static PyObject *
5277wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
5278{
5279    ternaryfunc func = (ternaryfunc)wrapped;
5280    PyObject *other;
5281    PyObject *third = Py_None;
5282
5283    /* Note: This wrapper only works for __pow__() */
5284
5285    if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
5286        return NULL;
5287    return (*func)(other, self, third);
5288}
5289
5290static PyObject *
5291wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
5292{
5293    unaryfunc func = (unaryfunc)wrapped;
5294
5295    if (!check_num_args(args, 0))
5296        return NULL;
5297    return (*func)(self);
5298}
5299
5300static PyObject *
5301wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
5302{
5303    ssizeargfunc func = (ssizeargfunc)wrapped;
5304    PyObject* o;
5305    Py_ssize_t i;
5306
5307    if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
5308        return NULL;
5309    i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
5310    if (i == -1 && PyErr_Occurred())
5311        return NULL;
5312    return (*func)(self, i);
5313}
5314
5315static Py_ssize_t
5316getindex(PyObject *self, PyObject *arg)
5317{
5318    Py_ssize_t i;
5319
5320    i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
5321    if (i == -1 && PyErr_Occurred())
5322        return -1;
5323    if (i < 0) {
5324        PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
5325        if (sq && sq->sq_length) {
5326            Py_ssize_t n = (*sq->sq_length)(self);
5327            if (n < 0)
5328                return -1;
5329            i += n;
5330        }
5331    }
5332    return i;
5333}
5334
5335static PyObject *
5336wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
5337{
5338    ssizeargfunc func = (ssizeargfunc)wrapped;
5339    PyObject *arg;
5340    Py_ssize_t i;
5341
5342    if (PyTuple_GET_SIZE(args) == 1) {
5343        arg = PyTuple_GET_ITEM(args, 0);
5344        i = getindex(self, arg);
5345        if (i == -1 && PyErr_Occurred())
5346            return NULL;
5347        return (*func)(self, i);
5348    }
5349    check_num_args(args, 1);
5350    assert(PyErr_Occurred());
5351    return NULL;
5352}
5353
5354static PyObject *
5355wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
5356{
5357    ssizeobjargproc func = (ssizeobjargproc)wrapped;
5358    Py_ssize_t i;
5359    int res;
5360    PyObject *arg, *value;
5361
5362    if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
5363        return NULL;
5364    i = getindex(self, arg);
5365    if (i == -1 && PyErr_Occurred())
5366        return NULL;
5367    res = (*func)(self, i, value);
5368    if (res == -1 && PyErr_Occurred())
5369        return NULL;
5370    Py_INCREF(Py_None);
5371    return Py_None;
5372}
5373
5374static PyObject *
5375wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
5376{
5377    ssizeobjargproc func = (ssizeobjargproc)wrapped;
5378    Py_ssize_t i;
5379    int res;
5380    PyObject *arg;
5381
5382    if (!check_num_args(args, 1))
5383        return NULL;
5384    arg = PyTuple_GET_ITEM(args, 0);
5385    i = getindex(self, arg);
5386    if (i == -1 && PyErr_Occurred())
5387        return NULL;
5388    res = (*func)(self, i, NULL);
5389    if (res == -1 && PyErr_Occurred())
5390        return NULL;
5391    Py_INCREF(Py_None);
5392    return Py_None;
5393}
5394
5395/* XXX objobjproc is a misnomer; should be objargpred */
5396static PyObject *
5397wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
5398{
5399    objobjproc func = (objobjproc)wrapped;
5400    int res;
5401    PyObject *value;
5402
5403    if (!check_num_args(args, 1))
5404        return NULL;
5405    value = PyTuple_GET_ITEM(args, 0);
5406    res = (*func)(self, value);
5407    if (res == -1 && PyErr_Occurred())
5408        return NULL;
5409    else
5410        return PyBool_FromLong(res);
5411}
5412
5413static PyObject *
5414wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
5415{
5416    objobjargproc func = (objobjargproc)wrapped;
5417    int res;
5418    PyObject *key, *value;
5419
5420    if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
5421        return NULL;
5422    res = (*func)(self, key, value);
5423    if (res == -1 && PyErr_Occurred())
5424        return NULL;
5425    Py_INCREF(Py_None);
5426    return Py_None;
5427}
5428
5429static PyObject *
5430wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
5431{
5432    objobjargproc func = (objobjargproc)wrapped;
5433    int res;
5434    PyObject *key;
5435
5436    if (!check_num_args(args, 1))
5437        return NULL;
5438    key = PyTuple_GET_ITEM(args, 0);
5439    res = (*func)(self, key, NULL);
5440    if (res == -1 && PyErr_Occurred())
5441        return NULL;
5442    Py_INCREF(Py_None);
5443    return Py_None;
5444}
5445
5446/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
5447   This is called the Carlo Verre hack after its discoverer. */
5448static int
5449hackcheck(PyObject *self, setattrofunc func, const char *what)
5450{
5451    PyTypeObject *type = Py_TYPE(self);
5452    while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5453        type = type->tp_base;
5454    /* If type is NULL now, this is a really weird type.
5455       In the spirit of backwards compatibility (?), just shut up. */
5456    if (type && type->tp_setattro != func) {
5457        PyErr_Format(PyExc_TypeError,
5458                     "can't apply this %s to %s object",
5459                     what,
5460                     type->tp_name);
5461        return 0;
5462    }
5463    return 1;
5464}
5465
5466static PyObject *
5467wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
5468{
5469    setattrofunc func = (setattrofunc)wrapped;
5470    int res;
5471    PyObject *name, *value;
5472
5473    if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
5474        return NULL;
5475    if (!hackcheck(self, func, "__setattr__"))
5476        return NULL;
5477    res = (*func)(self, name, value);
5478    if (res < 0)
5479        return NULL;
5480    Py_INCREF(Py_None);
5481    return Py_None;
5482}
5483
5484static PyObject *
5485wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
5486{
5487    setattrofunc func = (setattrofunc)wrapped;
5488    int res;
5489    PyObject *name;
5490
5491    if (!check_num_args(args, 1))
5492        return NULL;
5493    name = PyTuple_GET_ITEM(args, 0);
5494    if (!hackcheck(self, func, "__delattr__"))
5495        return NULL;
5496    res = (*func)(self, name, NULL);
5497    if (res < 0)
5498        return NULL;
5499    Py_INCREF(Py_None);
5500    return Py_None;
5501}
5502
5503static PyObject *
5504wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
5505{
5506    hashfunc func = (hashfunc)wrapped;
5507    Py_hash_t res;
5508
5509    if (!check_num_args(args, 0))
5510        return NULL;
5511    res = (*func)(self);
5512    if (res == -1 && PyErr_Occurred())
5513        return NULL;
5514    return PyLong_FromSsize_t(res);
5515}
5516
5517static PyObject *
5518wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
5519{
5520    ternaryfunc func = (ternaryfunc)wrapped;
5521
5522    return (*func)(self, args, kwds);
5523}
5524
5525static PyObject *
5526wrap_del(PyObject *self, PyObject *args, void *wrapped)
5527{
5528    destructor func = (destructor)wrapped;
5529
5530    if (!check_num_args(args, 0))
5531        return NULL;
5532
5533    (*func)(self);
5534    Py_RETURN_NONE;
5535}
5536
5537static PyObject *
5538wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
5539{
5540    richcmpfunc func = (richcmpfunc)wrapped;
5541    PyObject *other;
5542
5543    if (!check_num_args(args, 1))
5544        return NULL;
5545    other = PyTuple_GET_ITEM(args, 0);
5546    return (*func)(self, other, op);
5547}
5548
5549#undef RICHCMP_WRAPPER
5550#define RICHCMP_WRAPPER(NAME, OP) \
5551static PyObject * \
5552richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
5553{ \
5554    return wrap_richcmpfunc(self, args, wrapped, OP); \
5555}
5556
5557RICHCMP_WRAPPER(lt, Py_LT)
5558RICHCMP_WRAPPER(le, Py_LE)
5559RICHCMP_WRAPPER(eq, Py_EQ)
5560RICHCMP_WRAPPER(ne, Py_NE)
5561RICHCMP_WRAPPER(gt, Py_GT)
5562RICHCMP_WRAPPER(ge, Py_GE)
5563
5564static PyObject *
5565wrap_next(PyObject *self, PyObject *args, void *wrapped)
5566{
5567    unaryfunc func = (unaryfunc)wrapped;
5568    PyObject *res;
5569
5570    if (!check_num_args(args, 0))
5571        return NULL;
5572    res = (*func)(self);
5573    if (res == NULL && !PyErr_Occurred())
5574        PyErr_SetNone(PyExc_StopIteration);
5575    return res;
5576}
5577
5578static PyObject *
5579wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
5580{
5581    descrgetfunc func = (descrgetfunc)wrapped;
5582    PyObject *obj;
5583    PyObject *type = NULL;
5584
5585    if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
5586        return NULL;
5587    if (obj == Py_None)
5588        obj = NULL;
5589    if (type == Py_None)
5590        type = NULL;
5591    if (type == NULL &&obj == NULL) {
5592        PyErr_SetString(PyExc_TypeError,
5593                        "__get__(None, None) is invalid");
5594        return NULL;
5595    }
5596    return (*func)(self, obj, type);
5597}
5598
5599static PyObject *
5600wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
5601{
5602    descrsetfunc func = (descrsetfunc)wrapped;
5603    PyObject *obj, *value;
5604    int ret;
5605
5606    if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
5607        return NULL;
5608    ret = (*func)(self, obj, value);
5609    if (ret < 0)
5610        return NULL;
5611    Py_INCREF(Py_None);
5612    return Py_None;
5613}
5614
5615static PyObject *
5616wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
5617{
5618    descrsetfunc func = (descrsetfunc)wrapped;
5619    PyObject *obj;
5620    int ret;
5621
5622    if (!check_num_args(args, 1))
5623        return NULL;
5624    obj = PyTuple_GET_ITEM(args, 0);
5625    ret = (*func)(self, obj, NULL);
5626    if (ret < 0)
5627        return NULL;
5628    Py_INCREF(Py_None);
5629    return Py_None;
5630}
5631
5632static PyObject *
5633wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
5634{
5635    initproc func = (initproc)wrapped;
5636
5637    if (func(self, args, kwds) < 0)
5638        return NULL;
5639    Py_INCREF(Py_None);
5640    return Py_None;
5641}
5642
5643static PyObject *
5644tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
5645{
5646    PyTypeObject *type, *subtype, *staticbase;
5647    PyObject *arg0, *res;
5648
5649    if (self == NULL || !PyType_Check(self))
5650        Py_FatalError("__new__() called with non-type 'self'");
5651    type = (PyTypeObject *)self;
5652    if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
5653        PyErr_Format(PyExc_TypeError,
5654                     "%s.__new__(): not enough arguments",
5655                     type->tp_name);
5656        return NULL;
5657    }
5658    arg0 = PyTuple_GET_ITEM(args, 0);
5659    if (!PyType_Check(arg0)) {
5660        PyErr_Format(PyExc_TypeError,
5661                     "%s.__new__(X): X is not a type object (%s)",
5662                     type->tp_name,
5663                     Py_TYPE(arg0)->tp_name);
5664        return NULL;
5665    }
5666    subtype = (PyTypeObject *)arg0;
5667    if (!PyType_IsSubtype(subtype, type)) {
5668        PyErr_Format(PyExc_TypeError,
5669                     "%s.__new__(%s): %s is not a subtype of %s",
5670                     type->tp_name,
5671                     subtype->tp_name,
5672                     subtype->tp_name,
5673                     type->tp_name);
5674        return NULL;
5675    }
5676
5677    /* Check that the use doesn't do something silly and unsafe like
5678       object.__new__(dict).  To do this, we check that the
5679       most derived base that's not a heap type is this type. */
5680    staticbase = subtype;
5681    while (staticbase && (staticbase->tp_new == slot_tp_new))
5682        staticbase = staticbase->tp_base;
5683    /* If staticbase is NULL now, it is a really weird type.
5684       In the spirit of backwards compatibility (?), just shut up. */
5685    if (staticbase && staticbase->tp_new != type->tp_new) {
5686        PyErr_Format(PyExc_TypeError,
5687                     "%s.__new__(%s) is not safe, use %s.__new__()",
5688                     type->tp_name,
5689                     subtype->tp_name,
5690                     staticbase->tp_name);
5691        return NULL;
5692    }
5693
5694    args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
5695    if (args == NULL)
5696        return NULL;
5697    res = type->tp_new(subtype, args, kwds);
5698    Py_DECREF(args);
5699    return res;
5700}
5701
5702static struct PyMethodDef tp_new_methoddef[] = {
5703    {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
5704     PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
5705               "Create and return a new object.  "
5706               "See help(type) for accurate signature.")},
5707    {0}
5708};
5709
5710static int
5711add_tp_new_wrapper(PyTypeObject *type)
5712{
5713    PyObject *func;
5714
5715    if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL)
5716        return 0;
5717    func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL);
5718    if (func == NULL)
5719        return -1;
5720    if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) {
5721        Py_DECREF(func);
5722        return -1;
5723    }
5724    Py_DECREF(func);
5725    return 0;
5726}
5727
5728/* Slot wrappers that call the corresponding __foo__ slot.  See comments
5729   below at override_slots() for more explanation. */
5730
5731#define SLOT0(FUNCNAME, OPSTR) \
5732static PyObject * \
5733FUNCNAME(PyObject *self) \
5734{ \
5735    _Py_static_string(id, OPSTR); \
5736    return call_method(self, &id, NULL); \
5737}
5738
5739#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
5740static PyObject * \
5741FUNCNAME(PyObject *self, ARG1TYPE arg1) \
5742{ \
5743    _Py_static_string(id, OPSTR); \
5744    return call_method(self, &id, "(" ARGCODES ")", arg1); \
5745}
5746
5747/* Boolean helper for SLOT1BINFULL().
5748   right.__class__ is a nontrivial subclass of left.__class__. */
5749static int
5750method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name)
5751{
5752    PyObject *a, *b;
5753    int ok;
5754
5755    b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name);
5756    if (b == NULL) {
5757        PyErr_Clear();
5758        /* If right doesn't have it, it's not overloaded */
5759        return 0;
5760    }
5761
5762    a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name);
5763    if (a == NULL) {
5764        PyErr_Clear();
5765        Py_DECREF(b);
5766        /* If right has it but left doesn't, it's overloaded */
5767        return 1;
5768    }
5769
5770    ok = PyObject_RichCompareBool(a, b, Py_NE);
5771    Py_DECREF(a);
5772    Py_DECREF(b);
5773    if (ok < 0) {
5774        PyErr_Clear();
5775        return 0;
5776    }
5777
5778    return ok;
5779}
5780
5781
5782#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
5783static PyObject * \
5784FUNCNAME(PyObject *self, PyObject *other) \
5785{ \
5786    _Py_static_string(op_id, OPSTR); \
5787    _Py_static_string(rop_id, ROPSTR); \
5788    int do_other = Py_TYPE(self) != Py_TYPE(other) && \
5789        Py_TYPE(other)->tp_as_number != NULL && \
5790        Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
5791    if (Py_TYPE(self)->tp_as_number != NULL && \
5792        Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
5793        PyObject *r; \
5794        if (do_other && \
5795            PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
5796            method_is_overloaded(self, other, &rop_id)) { \
5797            r = call_maybe(other, &rop_id, "(O)", self); \
5798            if (r != Py_NotImplemented) \
5799                return r; \
5800            Py_DECREF(r); \
5801            do_other = 0; \
5802        } \
5803        r = call_maybe(self, &op_id, "(O)", other); \
5804        if (r != Py_NotImplemented || \
5805            Py_TYPE(other) == Py_TYPE(self)) \
5806            return r; \
5807        Py_DECREF(r); \
5808    } \
5809    if (do_other) { \
5810        return call_maybe(other, &rop_id, "(O)", self); \
5811    } \
5812    Py_RETURN_NOTIMPLEMENTED; \
5813}
5814
5815#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
5816    SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
5817
5818#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
5819static PyObject * \
5820FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5821{ \
5822    _Py_static_string(id, #OPSTR); \
5823    return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
5824}
5825
5826static Py_ssize_t
5827slot_sq_length(PyObject *self)
5828{
5829    PyObject *res = call_method(self, &PyId___len__, NULL);
5830    Py_ssize_t len;
5831
5832    if (res == NULL)
5833        return -1;
5834    len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5835    Py_DECREF(res);
5836    if (len < 0) {
5837        if (!PyErr_Occurred())
5838            PyErr_SetString(PyExc_ValueError,
5839                            "__len__() should return >= 0");
5840        return -1;
5841    }
5842    return len;
5843}
5844
5845/* Super-optimized version of slot_sq_item.
5846   Other slots could do the same... */
5847static PyObject *
5848slot_sq_item(PyObject *self, Py_ssize_t i)
5849{
5850    PyObject *func, *ival = NULL, *retval = NULL;
5851    descrgetfunc f;
5852
5853    func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
5854    if (func == NULL) {
5855        PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
5856        PyErr_SetObject(PyExc_AttributeError, getitem_str);
5857        return NULL;
5858    }
5859
5860    f = Py_TYPE(func)->tp_descr_get;
5861    if (f == NULL) {
5862        Py_INCREF(func);
5863    }
5864    else {
5865        func = f(func, self, (PyObject *)(Py_TYPE(self)));
5866        if (func == NULL) {
5867            return NULL;
5868        }
5869    }
5870
5871    ival = PyLong_FromSsize_t(i);
5872    if (ival == NULL) {
5873        goto error;
5874    }
5875
5876    retval = _PyObject_CallArg1(func, ival);
5877    Py_DECREF(func);
5878    Py_DECREF(ival);
5879    return retval;
5880
5881error:
5882    Py_DECREF(func);
5883    return NULL;
5884}
5885
5886static int
5887slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
5888{
5889    PyObject *res;
5890
5891    if (value == NULL)
5892        res = call_method(self, &PyId___delitem__, "(n)", index);
5893    else
5894        res = call_method(self, &PyId___setitem__, "(nO)", index, value);
5895    if (res == NULL)
5896        return -1;
5897    Py_DECREF(res);
5898    return 0;
5899}
5900
5901static int
5902slot_sq_contains(PyObject *self, PyObject *value)
5903{
5904    PyObject *func, *res;
5905    int result = -1;
5906    _Py_IDENTIFIER(__contains__);
5907
5908    func = lookup_maybe(self, &PyId___contains__);
5909    if (func == Py_None) {
5910        Py_DECREF(func);
5911        PyErr_Format(PyExc_TypeError,
5912                     "'%.200s' object is not a container",
5913                     Py_TYPE(self)->tp_name);
5914        return -1;
5915    }
5916    if (func != NULL) {
5917        res = _PyObject_CallArg1(func, value);
5918        Py_DECREF(func);
5919        if (res != NULL) {
5920            result = PyObject_IsTrue(res);
5921            Py_DECREF(res);
5922        }
5923    }
5924    else if (! PyErr_Occurred()) {
5925        /* Possible results: -1 and 1 */
5926        result = (int)_PySequence_IterSearch(self, value,
5927                                         PY_ITERSEARCH_CONTAINS);
5928    }
5929    return result;
5930}
5931
5932#define slot_mp_length slot_sq_length
5933
5934SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
5935
5936static int
5937slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
5938{
5939    PyObject *res;
5940
5941    if (value == NULL)
5942        res = call_method(self, &PyId___delitem__, "(O)", key);
5943    else
5944        res = call_method(self, &PyId___setitem__, "(OO)", key, value);
5945
5946    if (res == NULL)
5947        return -1;
5948    Py_DECREF(res);
5949    return 0;
5950}
5951
5952SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
5953SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
5954SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
5955SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__")
5956SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
5957SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
5958
5959static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
5960
5961SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
5962             nb_power, "__pow__", "__rpow__")
5963
5964static PyObject *
5965slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
5966{
5967    _Py_IDENTIFIER(__pow__);
5968
5969    if (modulus == Py_None)
5970        return slot_nb_power_binary(self, other);
5971    /* Three-arg power doesn't use __rpow__.  But ternary_op
5972       can call this when the second argument's type uses
5973       slot_nb_power, so check before calling self.__pow__. */
5974    if (Py_TYPE(self)->tp_as_number != NULL &&
5975        Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
5976        return call_method(self, &PyId___pow__, "(OO)", other, modulus);
5977    }
5978    Py_RETURN_NOTIMPLEMENTED;
5979}
5980
5981SLOT0(slot_nb_negative, "__neg__")
5982SLOT0(slot_nb_positive, "__pos__")
5983SLOT0(slot_nb_absolute, "__abs__")
5984
5985static int
5986slot_nb_bool(PyObject *self)
5987{
5988    PyObject *func, *value;
5989    int result;
5990    int using_len = 0;
5991    _Py_IDENTIFIER(__bool__);
5992
5993    func = lookup_maybe(self, &PyId___bool__);
5994    if (func == NULL) {
5995        if (PyErr_Occurred()) {
5996            return -1;
5997        }
5998
5999        func = lookup_maybe(self, &PyId___len__);
6000        if (func == NULL) {
6001            if (PyErr_Occurred()) {
6002                return -1;
6003            }
6004            return 1;
6005        }
6006        using_len = 1;
6007    }
6008
6009    value = _PyObject_CallNoArg(func);
6010    if (value == NULL) {
6011        goto error;
6012    }
6013
6014    if (using_len) {
6015        /* bool type enforced by slot_nb_len */
6016        result = PyObject_IsTrue(value);
6017    }
6018    else if (PyBool_Check(value)) {
6019        result = PyObject_IsTrue(value);
6020    }
6021    else {
6022        PyErr_Format(PyExc_TypeError,
6023                     "__bool__ should return "
6024                     "bool, returned %s",
6025                     Py_TYPE(value)->tp_name);
6026        result = -1;
6027    }
6028
6029    Py_DECREF(value);
6030    Py_DECREF(func);
6031    return result;
6032
6033error:
6034    Py_DECREF(func);
6035    return -1;
6036}
6037
6038
6039static PyObject *
6040slot_nb_index(PyObject *self)
6041{
6042    _Py_IDENTIFIER(__index__);
6043    return call_method(self, &PyId___index__, NULL);
6044}
6045
6046
6047SLOT0(slot_nb_invert, "__invert__")
6048SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
6049SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
6050SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
6051SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
6052SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
6053
6054SLOT0(slot_nb_int, "__int__")
6055SLOT0(slot_nb_float, "__float__")
6056SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
6057SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
6058SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
6059SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *, "O")
6060SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
6061/* Can't use SLOT1 here, because nb_inplace_power is ternary */
6062static PyObject *
6063slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
6064{
6065    _Py_IDENTIFIER(__ipow__);
6066    return call_method(self, &PyId___ipow__, "(" "O" ")", arg1);
6067}
6068SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
6069SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
6070SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
6071SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
6072SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
6073SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
6074         "__floordiv__", "__rfloordiv__")
6075SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
6076SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
6077SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
6078
6079static PyObject *
6080slot_tp_repr(PyObject *self)
6081{
6082    PyObject *func, *res;
6083    _Py_IDENTIFIER(__repr__);
6084
6085    func = lookup_method(self, &PyId___repr__);
6086    if (func != NULL) {
6087        res = PyEval_CallObject(func, NULL);
6088        Py_DECREF(func);
6089        return res;
6090    }
6091    PyErr_Clear();
6092    return PyUnicode_FromFormat("<%s object at %p>",
6093                               Py_TYPE(self)->tp_name, self);
6094}
6095
6096static PyObject *
6097slot_tp_str(PyObject *self)
6098{
6099    PyObject *func, *res;
6100    _Py_IDENTIFIER(__str__);
6101
6102    func = lookup_method(self, &PyId___str__);
6103    if (func == NULL)
6104        return NULL;
6105    res = PyEval_CallObject(func, NULL);
6106    Py_DECREF(func);
6107    return res;
6108}
6109
6110static Py_hash_t
6111slot_tp_hash(PyObject *self)
6112{
6113    PyObject *func, *res;
6114    Py_ssize_t h;
6115
6116    func = lookup_method(self, &PyId___hash__);
6117
6118    if (func == Py_None) {
6119        Py_DECREF(func);
6120        func = NULL;
6121    }
6122
6123    if (func == NULL) {
6124        return PyObject_HashNotImplemented(self);
6125    }
6126
6127    res = PyEval_CallObject(func, NULL);
6128    Py_DECREF(func);
6129    if (res == NULL)
6130        return -1;
6131
6132    if (!PyLong_Check(res)) {
6133        PyErr_SetString(PyExc_TypeError,
6134                        "__hash__ method should return an integer");
6135        return -1;
6136    }
6137    /* Transform the PyLong `res` to a Py_hash_t `h`.  For an existing
6138       hashable Python object x, hash(x) will always lie within the range of
6139       Py_hash_t.  Therefore our transformation must preserve values that
6140       already lie within this range, to ensure that if x.__hash__() returns
6141       hash(y) then hash(x) == hash(y). */
6142    h = PyLong_AsSsize_t(res);
6143    if (h == -1 && PyErr_Occurred()) {
6144        /* res was not within the range of a Py_hash_t, so we're free to
6145           use any sufficiently bit-mixing transformation;
6146           long.__hash__ will do nicely. */
6147        PyErr_Clear();
6148        h = PyLong_Type.tp_hash(res);
6149    }
6150    /* -1 is reserved for errors. */
6151    if (h == -1)
6152        h = -2;
6153    Py_DECREF(res);
6154    return h;
6155}
6156
6157static PyObject *
6158slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
6159{
6160    _Py_IDENTIFIER(__call__);
6161    PyObject *meth = lookup_method(self, &PyId___call__);
6162    PyObject *res;
6163
6164    if (meth == NULL)
6165        return NULL;
6166
6167    res = PyObject_Call(meth, args, kwds);
6168
6169    Py_DECREF(meth);
6170    return res;
6171}
6172
6173/* There are two slot dispatch functions for tp_getattro.
6174
6175   - slot_tp_getattro() is used when __getattribute__ is overridden
6176     but no __getattr__ hook is present;
6177
6178   - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
6179
6180   The code in update_one_slot() always installs slot_tp_getattr_hook(); this
6181   detects the absence of __getattr__ and then installs the simpler slot if
6182   necessary. */
6183
6184static PyObject *
6185slot_tp_getattro(PyObject *self, PyObject *name)
6186{
6187    return call_method(self, &PyId___getattribute__, "(O)", name);
6188}
6189
6190static PyObject *
6191call_attribute(PyObject *self, PyObject *attr, PyObject *name)
6192{
6193    PyObject *res, *descr = NULL;
6194    descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
6195
6196    if (f != NULL) {
6197        descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
6198        if (descr == NULL)
6199            return NULL;
6200        else
6201            attr = descr;
6202    }
6203    res = PyObject_CallFunctionObjArgs(attr, name, NULL);
6204    Py_XDECREF(descr);
6205    return res;
6206}
6207
6208static PyObject *
6209slot_tp_getattr_hook(PyObject *self, PyObject *name)
6210{
6211    PyTypeObject *tp = Py_TYPE(self);
6212    PyObject *getattr, *getattribute, *res;
6213    _Py_IDENTIFIER(__getattr__);
6214
6215    /* speed hack: we could use lookup_maybe, but that would resolve the
6216       method fully for each attribute lookup for classes with
6217       __getattr__, even when the attribute is present. So we use
6218       _PyType_Lookup and create the method only when needed, with
6219       call_attribute. */
6220    getattr = _PyType_LookupId(tp, &PyId___getattr__);
6221    if (getattr == NULL) {
6222        /* No __getattr__ hook: use a simpler dispatcher */
6223        tp->tp_getattro = slot_tp_getattro;
6224        return slot_tp_getattro(self, name);
6225    }
6226    Py_INCREF(getattr);
6227    /* speed hack: we could use lookup_maybe, but that would resolve the
6228       method fully for each attribute lookup for classes with
6229       __getattr__, even when self has the default __getattribute__
6230       method. So we use _PyType_Lookup and create the method only when
6231       needed, with call_attribute. */
6232    getattribute = _PyType_LookupId(tp, &PyId___getattribute__);
6233    if (getattribute == NULL ||
6234        (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
6235         ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
6236         (void *)PyObject_GenericGetAttr))
6237        res = PyObject_GenericGetAttr(self, name);
6238    else {
6239        Py_INCREF(getattribute);
6240        res = call_attribute(self, getattribute, name);
6241        Py_DECREF(getattribute);
6242    }
6243    if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
6244        PyErr_Clear();
6245        res = call_attribute(self, getattr, name);
6246    }
6247    Py_DECREF(getattr);
6248    return res;
6249}
6250
6251static int
6252slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
6253{
6254    PyObject *res;
6255    _Py_IDENTIFIER(__delattr__);
6256    _Py_IDENTIFIER(__setattr__);
6257
6258    if (value == NULL)
6259        res = call_method(self, &PyId___delattr__, "(O)", name);
6260    else
6261        res = call_method(self, &PyId___setattr__, "(OO)", name, value);
6262    if (res == NULL)
6263        return -1;
6264    Py_DECREF(res);
6265    return 0;
6266}
6267
6268static _Py_Identifier name_op[] = {
6269    {0, "__lt__", 0},
6270    {0, "__le__", 0},
6271    {0, "__eq__", 0},
6272    {0, "__ne__", 0},
6273    {0, "__gt__", 0},
6274    {0, "__ge__", 0}
6275};
6276
6277static PyObject *
6278slot_tp_richcompare(PyObject *self, PyObject *other, int op)
6279{
6280    PyObject *func, *res;
6281
6282    func = lookup_method(self, &name_op[op]);
6283    if (func == NULL) {
6284        PyErr_Clear();
6285        Py_RETURN_NOTIMPLEMENTED;
6286    }
6287    res = _PyObject_CallArg1(func, other);
6288    Py_DECREF(func);
6289    return res;
6290}
6291
6292static PyObject *
6293slot_tp_iter(PyObject *self)
6294{
6295    PyObject *func, *res;
6296    _Py_IDENTIFIER(__iter__);
6297
6298    func = lookup_method(self, &PyId___iter__);
6299    if (func == Py_None) {
6300        Py_DECREF(func);
6301        PyErr_Format(PyExc_TypeError,
6302                     "'%.200s' object is not iterable",
6303                     Py_TYPE(self)->tp_name);
6304        return NULL;
6305    }
6306
6307    if (func != NULL) {
6308        res = _PyObject_CallNoArg(func);
6309        Py_DECREF(func);
6310        return res;
6311    }
6312
6313    PyErr_Clear();
6314    func = lookup_method(self, &PyId___getitem__);
6315    if (func == NULL) {
6316        PyErr_Format(PyExc_TypeError,
6317                     "'%.200s' object is not iterable",
6318                     Py_TYPE(self)->tp_name);
6319        return NULL;
6320    }
6321    Py_DECREF(func);
6322    return PySeqIter_New(self);
6323}
6324
6325static PyObject *
6326slot_tp_iternext(PyObject *self)
6327{
6328    _Py_IDENTIFIER(__next__);
6329    return call_method(self, &PyId___next__, NULL);
6330}
6331
6332static PyObject *
6333slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6334{
6335    PyTypeObject *tp = Py_TYPE(self);
6336    PyObject *get;
6337    _Py_IDENTIFIER(__get__);
6338
6339    get = _PyType_LookupId(tp, &PyId___get__);
6340    if (get == NULL) {
6341        /* Avoid further slowdowns */
6342        if (tp->tp_descr_get == slot_tp_descr_get)
6343            tp->tp_descr_get = NULL;
6344        Py_INCREF(self);
6345        return self;
6346    }
6347    if (obj == NULL)
6348        obj = Py_None;
6349    if (type == NULL)
6350        type = Py_None;
6351    return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
6352}
6353
6354static int
6355slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
6356{
6357    PyObject *res;
6358    _Py_IDENTIFIER(__delete__);
6359    _Py_IDENTIFIER(__set__);
6360
6361    if (value == NULL)
6362        res = call_method(self, &PyId___delete__, "(O)", target);
6363    else
6364        res = call_method(self, &PyId___set__, "(OO)", target, value);
6365    if (res == NULL)
6366        return -1;
6367    Py_DECREF(res);
6368    return 0;
6369}
6370
6371static int
6372slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
6373{
6374    _Py_IDENTIFIER(__init__);
6375    PyObject *meth = lookup_method(self, &PyId___init__);
6376    PyObject *res;
6377
6378    if (meth == NULL)
6379        return -1;
6380    res = PyObject_Call(meth, args, kwds);
6381    Py_DECREF(meth);
6382    if (res == NULL)
6383        return -1;
6384    if (res != Py_None) {
6385        PyErr_Format(PyExc_TypeError,
6386                     "__init__() should return None, not '%.200s'",
6387                     Py_TYPE(res)->tp_name);
6388        Py_DECREF(res);
6389        return -1;
6390    }
6391    Py_DECREF(res);
6392    return 0;
6393}
6394
6395static PyObject *
6396slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6397{
6398    PyObject *func, *result;
6399
6400    func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
6401    if (func == NULL) {
6402        return NULL;
6403    }
6404
6405    result = _PyObject_Call_Prepend(func, (PyObject *)type, args, kwds);
6406    Py_DECREF(func);
6407    return result;
6408}
6409
6410static void
6411slot_tp_finalize(PyObject *self)
6412{
6413    _Py_IDENTIFIER(__del__);
6414    PyObject *del, *res;
6415    PyObject *error_type, *error_value, *error_traceback;
6416
6417    /* Save the current exception, if any. */
6418    PyErr_Fetch(&error_type, &error_value, &error_traceback);
6419
6420    /* Execute __del__ method, if any. */
6421    del = lookup_maybe(self, &PyId___del__);
6422    if (del != NULL) {
6423        res = PyEval_CallObject(del, NULL);
6424        if (res == NULL)
6425            PyErr_WriteUnraisable(del);
6426        else
6427            Py_DECREF(res);
6428        Py_DECREF(del);
6429    }
6430
6431    /* Restore the saved exception. */
6432    PyErr_Restore(error_type, error_value, error_traceback);
6433}
6434
6435static PyObject *
6436slot_am_await(PyObject *self)
6437{
6438    PyObject *func, *res;
6439    _Py_IDENTIFIER(__await__);
6440
6441    func = lookup_method(self, &PyId___await__);
6442    if (func != NULL) {
6443        res = PyEval_CallObject(func, NULL);
6444        Py_DECREF(func);
6445        return res;
6446    }
6447    PyErr_Format(PyExc_AttributeError,
6448                 "object %.50s does not have __await__ method",
6449                 Py_TYPE(self)->tp_name);
6450    return NULL;
6451}
6452
6453static PyObject *
6454slot_am_aiter(PyObject *self)
6455{
6456    PyObject *func, *res;
6457    _Py_IDENTIFIER(__aiter__);
6458
6459    func = lookup_method(self, &PyId___aiter__);
6460    if (func != NULL) {
6461        res = PyEval_CallObject(func, NULL);
6462        Py_DECREF(func);
6463        return res;
6464    }
6465    PyErr_Format(PyExc_AttributeError,
6466                 "object %.50s does not have __aiter__ method",
6467                 Py_TYPE(self)->tp_name);
6468    return NULL;
6469}
6470
6471static PyObject *
6472slot_am_anext(PyObject *self)
6473{
6474    PyObject *func, *res;
6475    _Py_IDENTIFIER(__anext__);
6476
6477    func = lookup_method(self, &PyId___anext__);
6478    if (func != NULL) {
6479        res = PyEval_CallObject(func, NULL);
6480        Py_DECREF(func);
6481        return res;
6482    }
6483    PyErr_Format(PyExc_AttributeError,
6484                 "object %.50s does not have __anext__ method",
6485                 Py_TYPE(self)->tp_name);
6486    return NULL;
6487}
6488
6489/*
6490Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6491
6492The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6493which incorporates the additional structures used for numbers, sequences and
6494mappings.  Note that multiple names may map to the same slot (e.g. __eq__,
6495__ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6496(e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6497an all-zero entry.  (This table is further initialized in init_slotdefs().)
6498*/
6499
6500typedef struct wrapperbase slotdef;
6501
6502#undef TPSLOT
6503#undef FLSLOT
6504#undef AMSLOT
6505#undef ETSLOT
6506#undef SQSLOT
6507#undef MPSLOT
6508#undef NBSLOT
6509#undef UNSLOT
6510#undef IBSLOT
6511#undef BINSLOT
6512#undef RBINSLOT
6513
6514#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6515    {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6516     PyDoc_STR(DOC)}
6517#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
6518    {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6519     PyDoc_STR(DOC), FLAGS}
6520#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6521    {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6522     PyDoc_STR(DOC)}
6523#define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6524    ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
6525#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6526    ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
6527#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6528    ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
6529#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6530    ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
6531#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6532    ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
6533           NAME "($self, /)\n--\n\n" DOC)
6534#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6535    ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
6536           NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
6537#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
6538    ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
6539           NAME "($self, value, /)\n--\n\nReturn self" DOC "value.")
6540#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
6541    ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
6542           NAME "($self, value, /)\n--\n\nReturn value" DOC "self.")
6543#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
6544    ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
6545           NAME "($self, value, /)\n--\n\n" DOC)
6546#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
6547    ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
6548           NAME "($self, value, /)\n--\n\n" DOC)
6549
6550static slotdef slotdefs[] = {
6551    TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
6552    TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
6553    TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
6554    TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
6555    TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
6556           "__repr__($self, /)\n--\n\nReturn repr(self)."),
6557    TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
6558           "__hash__($self, /)\n--\n\nReturn hash(self)."),
6559    FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
6560           "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.",
6561           PyWrapperFlag_KEYWORDS),
6562    TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
6563           "__str__($self, /)\n--\n\nReturn str(self)."),
6564    TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
6565           wrap_binaryfunc,
6566           "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."),
6567    TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
6568    TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
6569           "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."),
6570    TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
6571           "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."),
6572    TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
6573           "__lt__($self, value, /)\n--\n\nReturn self<value."),
6574    TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
6575           "__le__($self, value, /)\n--\n\nReturn self<=value."),
6576    TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
6577           "__eq__($self, value, /)\n--\n\nReturn self==value."),
6578    TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
6579           "__ne__($self, value, /)\n--\n\nReturn self!=value."),
6580    TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
6581           "__gt__($self, value, /)\n--\n\nReturn self>value."),
6582    TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
6583           "__ge__($self, value, /)\n--\n\nReturn self>=value."),
6584    TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
6585           "__iter__($self, /)\n--\n\nImplement iter(self)."),
6586    TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
6587           "__next__($self, /)\n--\n\nImplement next(self)."),
6588    TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
6589           "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."),
6590    TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
6591           "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."),
6592    TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
6593           wrap_descr_delete,
6594           "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."),
6595    FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
6596           "__init__($self, /, *args, **kwargs)\n--\n\n"
6597           "Initialize self.  See help(type(self)) for accurate signature.",
6598           PyWrapperFlag_KEYWORDS),
6599    TPSLOT("__new__", tp_new, slot_tp_new, NULL,
6600           "__new__(type, /, *args, **kwargs)\n--\n\n"
6601           "Create and return new object.  See help(type) for accurate signature."),
6602    TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
6603
6604    AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
6605           "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."),
6606    AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
6607           "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."),
6608    AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
6609           "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."),
6610
6611    BINSLOT("__add__", nb_add, slot_nb_add,
6612           "+"),
6613    RBINSLOT("__radd__", nb_add, slot_nb_add,
6614           "+"),
6615    BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
6616           "-"),
6617    RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
6618           "-"),
6619    BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
6620           "*"),
6621    RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
6622           "*"),
6623    BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
6624           "%"),
6625    RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
6626           "%"),
6627    BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
6628           "Return divmod(self, value)."),
6629    RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
6630           "Return divmod(value, self)."),
6631    NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
6632           "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."),
6633    NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
6634           "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."),
6635    UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"),
6636    UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"),
6637    UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
6638           "abs(self)"),
6639    UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
6640           "self != 0"),
6641    UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"),
6642    BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
6643    RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
6644    BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
6645    RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
6646    BINSLOT("__and__", nb_and, slot_nb_and, "&"),
6647    RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
6648    BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
6649    RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
6650    BINSLOT("__or__", nb_or, slot_nb_or, "|"),
6651    RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
6652    UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
6653           "int(self)"),
6654    UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
6655           "float(self)"),
6656    IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
6657           wrap_binaryfunc, "+="),
6658    IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
6659           wrap_binaryfunc, "-="),
6660    IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
6661           wrap_binaryfunc, "*="),
6662    IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
6663           wrap_binaryfunc, "%="),
6664    IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
6665           wrap_binaryfunc, "**="),
6666    IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
6667           wrap_binaryfunc, "<<="),
6668    IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
6669           wrap_binaryfunc, ">>="),
6670    IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
6671           wrap_binaryfunc, "&="),
6672    IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
6673           wrap_binaryfunc, "^="),
6674    IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
6675           wrap_binaryfunc, "|="),
6676    BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6677    RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
6678    BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
6679    RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
6680    IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
6681           slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="),
6682    IBSLOT("__itruediv__", nb_inplace_true_divide,
6683           slot_nb_inplace_true_divide, wrap_binaryfunc, "/="),
6684    NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
6685           "__index__($self, /)\n--\n\n"
6686           "Return self converted to an integer, if self is suitable "
6687           "for use as an index into a list."),
6688    BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6689            "@"),
6690    RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply,
6691             "@"),
6692    IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply,
6693           wrap_binaryfunc, "@="),
6694    MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
6695           "__len__($self, /)\n--\n\nReturn len(self)."),
6696    MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
6697           wrap_binaryfunc,
6698           "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
6699    MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
6700           wrap_objobjargproc,
6701           "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
6702    MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
6703           wrap_delitem,
6704           "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
6705
6706    SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
6707           "__len__($self, /)\n--\n\nReturn len(self)."),
6708    /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
6709       The logic in abstract.c always falls back to nb_add/nb_multiply in
6710       this case.  Defining both the nb_* and the sq_* slots to call the
6711       user-defined methods has unexpected side-effects, as shown by
6712       test_descr.notimplemented() */
6713    SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
6714           "__add__($self, value, /)\n--\n\nReturn self+value."),
6715    SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
6716           "__mul__($self, value, /)\n--\n\nReturn self*value.n"),
6717    SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
6718           "__rmul__($self, value, /)\n--\n\nReturn self*value."),
6719    SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
6720           "__getitem__($self, key, /)\n--\n\nReturn self[key]."),
6721    SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
6722           "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."),
6723    SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
6724           "__delitem__($self, key, /)\n--\n\nDelete self[key]."),
6725    SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
6726           "__contains__($self, key, /)\n--\n\nReturn key in self."),
6727    SQSLOT("__iadd__", sq_inplace_concat, NULL,
6728           wrap_binaryfunc,
6729           "__iadd__($self, value, /)\n--\n\nImplement self+=value."),
6730    SQSLOT("__imul__", sq_inplace_repeat, NULL,
6731           wrap_indexargfunc,
6732           "__imul__($self, value, /)\n--\n\nImplement self*=value."),
6733
6734    {NULL}
6735};
6736
6737/* Given a type pointer and an offset gotten from a slotdef entry, return a
6738   pointer to the actual slot.  This is not quite the same as simply adding
6739   the offset to the type pointer, since it takes care to indirect through the
6740   proper indirection pointer (as_buffer, etc.); it returns NULL if the
6741   indirection pointer is NULL. */
6742static void **
6743slotptr(PyTypeObject *type, int ioffset)
6744{
6745    char *ptr;
6746    long offset = ioffset;
6747
6748    /* Note: this depends on the order of the members of PyHeapTypeObject! */
6749    assert(offset >= 0);
6750    assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
6751    if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
6752        ptr = (char *)type->tp_as_sequence;
6753        offset -= offsetof(PyHeapTypeObject, as_sequence);
6754    }
6755    else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6756        ptr = (char *)type->tp_as_mapping;
6757        offset -= offsetof(PyHeapTypeObject, as_mapping);
6758    }
6759    else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6760        ptr = (char *)type->tp_as_number;
6761        offset -= offsetof(PyHeapTypeObject, as_number);
6762    }
6763    else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
6764        ptr = (char *)type->tp_as_async;
6765        offset -= offsetof(PyHeapTypeObject, as_async);
6766    }
6767    else {
6768        ptr = (char *)type;
6769    }
6770    if (ptr != NULL)
6771        ptr += offset;
6772    return (void **)ptr;
6773}
6774
6775/* Length of array of slotdef pointers used to store slots with the
6776   same __name__.  There should be at most MAX_EQUIV-1 slotdef entries with
6777   the same __name__, for any __name__. Since that's a static property, it is
6778   appropriate to declare fixed-size arrays for this. */
6779#define MAX_EQUIV 10
6780
6781/* Return a slot pointer for a given name, but ONLY if the attribute has
6782   exactly one slot function.  The name must be an interned string. */
6783static void **
6784resolve_slotdups(PyTypeObject *type, PyObject *name)
6785{
6786    /* XXX Maybe this could be optimized more -- but is it worth it? */
6787
6788    /* pname and ptrs act as a little cache */
6789    static PyObject *pname;
6790    static slotdef *ptrs[MAX_EQUIV];
6791    slotdef *p, **pp;
6792    void **res, **ptr;
6793
6794    if (pname != name) {
6795        /* Collect all slotdefs that match name into ptrs. */
6796        pname = name;
6797        pp = ptrs;
6798        for (p = slotdefs; p->name_strobj; p++) {
6799            if (p->name_strobj == name)
6800                *pp++ = p;
6801        }
6802        *pp = NULL;
6803    }
6804
6805    /* Look in all matching slots of the type; if exactly one of these has
6806       a filled-in slot, return its value.      Otherwise return NULL. */
6807    res = NULL;
6808    for (pp = ptrs; *pp; pp++) {
6809        ptr = slotptr(type, (*pp)->offset);
6810        if (ptr == NULL || *ptr == NULL)
6811            continue;
6812        if (res != NULL)
6813            return NULL;
6814        res = ptr;
6815    }
6816    return res;
6817}
6818
6819/* Common code for update_slots_callback() and fixup_slot_dispatchers().  This
6820   does some incredibly complex thinking and then sticks something into the
6821   slot.  (It sees if the adjacent slotdefs for the same slot have conflicting
6822   interests, and then stores a generic wrapper or a specific function into
6823   the slot.)  Return a pointer to the next slotdef with a different offset,
6824   because that's convenient  for fixup_slot_dispatchers(). */
6825static slotdef *
6826update_one_slot(PyTypeObject *type, slotdef *p)
6827{
6828    PyObject *descr;
6829    PyWrapperDescrObject *d;
6830    void *generic = NULL, *specific = NULL;
6831    int use_generic = 0;
6832    int offset = p->offset;
6833    void **ptr = slotptr(type, offset);
6834
6835    if (ptr == NULL) {
6836        do {
6837            ++p;
6838        } while (p->offset == offset);
6839        return p;
6840    }
6841    do {
6842        descr = _PyType_Lookup(type, p->name_strobj);
6843        if (descr == NULL) {
6844            if (ptr == (void**)&type->tp_iternext) {
6845                specific = (void *)_PyObject_NextNotImplemented;
6846            }
6847            continue;
6848        }
6849        if (Py_TYPE(descr) == &PyWrapperDescr_Type &&
6850            ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) {
6851            void **tptr = resolve_slotdups(type, p->name_strobj);
6852            if (tptr == NULL || tptr == ptr)
6853                generic = p->function;
6854            d = (PyWrapperDescrObject *)descr;
6855            if (d->d_base->wrapper == p->wrapper &&
6856                PyType_IsSubtype(type, PyDescr_TYPE(d)))
6857            {
6858                if (specific == NULL ||
6859                    specific == d->d_wrapped)
6860                    specific = d->d_wrapped;
6861                else
6862                    use_generic = 1;
6863            }
6864        }
6865        else if (Py_TYPE(descr) == &PyCFunction_Type &&
6866                 PyCFunction_GET_FUNCTION(descr) ==
6867                 (PyCFunction)tp_new_wrapper &&
6868                 ptr == (void**)&type->tp_new)
6869        {
6870            /* The __new__ wrapper is not a wrapper descriptor,
6871               so must be special-cased differently.
6872               If we don't do this, creating an instance will
6873               always use slot_tp_new which will look up
6874               __new__ in the MRO which will call tp_new_wrapper
6875               which will look through the base classes looking
6876               for a static base and call its tp_new (usually
6877               PyType_GenericNew), after performing various
6878               sanity checks and constructing a new argument
6879               list.  Cut all that nonsense short -- this speeds
6880               up instance creation tremendously. */
6881            specific = (void *)type->tp_new;
6882            /* XXX I'm not 100% sure that there isn't a hole
6883               in this reasoning that requires additional
6884               sanity checks.  I'll buy the first person to
6885               point out a bug in this reasoning a beer. */
6886        }
6887        else if (descr == Py_None &&
6888                 ptr == (void**)&type->tp_hash) {
6889            /* We specifically allow __hash__ to be set to None
6890               to prevent inheritance of the default
6891               implementation from object.__hash__ */
6892            specific = (void *)PyObject_HashNotImplemented;
6893        }
6894        else {
6895            use_generic = 1;
6896            generic = p->function;
6897        }
6898    } while ((++p)->offset == offset);
6899    if (specific && !use_generic)
6900        *ptr = specific;
6901    else
6902        *ptr = generic;
6903    return p;
6904}
6905
6906/* In the type, update the slots whose slotdefs are gathered in the pp array.
6907   This is a callback for update_subclasses(). */
6908static int
6909update_slots_callback(PyTypeObject *type, void *data)
6910{
6911    slotdef **pp = (slotdef **)data;
6912
6913    for (; *pp; pp++)
6914        update_one_slot(type, *pp);
6915    return 0;
6916}
6917
6918static int slotdefs_initialized = 0;
6919/* Initialize the slotdefs table by adding interned string objects for the
6920   names. */
6921static void
6922init_slotdefs(void)
6923{
6924    slotdef *p;
6925
6926    if (slotdefs_initialized)
6927        return;
6928    for (p = slotdefs; p->name; p++) {
6929        /* Slots must be ordered by their offset in the PyHeapTypeObject. */
6930        assert(!p[1].name || p->offset <= p[1].offset);
6931        p->name_strobj = PyUnicode_InternFromString(p->name);
6932        if (!p->name_strobj)
6933            Py_FatalError("Out of memory interning slotdef names");
6934    }
6935    slotdefs_initialized = 1;
6936}
6937
6938/* Undo init_slotdefs, releasing the interned strings. */
6939static void clear_slotdefs(void)
6940{
6941    slotdef *p;
6942    for (p = slotdefs; p->name; p++) {
6943        Py_CLEAR(p->name_strobj);
6944    }
6945    slotdefs_initialized = 0;
6946}
6947
6948/* Update the slots after assignment to a class (type) attribute. */
6949static int
6950update_slot(PyTypeObject *type, PyObject *name)
6951{
6952    slotdef *ptrs[MAX_EQUIV];
6953    slotdef *p;
6954    slotdef **pp;
6955    int offset;
6956
6957    /* Clear the VALID_VERSION flag of 'type' and all its
6958       subclasses.  This could possibly be unified with the
6959       update_subclasses() recursion below, but carefully:
6960       they each have their own conditions on which to stop
6961       recursing into subclasses. */
6962    PyType_Modified(type);
6963
6964    init_slotdefs();
6965    pp = ptrs;
6966    for (p = slotdefs; p->name; p++) {
6967        /* XXX assume name is interned! */
6968        if (p->name_strobj == name)
6969            *pp++ = p;
6970    }
6971    *pp = NULL;
6972    for (pp = ptrs; *pp; pp++) {
6973        p = *pp;
6974        offset = p->offset;
6975        while (p > slotdefs && (p-1)->offset == offset)
6976            --p;
6977        *pp = p;
6978    }
6979    if (ptrs[0] == NULL)
6980        return 0; /* Not an attribute that affects any slots */
6981    return update_subclasses(type, name,
6982                             update_slots_callback, (void *)ptrs);
6983}
6984
6985/* Store the proper functions in the slot dispatches at class (type)
6986   definition time, based upon which operations the class overrides in its
6987   dict. */
6988static void
6989fixup_slot_dispatchers(PyTypeObject *type)
6990{
6991    slotdef *p;
6992
6993    init_slotdefs();
6994    for (p = slotdefs; p->name; )
6995        p = update_one_slot(type, p);
6996}
6997
6998static void
6999update_all_slots(PyTypeObject* type)
7000{
7001    slotdef *p;
7002
7003    init_slotdefs();
7004    for (p = slotdefs; p->name; p++) {
7005        /* update_slot returns int but can't actually fail */
7006        update_slot(type, p->name_strobj);
7007    }
7008}
7009
7010/* Call __set_name__ on all descriptors in a newly generated type */
7011static int
7012set_names(PyTypeObject *type)
7013{
7014    PyObject *names_to_set, *key, *value, *set_name, *tmp;
7015    Py_ssize_t i = 0;
7016
7017    names_to_set = PyDict_Copy(type->tp_dict);
7018    if (names_to_set == NULL)
7019        return -1;
7020
7021    while (PyDict_Next(names_to_set, &i, &key, &value)) {
7022        set_name = lookup_maybe(value, &PyId___set_name__);
7023        if (set_name != NULL) {
7024            tmp = PyObject_CallFunctionObjArgs(set_name, type, key, NULL);
7025            Py_DECREF(set_name);
7026            if (tmp == NULL) {
7027                _PyErr_FormatFromCause(PyExc_RuntimeError,
7028                    "Error calling __set_name__ on '%.100s' instance %R "
7029                    "in '%.100s'",
7030                    value->ob_type->tp_name, key, type->tp_name);
7031                Py_DECREF(names_to_set);
7032                return -1;
7033            }
7034            else
7035                Py_DECREF(tmp);
7036        }
7037        else if (PyErr_Occurred()) {
7038            Py_DECREF(names_to_set);
7039            return -1;
7040        }
7041    }
7042
7043    Py_DECREF(names_to_set);
7044    return 0;
7045}
7046
7047/* Call __init_subclass__ on the parent of a newly generated type */
7048static int
7049init_subclass(PyTypeObject *type, PyObject *kwds)
7050{
7051    PyObject *super, *func, *result;
7052    PyObject *args[2] = {(PyObject *)type, (PyObject *)type};
7053
7054    super = _PyObject_FastCall((PyObject *)&PySuper_Type, args, 2);
7055    if (super == NULL) {
7056        return -1;
7057    }
7058
7059    func = _PyObject_GetAttrId(super, &PyId___init_subclass__);
7060    Py_DECREF(super);
7061    if (func == NULL) {
7062        return -1;
7063    }
7064
7065
7066    result = _PyObject_FastCallDict(func, NULL, 0, kwds);
7067    Py_DECREF(func);
7068    if (result == NULL) {
7069        return -1;
7070    }
7071
7072    Py_DECREF(result);
7073    return 0;
7074}
7075
7076/* recurse_down_subclasses() and update_subclasses() are mutually
7077   recursive functions to call a callback for all subclasses,
7078   but refraining from recursing into subclasses that define 'name'. */
7079
7080static int
7081update_subclasses(PyTypeObject *type, PyObject *name,
7082                  update_callback callback, void *data)
7083{
7084    if (callback(type, data) < 0)
7085        return -1;
7086    return recurse_down_subclasses(type, name, callback, data);
7087}
7088
7089static int
7090recurse_down_subclasses(PyTypeObject *type, PyObject *name,
7091                        update_callback callback, void *data)
7092{
7093    PyTypeObject *subclass;
7094    PyObject *ref, *subclasses, *dict;
7095    Py_ssize_t i;
7096
7097    subclasses = type->tp_subclasses;
7098    if (subclasses == NULL)
7099        return 0;
7100    assert(PyDict_CheckExact(subclasses));
7101    i = 0;
7102    while (PyDict_Next(subclasses, &i, NULL, &ref)) {
7103        assert(PyWeakref_CheckRef(ref));
7104        subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
7105        assert(subclass != NULL);
7106        if ((PyObject *)subclass == Py_None)
7107            continue;
7108        assert(PyType_Check(subclass));
7109        /* Avoid recursing down into unaffected classes */
7110        dict = subclass->tp_dict;
7111        if (dict != NULL && PyDict_Check(dict) &&
7112            PyDict_GetItem(dict, name) != NULL)
7113            continue;
7114        if (update_subclasses(subclass, name, callback, data) < 0)
7115            return -1;
7116    }
7117    return 0;
7118}
7119
7120/* This function is called by PyType_Ready() to populate the type's
7121   dictionary with method descriptors for function slots.  For each
7122   function slot (like tp_repr) that's defined in the type, one or more
7123   corresponding descriptors are added in the type's tp_dict dictionary
7124   under the appropriate name (like __repr__).  Some function slots
7125   cause more than one descriptor to be added (for example, the nb_add
7126   slot adds both __add__ and __radd__ descriptors) and some function
7127   slots compete for the same descriptor (for example both sq_item and
7128   mp_subscript generate a __getitem__ descriptor).
7129
7130   In the latter case, the first slotdef entry encountered wins.  Since
7131   slotdef entries are sorted by the offset of the slot in the
7132   PyHeapTypeObject, this gives us some control over disambiguating
7133   between competing slots: the members of PyHeapTypeObject are listed
7134   from most general to least general, so the most general slot is
7135   preferred.  In particular, because as_mapping comes before as_sequence,
7136   for a type that defines both mp_subscript and sq_item, mp_subscript
7137   wins.
7138
7139   This only adds new descriptors and doesn't overwrite entries in
7140   tp_dict that were previously defined.  The descriptors contain a
7141   reference to the C function they must call, so that it's safe if they
7142   are copied into a subtype's __dict__ and the subtype has a different
7143   C function in its slot -- calling the method defined by the
7144   descriptor will call the C function that was used to create it,
7145   rather than the C function present in the slot when it is called.
7146   (This is important because a subtype may have a C function in the
7147   slot that calls the method from the dictionary, and we want to avoid
7148   infinite recursion here.) */
7149
7150static int
7151add_operators(PyTypeObject *type)
7152{
7153    PyObject *dict = type->tp_dict;
7154    slotdef *p;
7155    PyObject *descr;
7156    void **ptr;
7157
7158    init_slotdefs();
7159    for (p = slotdefs; p->name; p++) {
7160        if (p->wrapper == NULL)
7161            continue;
7162        ptr = slotptr(type, p->offset);
7163        if (!ptr || !*ptr)
7164            continue;
7165        if (PyDict_GetItem(dict, p->name_strobj))
7166            continue;
7167        if (*ptr == (void *)PyObject_HashNotImplemented) {
7168            /* Classes may prevent the inheritance of the tp_hash
7169               slot by storing PyObject_HashNotImplemented in it. Make it
7170               visible as a None value for the __hash__ attribute. */
7171            if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
7172                return -1;
7173        }
7174        else {
7175            descr = PyDescr_NewWrapper(type, p, *ptr);
7176            if (descr == NULL)
7177                return -1;
7178            if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
7179                Py_DECREF(descr);
7180                return -1;
7181            }
7182            Py_DECREF(descr);
7183        }
7184    }
7185    if (type->tp_new != NULL) {
7186        if (add_tp_new_wrapper(type) < 0)
7187            return -1;
7188    }
7189    return 0;
7190}
7191
7192
7193/* Cooperative 'super' */
7194
7195typedef struct {
7196    PyObject_HEAD
7197    PyTypeObject *type;
7198    PyObject *obj;
7199    PyTypeObject *obj_type;
7200} superobject;
7201
7202static PyMemberDef super_members[] = {
7203    {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
7204     "the class invoking super()"},
7205    {"__self__",  T_OBJECT, offsetof(superobject, obj), READONLY,
7206     "the instance invoking super(); may be None"},
7207    {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
7208     "the type of the instance invoking super(); may be None"},
7209    {0}
7210};
7211
7212static void
7213super_dealloc(PyObject *self)
7214{
7215    superobject *su = (superobject *)self;
7216
7217    _PyObject_GC_UNTRACK(self);
7218    Py_XDECREF(su->obj);
7219    Py_XDECREF(su->type);
7220    Py_XDECREF(su->obj_type);
7221    Py_TYPE(self)->tp_free(self);
7222}
7223
7224static PyObject *
7225super_repr(PyObject *self)
7226{
7227    superobject *su = (superobject *)self;
7228
7229    if (su->obj_type)
7230        return PyUnicode_FromFormat(
7231            "<super: <class '%s'>, <%s object>>",
7232            su->type ? su->type->tp_name : "NULL",
7233            su->obj_type->tp_name);
7234    else
7235        return PyUnicode_FromFormat(
7236            "<super: <class '%s'>, NULL>",
7237            su->type ? su->type->tp_name : "NULL");
7238}
7239
7240static PyObject *
7241super_getattro(PyObject *self, PyObject *name)
7242{
7243    superobject *su = (superobject *)self;
7244    PyTypeObject *starttype;
7245    PyObject *mro;
7246    Py_ssize_t i, n;
7247
7248    starttype = su->obj_type;
7249    if (starttype == NULL)
7250        goto skip;
7251
7252    /* We want __class__ to return the class of the super object
7253       (i.e. super, or a subclass), not the class of su->obj. */
7254    if (PyUnicode_Check(name) &&
7255        PyUnicode_GET_LENGTH(name) == 9 &&
7256        _PyUnicode_EqualToASCIIId(name, &PyId___class__))
7257        goto skip;
7258
7259    mro = starttype->tp_mro;
7260    if (mro == NULL)
7261        goto skip;
7262
7263    assert(PyTuple_Check(mro));
7264    n = PyTuple_GET_SIZE(mro);
7265
7266    /* No need to check the last one: it's gonna be skipped anyway.  */
7267    for (i = 0; i+1 < n; i++) {
7268        if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
7269            break;
7270    }
7271    i++;  /* skip su->type (if any)  */
7272    if (i >= n)
7273        goto skip;
7274
7275    /* keep a strong reference to mro because starttype->tp_mro can be
7276       replaced during PyDict_GetItem(dict, name)  */
7277    Py_INCREF(mro);
7278    do {
7279        PyObject *res, *tmp, *dict;
7280        descrgetfunc f;
7281
7282        tmp = PyTuple_GET_ITEM(mro, i);
7283        assert(PyType_Check(tmp));
7284
7285        dict = ((PyTypeObject *)tmp)->tp_dict;
7286        assert(dict != NULL && PyDict_Check(dict));
7287
7288        res = PyDict_GetItem(dict, name);
7289        if (res != NULL) {
7290            Py_INCREF(res);
7291
7292            f = Py_TYPE(res)->tp_descr_get;
7293            if (f != NULL) {
7294                tmp = f(res,
7295                    /* Only pass 'obj' param if this is instance-mode super
7296                       (See SF ID #743627)  */
7297                    (su->obj == (PyObject *)starttype) ? NULL : su->obj,
7298                    (PyObject *)starttype);
7299                Py_DECREF(res);
7300                res = tmp;
7301            }
7302
7303            Py_DECREF(mro);
7304            return res;
7305        }
7306
7307        i++;
7308    } while (i < n);
7309    Py_DECREF(mro);
7310
7311  skip:
7312    return PyObject_GenericGetAttr(self, name);
7313}
7314
7315static PyTypeObject *
7316supercheck(PyTypeObject *type, PyObject *obj)
7317{
7318    /* Check that a super() call makes sense.  Return a type object.
7319
7320       obj can be a class, or an instance of one:
7321
7322       - If it is a class, it must be a subclass of 'type'.      This case is
7323         used for class methods; the return value is obj.
7324
7325       - If it is an instance, it must be an instance of 'type'.  This is
7326         the normal case; the return value is obj.__class__.
7327
7328       But... when obj is an instance, we want to allow for the case where
7329       Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
7330       This will allow using super() with a proxy for obj.
7331    */
7332
7333    /* Check for first bullet above (special case) */
7334    if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
7335        Py_INCREF(obj);
7336        return (PyTypeObject *)obj;
7337    }
7338
7339    /* Normal case */
7340    if (PyType_IsSubtype(Py_TYPE(obj), type)) {
7341        Py_INCREF(Py_TYPE(obj));
7342        return Py_TYPE(obj);
7343    }
7344    else {
7345        /* Try the slow way */
7346        PyObject *class_attr;
7347
7348        class_attr = _PyObject_GetAttrId(obj, &PyId___class__);
7349        if (class_attr != NULL &&
7350            PyType_Check(class_attr) &&
7351            (PyTypeObject *)class_attr != Py_TYPE(obj))
7352        {
7353            int ok = PyType_IsSubtype(
7354                (PyTypeObject *)class_attr, type);
7355            if (ok)
7356                return (PyTypeObject *)class_attr;
7357        }
7358
7359        if (class_attr == NULL)
7360            PyErr_Clear();
7361        else
7362            Py_DECREF(class_attr);
7363    }
7364
7365    PyErr_SetString(PyExc_TypeError,
7366                    "super(type, obj): "
7367                    "obj must be an instance or subtype of type");
7368    return NULL;
7369}
7370
7371static PyObject *
7372super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
7373{
7374    superobject *su = (superobject *)self;
7375    superobject *newobj;
7376
7377    if (obj == NULL || obj == Py_None || su->obj != NULL) {
7378        /* Not binding to an object, or already bound */
7379        Py_INCREF(self);
7380        return self;
7381    }
7382    if (Py_TYPE(su) != &PySuper_Type)
7383        /* If su is an instance of a (strict) subclass of super,
7384           call its type */
7385        return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
7386                                            su->type, obj, NULL);
7387    else {
7388        /* Inline the common case */
7389        PyTypeObject *obj_type = supercheck(su->type, obj);
7390        if (obj_type == NULL)
7391            return NULL;
7392        newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
7393                                                 NULL, NULL);
7394        if (newobj == NULL)
7395            return NULL;
7396        Py_INCREF(su->type);
7397        Py_INCREF(obj);
7398        newobj->type = su->type;
7399        newobj->obj = obj;
7400        newobj->obj_type = obj_type;
7401        return (PyObject *)newobj;
7402    }
7403}
7404
7405static int
7406super_init(PyObject *self, PyObject *args, PyObject *kwds)
7407{
7408    superobject *su = (superobject *)self;
7409    PyTypeObject *type = NULL;
7410    PyObject *obj = NULL;
7411    PyTypeObject *obj_type = NULL;
7412
7413    if (!_PyArg_NoKeywords("super", kwds))
7414        return -1;
7415    if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
7416        return -1;
7417
7418    if (type == NULL) {
7419        /* Call super(), without args -- fill in from __class__
7420           and first local variable on the stack. */
7421        PyFrameObject *f;
7422        PyCodeObject *co;
7423        Py_ssize_t i, n;
7424        f = PyThreadState_GET()->frame;
7425        if (f == NULL) {
7426            PyErr_SetString(PyExc_RuntimeError,
7427                            "super(): no current frame");
7428            return -1;
7429        }
7430        co = f->f_code;
7431        if (co == NULL) {
7432            PyErr_SetString(PyExc_RuntimeError,
7433                            "super(): no code object");
7434            return -1;
7435        }
7436        if (co->co_argcount == 0) {
7437            PyErr_SetString(PyExc_RuntimeError,
7438                            "super(): no arguments");
7439            return -1;
7440        }
7441        obj = f->f_localsplus[0];
7442        if (obj == NULL && co->co_cell2arg) {
7443            /* The first argument might be a cell. */
7444            n = PyTuple_GET_SIZE(co->co_cellvars);
7445            for (i = 0; i < n; i++) {
7446                if (co->co_cell2arg[i] == 0) {
7447                    PyObject *cell = f->f_localsplus[co->co_nlocals + i];
7448                    assert(PyCell_Check(cell));
7449                    obj = PyCell_GET(cell);
7450                    break;
7451                }
7452            }
7453        }
7454        if (obj == NULL) {
7455            PyErr_SetString(PyExc_RuntimeError,
7456                            "super(): arg[0] deleted");
7457            return -1;
7458        }
7459        if (co->co_freevars == NULL)
7460            n = 0;
7461        else {
7462            assert(PyTuple_Check(co->co_freevars));
7463            n = PyTuple_GET_SIZE(co->co_freevars);
7464        }
7465        for (i = 0; i < n; i++) {
7466            PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
7467            assert(PyUnicode_Check(name));
7468            if (_PyUnicode_EqualToASCIIId(name, &PyId___class__)) {
7469                Py_ssize_t index = co->co_nlocals +
7470                    PyTuple_GET_SIZE(co->co_cellvars) + i;
7471                PyObject *cell = f->f_localsplus[index];
7472                if (cell == NULL || !PyCell_Check(cell)) {
7473                    PyErr_SetString(PyExc_RuntimeError,
7474                      "super(): bad __class__ cell");
7475                    return -1;
7476                }
7477                type = (PyTypeObject *) PyCell_GET(cell);
7478                if (type == NULL) {
7479                    PyErr_SetString(PyExc_RuntimeError,
7480                      "super(): empty __class__ cell");
7481                    return -1;
7482                }
7483                if (!PyType_Check(type)) {
7484                    PyErr_Format(PyExc_RuntimeError,
7485                      "super(): __class__ is not a type (%s)",
7486                      Py_TYPE(type)->tp_name);
7487                    return -1;
7488                }
7489                break;
7490            }
7491        }
7492        if (type == NULL) {
7493            PyErr_SetString(PyExc_RuntimeError,
7494                            "super(): __class__ cell not found");
7495            return -1;
7496        }
7497    }
7498
7499    if (obj == Py_None)
7500        obj = NULL;
7501    if (obj != NULL) {
7502        obj_type = supercheck(type, obj);
7503        if (obj_type == NULL)
7504            return -1;
7505        Py_INCREF(obj);
7506    }
7507    Py_INCREF(type);
7508    Py_XSETREF(su->type, type);
7509    Py_XSETREF(su->obj, obj);
7510    Py_XSETREF(su->obj_type, obj_type);
7511    return 0;
7512}
7513
7514PyDoc_STRVAR(super_doc,
7515"super() -> same as super(__class__, <first argument>)\n"
7516"super(type) -> unbound super object\n"
7517"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
7518"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
7519"Typical use to call a cooperative superclass method:\n"
7520"class C(B):\n"
7521"    def meth(self, arg):\n"
7522"        super().meth(arg)\n"
7523"This works for class methods too:\n"
7524"class C(B):\n"
7525"    @classmethod\n"
7526"    def cmeth(cls, arg):\n"
7527"        super().cmeth(arg)\n");
7528
7529static int
7530super_traverse(PyObject *self, visitproc visit, void *arg)
7531{
7532    superobject *su = (superobject *)self;
7533
7534    Py_VISIT(su->obj);
7535    Py_VISIT(su->type);
7536    Py_VISIT(su->obj_type);
7537
7538    return 0;
7539}
7540
7541PyTypeObject PySuper_Type = {
7542    PyVarObject_HEAD_INIT(&PyType_Type, 0)
7543    "super",                                    /* tp_name */
7544    sizeof(superobject),                        /* tp_basicsize */
7545    0,                                          /* tp_itemsize */
7546    /* methods */
7547    super_dealloc,                              /* tp_dealloc */
7548    0,                                          /* tp_print */
7549    0,                                          /* tp_getattr */
7550    0,                                          /* tp_setattr */
7551    0,                                          /* tp_reserved */
7552    super_repr,                                 /* tp_repr */
7553    0,                                          /* tp_as_number */
7554    0,                                          /* tp_as_sequence */
7555    0,                                          /* tp_as_mapping */
7556    0,                                          /* tp_hash */
7557    0,                                          /* tp_call */
7558    0,                                          /* tp_str */
7559    super_getattro,                             /* tp_getattro */
7560    0,                                          /* tp_setattro */
7561    0,                                          /* tp_as_buffer */
7562    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
7563        Py_TPFLAGS_BASETYPE,                    /* tp_flags */
7564    super_doc,                                  /* tp_doc */
7565    super_traverse,                             /* tp_traverse */
7566    0,                                          /* tp_clear */
7567    0,                                          /* tp_richcompare */
7568    0,                                          /* tp_weaklistoffset */
7569    0,                                          /* tp_iter */
7570    0,                                          /* tp_iternext */
7571    0,                                          /* tp_methods */
7572    super_members,                              /* tp_members */
7573    0,                                          /* tp_getset */
7574    0,                                          /* tp_base */
7575    0,                                          /* tp_dict */
7576    super_descr_get,                            /* tp_descr_get */
7577    0,                                          /* tp_descr_set */
7578    0,                                          /* tp_dictoffset */
7579    super_init,                                 /* tp_init */
7580    PyType_GenericAlloc,                        /* tp_alloc */
7581    PyType_GenericNew,                          /* tp_new */
7582    PyObject_GC_Del,                            /* tp_free */
7583};
7584