ยปCore Development>Code coverage>Objects/typeobject.c

Python code coverage for Objects/typeobject.c

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