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