Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(151134)

Delta Between Two Patch Sets: Objects/typeobject.c

Issue 23722: During metaclass.__init__, super() of the constructed class does not work
Left Patch Set: Created 4 years, 8 months ago
Right Patch Set: Created 3 years ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
LEFTRIGHT
1 /* Type object implementation */ 1 /* Type object implementation */
2 2
3 #include "Python.h" 3 #include "Python.h"
4 #include "frameobject.h" 4 #include "frameobject.h"
5 #include "structmember.h" 5 #include "structmember.h"
6 6
7 #include <ctype.h> 7 #include <ctype.h>
8 8
9 9
10 /* Support type attribute cache */ 10 /* Support type attribute cache */
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
46 46
47 /* alphabetical order */ 47 /* alphabetical order */
48 _Py_IDENTIFIER(__abstractmethods__); 48 _Py_IDENTIFIER(__abstractmethods__);
49 _Py_IDENTIFIER(__class__); 49 _Py_IDENTIFIER(__class__);
50 _Py_IDENTIFIER(__delitem__); 50 _Py_IDENTIFIER(__delitem__);
51 _Py_IDENTIFIER(__dict__); 51 _Py_IDENTIFIER(__dict__);
52 _Py_IDENTIFIER(__doc__); 52 _Py_IDENTIFIER(__doc__);
53 _Py_IDENTIFIER(__getattribute__); 53 _Py_IDENTIFIER(__getattribute__);
54 _Py_IDENTIFIER(__getitem__); 54 _Py_IDENTIFIER(__getitem__);
55 _Py_IDENTIFIER(__hash__); 55 _Py_IDENTIFIER(__hash__);
56 _Py_IDENTIFIER(__init_subclass__);
56 _Py_IDENTIFIER(__len__); 57 _Py_IDENTIFIER(__len__);
57 _Py_IDENTIFIER(__module__); 58 _Py_IDENTIFIER(__module__);
58 _Py_IDENTIFIER(__name__); 59 _Py_IDENTIFIER(__name__);
59 _Py_IDENTIFIER(__new__); 60 _Py_IDENTIFIER(__new__);
61 _Py_IDENTIFIER(__set_name__);
60 _Py_IDENTIFIER(__setitem__); 62 _Py_IDENTIFIER(__setitem__);
61 _Py_IDENTIFIER(builtins); 63 _Py_IDENTIFIER(builtins);
62 64
63 static PyObject * 65 static PyObject *
64 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds); 66 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
65 67
66 static void 68 static void
67 clear_slotdefs(void); 69 clear_slotdefs(void);
68 70
69 /* 71 /*
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
130 return doc; 132 return doc;
131 } 133 }
132 return internal_doc; 134 return internal_doc;
133 } 135 }
134 136
135 PyObject * 137 PyObject *
136 _PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc) 138 _PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc)
137 { 139 {
138 const char *doc = _PyType_DocWithoutSignature(name, internal_doc); 140 const char *doc = _PyType_DocWithoutSignature(name, internal_doc);
139 141
140 if (!doc) { 142 if (!doc || *doc == '\0') {
141 Py_INCREF(Py_None); 143 Py_INCREF(Py_None);
142 return Py_None; 144 return Py_None;
143 } 145 }
144 146
145 return PyUnicode_FromString(doc); 147 return PyUnicode_FromString(doc);
146 } 148 }
147 149
148 PyObject * 150 PyObject *
149 _PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_d oc) 151 _PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_d oc)
150 { 152 {
(...skipping 157 matching lines...) Expand 10 before | Expand all | Expand 10 after
308 type->tp_version_tag = next_version_tag++; 310 type->tp_version_tag = next_version_tag++;
309 /* for stress-testing: next_version_tag &= 0xFF; */ 311 /* for stress-testing: next_version_tag &= 0xFF; */
310 312
311 if (type->tp_version_tag == 0) { 313 if (type->tp_version_tag == 0) {
312 /* wrap-around or just starting Python - clear the whole 314 /* wrap-around or just starting Python - clear the whole
313 cache by filling names with references to Py_None. 315 cache by filling names with references to Py_None.
314 Values are also set to NULL for added protection, as they 316 Values are also set to NULL for added protection, as they
315 are borrowed reference */ 317 are borrowed reference */
316 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { 318 for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
317 method_cache[i].value = NULL; 319 method_cache[i].value = NULL;
318 Py_XDECREF(method_cache[i].name);
319 method_cache[i].name = Py_None;
320 Py_INCREF(Py_None); 320 Py_INCREF(Py_None);
321 Py_XSETREF(method_cache[i].name, Py_None);
321 } 322 }
322 /* mark all version tags as invalid */ 323 /* mark all version tags as invalid */
323 PyType_Modified(&PyBaseObject_Type); 324 PyType_Modified(&PyBaseObject_Type);
324 return 1; 325 return 1;
325 } 326 }
326 bases = type->tp_bases; 327 bases = type->tp_bases;
327 n = PyTuple_GET_SIZE(bases); 328 n = PyTuple_GET_SIZE(bases);
328 for (i = 0; i < n; i++) { 329 for (i = 0; i < n; i++) {
329 PyObject *b = PyTuple_GET_ITEM(bases, i); 330 PyObject *b = PyTuple_GET_ITEM(bases, i);
330 assert(PyType_Check(b)); 331 assert(PyType_Check(b));
(...skipping 64 matching lines...) Expand 10 before | Expand all | Expand 10 after
395 return et->ht_qualname; 396 return et->ht_qualname;
396 } 397 }
397 else { 398 else {
398 return type_name(type, context); 399 return type_name(type, context);
399 } 400 }
400 } 401 }
401 402
402 static int 403 static int
403 type_set_name(PyTypeObject *type, PyObject *value, void *context) 404 type_set_name(PyTypeObject *type, PyObject *value, void *context)
404 { 405 {
405 PyHeapTypeObject* et; 406 const char *tp_name;
406 char *tp_name; 407 Py_ssize_t name_size;
407 PyObject *tmp;
408 408
409 if (!check_set_special_type_attr(type, value, "__name__")) 409 if (!check_set_special_type_attr(type, value, "__name__"))
410 return -1; 410 return -1;
411 if (!PyUnicode_Check(value)) { 411 if (!PyUnicode_Check(value)) {
412 PyErr_Format(PyExc_TypeError, 412 PyErr_Format(PyExc_TypeError,
413 "can only assign string to %s.__name__, not '%s'", 413 "can only assign string to %s.__name__, not '%s'",
414 type->tp_name, Py_TYPE(value)->tp_name); 414 type->tp_name, Py_TYPE(value)->tp_name);
415 return -1; 415 return -1;
416 } 416 }
417 417
418 /* Check absence of null characters */ 418 tp_name = PyUnicode_AsUTF8AndSize(value, &name_size);
419 tmp = PyUnicode_FromStringAndSize("\0", 1);
420 if (tmp == NULL)
421 return -1;
422 if (PyUnicode_Contains(value, tmp) != 0) {
423 Py_DECREF(tmp);
424 PyErr_Format(PyExc_ValueError,
425 "__name__ must not contain null bytes");
426 return -1;
427 }
428 Py_DECREF(tmp);
429
430 tp_name = _PyUnicode_AsString(value);
431 if (tp_name == NULL) 419 if (tp_name == NULL)
432 return -1; 420 return -1;
433 421 if (strlen(tp_name) != (size_t)name_size) {
434 et = (PyHeapTypeObject*)type; 422 PyErr_SetString(PyExc_ValueError,
435 423 "type name must not contain null characters");
424 return -1;
425 }
426
427 type->tp_name = tp_name;
436 Py_INCREF(value); 428 Py_INCREF(value);
437 429 Py_SETREF(((PyHeapTypeObject*)type)->ht_name, value);
438 /* Wait until et is a sane state before Py_DECREF'ing the old et->ht_name
439 value. (Bug #16447.) */
440 tmp = et->ht_name;
441 et->ht_name = value;
442
443 type->tp_name = tp_name;
444 Py_DECREF(tmp);
445 430
446 return 0; 431 return 0;
447 } 432 }
448 433
449 static int 434 static int
450 type_set_qualname(PyTypeObject *type, PyObject *value, void *context) 435 type_set_qualname(PyTypeObject *type, PyObject *value, void *context)
451 { 436 {
452 PyHeapTypeObject* et; 437 PyHeapTypeObject* et;
453 438
454 if (!check_set_special_type_attr(type, value, "__qualname__")) 439 if (!check_set_special_type_attr(type, value, "__qualname__"))
455 return -1; 440 return -1;
456 if (!PyUnicode_Check(value)) { 441 if (!PyUnicode_Check(value)) {
457 PyErr_Format(PyExc_TypeError, 442 PyErr_Format(PyExc_TypeError,
458 "can only assign string to %s.__qualname__, not '%s'", 443 "can only assign string to %s.__qualname__, not '%s'",
459 type->tp_name, Py_TYPE(value)->tp_name); 444 type->tp_name, Py_TYPE(value)->tp_name);
460 return -1; 445 return -1;
461 } 446 }
462 447
463 et = (PyHeapTypeObject*)type; 448 et = (PyHeapTypeObject*)type;
464 Py_INCREF(value); 449 Py_INCREF(value);
465 Py_DECREF(et->ht_qualname); 450 Py_SETREF(et->ht_qualname, value);
466 et->ht_qualname = value;
467 return 0; 451 return 0;
468 } 452 }
469 453
470 static PyObject * 454 static PyObject *
471 type_module(PyTypeObject *type, void *context) 455 type_module(PyTypeObject *type, void *context)
472 { 456 {
473 char *s; 457 PyObject *mod;
474 458
475 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { 459 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
476 PyObject *mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__); 460 mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__);
477 if (!mod) { 461 if (mod == NULL) {
478 PyErr_Format(PyExc_AttributeError, "__module__"); 462 PyErr_Format(PyExc_AttributeError, "__module__");
479 return 0; 463 return NULL;
480 } 464 }
481 Py_XINCREF(mod); 465 Py_INCREF(mod);
482 return mod;
483 } 466 }
484 else { 467 else {
485 PyObject *name; 468 const char *s = strrchr(type->tp_name, '.');
486 s = strrchr(type->tp_name, '.'); 469 if (s != NULL) {
487 if (s != NULL) 470 mod = PyUnicode_FromStringAndSize(
488 return PyUnicode_FromStringAndSize(
489 type->tp_name, (Py_ssize_t)(s - type->tp_name)); 471 type->tp_name, (Py_ssize_t)(s - type->tp_name));
490 name = _PyUnicode_FromId(&PyId_builtins); 472 if (mod != NULL)
491 Py_XINCREF(name); 473 PyUnicode_InternInPlace(&mod);
492 return name; 474 }
493 } 475 else {
476 mod = _PyUnicode_FromId(&PyId_builtins);
477 Py_XINCREF(mod);
478 }
479 }
480 return mod;
494 } 481 }
495 482
496 static int 483 static int
497 type_set_module(PyTypeObject *type, PyObject *value, void *context) 484 type_set_module(PyTypeObject *type, PyObject *value, void *context)
498 { 485 {
499 if (!check_set_special_type_attr(type, value, "__module__")) 486 if (!check_set_special_type_attr(type, value, "__module__"))
500 return -1; 487 return -1;
501 488
502 PyType_Modified(type); 489 PyType_Modified(type);
503 490
504 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value); 491 return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value);
505 } 492 }
506 493
507 static PyObject * 494 static PyObject *
508 type_abstractmethods(PyTypeObject *type, void *context) 495 type_abstractmethods(PyTypeObject *type, void *context)
509 { 496 {
510 PyObject *mod = NULL; 497 PyObject *mod = NULL;
511 /* type itself has an __abstractmethods__ descriptor (this). Don't return 498 /* type itself has an __abstractmethods__ descriptor (this). Don't return
512 that. */ 499 that. */
513 if (type != &PyType_Type) 500 if (type != &PyType_Type)
514 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__); 501 mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__);
515 if (!mod) { 502 if (!mod) {
516 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__); 503 PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__);
517 if (message) 504 if (message)
518 PyErr_SetObject(PyExc_AttributeError, message); 505 PyErr_SetObject(PyExc_AttributeError, message);
519 return NULL; 506 return NULL;
520 } 507 }
521 Py_XINCREF(mod); 508 Py_INCREF(mod);
522 return mod; 509 return mod;
523 } 510 }
524 511
525 static int 512 static int
526 type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context) 513 type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
527 { 514 {
528 /* __abstractmethods__ should only be set once on a type, in 515 /* __abstractmethods__ should only be set once on a type, in
529 abc.ABCMeta.__new__, so this function doesn't do anything 516 abc.ABCMeta.__new__, so this function doesn't do anything
530 special to update subclasses. 517 special to update subclasses.
531 */ 518 */
(...skipping 26 matching lines...) Expand all
558 545
559 static PyObject * 546 static PyObject *
560 type_get_bases(PyTypeObject *type, void *context) 547 type_get_bases(PyTypeObject *type, void *context)
561 { 548 {
562 Py_INCREF(type->tp_bases); 549 Py_INCREF(type->tp_bases);
563 return type->tp_bases; 550 return type->tp_bases;
564 } 551 }
565 552
566 static PyTypeObject *best_base(PyObject *); 553 static PyTypeObject *best_base(PyObject *);
567 static int mro_internal(PyTypeObject *, PyObject **); 554 static int mro_internal(PyTypeObject *, PyObject **);
568 Py_LOCAL_INLINE(int) type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *); 555 static int type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *);
569 static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *); 556 static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, const char *);
570 static int add_subclass(PyTypeObject*, PyTypeObject*); 557 static int add_subclass(PyTypeObject*, PyTypeObject*);
571 static int add_all_subclasses(PyTypeObject *type, PyObject *bases); 558 static int add_all_subclasses(PyTypeObject *type, PyObject *bases);
572 static void remove_subclass(PyTypeObject *, PyTypeObject *); 559 static void remove_subclass(PyTypeObject *, PyTypeObject *);
573 static void remove_all_subclasses(PyTypeObject *type, PyObject *bases); 560 static void remove_all_subclasses(PyTypeObject *type, PyObject *bases);
574 static void update_all_slots(PyTypeObject *); 561 static void update_all_slots(PyTypeObject *);
575 562
576 typedef int (*update_callback)(PyTypeObject *, void *); 563 typedef int (*update_callback)(PyTypeObject *, void *);
577 static int update_subclasses(PyTypeObject *type, PyObject *name, 564 static int update_subclasses(PyTypeObject *type, PyObject *name,
578 update_callback callback, void *data); 565 update_callback callback, void *data);
579 static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, 566 static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
(...skipping 289 matching lines...) Expand 10 before | Expand all | Expand 10 after
869 else if (!PyUnicode_Check(mod)) { 856 else if (!PyUnicode_Check(mod)) {
870 Py_DECREF(mod); 857 Py_DECREF(mod);
871 mod = NULL; 858 mod = NULL;
872 } 859 }
873 name = type_qualname(type, NULL); 860 name = type_qualname(type, NULL);
874 if (name == NULL) { 861 if (name == NULL) {
875 Py_XDECREF(mod); 862 Py_XDECREF(mod);
876 return NULL; 863 return NULL;
877 } 864 }
878 865
879 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins)) 866 if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
880 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name); 867 rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
881 else 868 else
882 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name); 869 rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
883 870
884 Py_XDECREF(mod); 871 Py_XDECREF(mod);
885 Py_DECREF(name); 872 Py_DECREF(name);
886 return rtn; 873 return rtn;
887 } 874 }
888 875
889 static PyObject * 876 static PyObject *
890 type_call(PyTypeObject *type, PyObject *args, PyObject *kwds) 877 type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
891 { 878 {
892 PyObject *obj; 879 PyObject *obj;
893 880
894 if (type->tp_new == NULL) { 881 if (type->tp_new == NULL) {
895 PyErr_Format(PyExc_TypeError, 882 PyErr_Format(PyExc_TypeError,
896 "cannot create '%.100s' instances", 883 "cannot create '%.100s' instances",
897 type->tp_name); 884 type->tp_name);
898 return NULL; 885 return NULL;
899 } 886 }
900 887
901 #ifdef Py_DEBUG 888 #ifdef Py_DEBUG
902 /* type_call() must not be called with an exception set, 889 /* type_call() must not be called with an exception set,
903 because it may clear it (directly or indirectly) and so the 890 because it may clear it (directly or indirectly) and so the
904 caller looses its exception */ 891 caller loses its exception */
905 assert(!PyErr_Occurred()); 892 assert(!PyErr_Occurred());
906 #endif 893 #endif
907 894
908 obj = type->tp_new(type, args, kwds); 895 obj = type->tp_new(type, args, kwds);
909 if (obj != NULL) { 896 obj = _Py_CheckFunctionResult((PyObject*)type, obj, NULL);
910 /* Ugly exception: when the call was type(something), 897 if (obj == NULL)
911 don't call tp_init on the result. */ 898 return NULL;
912 if (type == &PyType_Type && 899
913 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && 900 /* Ugly exception: when the call was type(something),
914 (kwds == NULL || 901 don't call tp_init on the result. */
915 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) 902 if (type == &PyType_Type &&
916 return obj; 903 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
917 /* If the returned object is not an instance of type, 904 (kwds == NULL ||
918 it won't be initialized. */ 905 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
919 if (!PyType_IsSubtype(Py_TYPE(obj), type)) 906 return obj;
920 return obj; 907
921 type = Py_TYPE(obj); 908 /* If the returned object is not an instance of type,
922 if (type->tp_init != NULL) { 909 it won't be initialized. */
923 int res = type->tp_init(obj, args, kwds); 910 if (!PyType_IsSubtype(Py_TYPE(obj), type))
924 if (res < 0) { 911 return obj;
925 Py_DECREF(obj); 912
926 obj = NULL; 913 type = Py_TYPE(obj);
927 } 914 if (type->tp_init != NULL) {
915 int res = type->tp_init(obj, args, kwds);
916 if (res < 0) {
917 assert(PyErr_Occurred());
918 Py_DECREF(obj);
919 obj = NULL;
920 }
921 else {
922 assert(!PyErr_Occurred());
928 } 923 }
929 } 924 }
930 return obj; 925 return obj;
931 } 926 }
932 927
933 PyObject * 928 PyObject *
934 PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) 929 PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
935 { 930 {
936 PyObject *obj; 931 PyObject *obj;
937 const size_t size = _PyObject_VAR_SIZE(type, nitems+1); 932 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
(...skipping 196 matching lines...) Expand 10 before | Expand all | Expand 10 after
1134 /* We get here only if the type has GC */ 1129 /* We get here only if the type has GC */
1135 1130
1136 /* UnTrack and re-Track around the trashcan macro, alas */ 1131 /* UnTrack and re-Track around the trashcan macro, alas */
1137 /* See explanation at end of function for full disclosure */ 1132 /* See explanation at end of function for full disclosure */
1138 PyObject_GC_UnTrack(self); 1133 PyObject_GC_UnTrack(self);
1139 ++_PyTrash_delete_nesting; 1134 ++_PyTrash_delete_nesting;
1140 ++ tstate->trash_delete_nesting; 1135 ++ tstate->trash_delete_nesting;
1141 Py_TRASHCAN_SAFE_BEGIN(self); 1136 Py_TRASHCAN_SAFE_BEGIN(self);
1142 --_PyTrash_delete_nesting; 1137 --_PyTrash_delete_nesting;
1143 -- tstate->trash_delete_nesting; 1138 -- tstate->trash_delete_nesting;
1144 /* DO NOT restore GC tracking at this point. weakref callbacks
1145 * (if any, and whether directly here or indirectly in something we
1146 * call) may trigger GC, and if self is tracked at that point, it
1147 * will look like trash to GC and GC will try to delete self again.
1148 */
1149 1139
1150 /* Find the nearest base with a different tp_dealloc */ 1140 /* Find the nearest base with a different tp_dealloc */
1151 base = type; 1141 base = type;
1152 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) { 1142 while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
1153 base = base->tp_base; 1143 base = base->tp_base;
1154 assert(base); 1144 assert(base);
1155 } 1145 }
1156 1146
1157 has_finalizer = type->tp_finalize || type->tp_del; 1147 has_finalizer = type->tp_finalize || type->tp_del;
1158 1148
1159 /* Maybe call finalizer; exit early if resurrected */ 1149 if (type->tp_finalize) {
1160 if (has_finalizer)
1161 _PyObject_GC_TRACK(self); 1150 _PyObject_GC_TRACK(self);
1162
1163 if (type->tp_finalize) {
1164 if (PyObject_CallFinalizerFromDealloc(self) < 0) { 1151 if (PyObject_CallFinalizerFromDealloc(self) < 0) {
1165 /* Resurrected */ 1152 /* Resurrected */
1166 goto endlabel; 1153 goto endlabel;
1167 } 1154 }
1168 } 1155 _PyObject_GC_UNTRACK(self);
1169 /* If we added a weaklist, we clear it. Do this *before* calling 1156 }
1170 tp_del, clearing slots, or clearing the instance dict. */ 1157 /*
1158 If we added a weaklist, we clear it. Do this *before* calling tp_del,
1159 clearing slots, or clearing the instance dict.
1160
1161 GC tracking must be off at this point. weakref callbacks (if any, and
1162 whether directly here or indirectly in something we call) may trigger GC,
1163 and if self is tracked at that point, it will look like trash to GC and GC
1164 will try to delete self again.
1165 */
1171 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) 1166 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
1172 PyObject_ClearWeakRefs(self); 1167 PyObject_ClearWeakRefs(self);
1173 1168
1174 if (type->tp_del) { 1169 if (type->tp_del) {
1170 _PyObject_GC_TRACK(self);
1175 type->tp_del(self); 1171 type->tp_del(self);
1176 if (self->ob_refcnt > 0) { 1172 if (self->ob_refcnt > 0) {
1177 /* Resurrected */ 1173 /* Resurrected */
1178 goto endlabel; 1174 goto endlabel;
1179 } 1175 }
1176 _PyObject_GC_UNTRACK(self);
1180 } 1177 }
1181 if (has_finalizer) { 1178 if (has_finalizer) {
1182 _PyObject_GC_UNTRACK(self);
1183 /* New weakrefs could be created during the finalizer call. 1179 /* New weakrefs could be created during the finalizer call.
1184 If this occurs, clear them out without calling their 1180 If this occurs, clear them out without calling their
1185 finalizers since they might rely on part of the object 1181 finalizers since they might rely on part of the object
1186 being finalized that has already been destroyed. */ 1182 being finalized that has already been destroyed. */
1187 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { 1183 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
1188 /* Modeled after GET_WEAKREFS_LISTPTR() */ 1184 /* Modeled after GET_WEAKREFS_LISTPTR() */
1189 PyWeakReference **list = (PyWeakReference **) \ 1185 PyWeakReference **list = (PyWeakReference **) \
1190 PyObject_GET_WEAKREFS_LISTPTR(self); 1186 PyObject_GET_WEAKREFS_LISTPTR(self);
1191 while (*list) 1187 while (*list)
1192 _PyWeakref_ClearRef(*list); 1188 _PyWeakref_ClearRef(*list);
(...skipping 141 matching lines...) Expand 10 before | Expand all | Expand 10 after
1334 compiled in debug mode) before the trashcan level manipulations 1330 compiled in debug mode) before the trashcan level manipulations
1335 were added. For more discussion, see SF patches 581742, 575073 1331 were added. For more discussion, see SF patches 581742, 575073
1336 and bug 574207. 1332 and bug 574207.
1337 */ 1333 */
1338 } 1334 }
1339 1335
1340 static PyTypeObject *solid_base(PyTypeObject *type); 1336 static PyTypeObject *solid_base(PyTypeObject *type);
1341 1337
1342 /* type test with subclassing support */ 1338 /* type test with subclassing support */
1343 1339
1344 Py_LOCAL_INLINE(int) 1340 static int
1345 type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b) 1341 type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
1346 { 1342 {
1347 do { 1343 do {
1348 if (a == b) 1344 if (a == b)
1349 return 1; 1345 return 1;
1350 a = a->tp_base; 1346 a = a->tp_base;
1351 } while (a != NULL); 1347 } while (a != NULL);
1352 1348
1353 return (b == &PyBaseObject_Type); 1349 return (b == &PyBaseObject_Type);
1354 } 1350 }
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
1422 _PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid) 1418 _PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
1423 { 1419 {
1424 return lookup_maybe(self, attrid); 1420 return lookup_maybe(self, attrid);
1425 } 1421 }
1426 1422
1427 /* A variation of PyObject_CallMethod that uses lookup_method() 1423 /* A variation of PyObject_CallMethod that uses lookup_method()
1428 instead of PyObject_GetAttrString(). This uses the same convention 1424 instead of PyObject_GetAttrString(). This uses the same convention
1429 as lookup_method to cache the interned name string object. */ 1425 as lookup_method to cache the interned name string object. */
1430 1426
1431 static PyObject * 1427 static PyObject *
1432 call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...) 1428 call_method(PyObject *o, _Py_Identifier *nameid, const char *format, ...)
1433 { 1429 {
1434 va_list va; 1430 va_list va;
1435 PyObject *args, *func = 0, *retval; 1431 PyObject *func = NULL, *retval;
1436 va_start(va, format);
1437 1432
1438 func = lookup_maybe(o, nameid); 1433 func = lookup_maybe(o, nameid);
1439 if (func == NULL) { 1434 if (func == NULL) {
1440 va_end(va);
1441 if (!PyErr_Occurred()) 1435 if (!PyErr_Occurred())
1442 PyErr_SetObject(PyExc_AttributeError, nameid->object); 1436 PyErr_SetObject(PyExc_AttributeError, nameid->object);
1443 return NULL; 1437 return NULL;
1444 } 1438 }
1445 1439
1446 if (format && *format) 1440 if (format && *format) {
1441 PyObject *args;
1442
1443 va_start(va, format);
1447 args = Py_VaBuildValue(format, va); 1444 args = Py_VaBuildValue(format, va);
1448 else 1445 va_end(va);
1449 args = PyTuple_New(0); 1446
1450 1447 if (args == NULL) {
1451 va_end(va); 1448 Py_DECREF(func);
1452 1449 return NULL;
1453 if (args == NULL) 1450 }
1454 return NULL; 1451 assert(PyTuple_Check(args));
1455 1452
1456 assert(PyTuple_Check(args)); 1453 retval = PyObject_Call(func, args, NULL);
1457 retval = PyObject_Call(func, args, NULL); 1454 Py_DECREF(args);
1458 1455 }
1459 Py_DECREF(args); 1456 else {
1457 retval = _PyObject_CallNoArg(func);
1458 }
1459
1460 Py_DECREF(func); 1460 Py_DECREF(func);
1461 1461
1462 return retval; 1462 return retval;
1463 } 1463 }
1464 1464
1465 /* Clone of call_method() that returns NotImplemented when the lookup fails. */ 1465 /* Clone of call_method() that returns NotImplemented when the lookup fails. */
1466 1466
1467 static PyObject * 1467 static PyObject *
1468 call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...) 1468 call_maybe(PyObject *o, _Py_Identifier *nameid, const char *format, ...)
1469 { 1469 {
1470 va_list va; 1470 va_list va;
1471 PyObject *args, *func = 0, *retval; 1471 PyObject *func = NULL, *retval;
1472 va_start(va, format);
1473 1472
1474 func = lookup_maybe(o, nameid); 1473 func = lookup_maybe(o, nameid);
1475 if (func == NULL) { 1474 if (func == NULL) {
1476 va_end(va);
1477 if (!PyErr_Occurred()) 1475 if (!PyErr_Occurred())
1478 Py_RETURN_NOTIMPLEMENTED; 1476 Py_RETURN_NOTIMPLEMENTED;
1479 return NULL; 1477 return NULL;
1480 } 1478 }
1481 1479
1482 if (format && *format) 1480 if (format && *format) {
1481 PyObject *args;
1482
1483 va_start(va, format);
1483 args = Py_VaBuildValue(format, va); 1484 args = Py_VaBuildValue(format, va);
1484 else 1485 va_end(va);
1485 args = PyTuple_New(0); 1486
1486 1487 if (args == NULL) {
1487 va_end(va); 1488 Py_DECREF(func);
1488 1489 return NULL;
1489 if (args == NULL) 1490 }
1490 return NULL; 1491 assert(PyTuple_Check(args));
1491 1492
1492 assert(PyTuple_Check(args)); 1493 retval = PyObject_Call(func, args, NULL);
1493 retval = PyObject_Call(func, args, NULL); 1494 Py_DECREF(args);
1494 1495 }
1495 Py_DECREF(args); 1496 else {
1497 retval = _PyObject_CallNoArg(func);
1498 }
1499
1496 Py_DECREF(func); 1500 Py_DECREF(func);
1497 1501
1498 return retval; 1502 return retval;
1499 } 1503 }
1500 1504
1501 /* 1505 /*
1502 Method resolution order algorithm C3 described in 1506 Method resolution order algorithm C3 described in
1503 "A Monotonic Superclass Linearization for Dylan", 1507 "A Monotonic Superclass Linearization for Dylan",
1504 by Kim Barrett, Bob Cassel, Paul Haahr, 1508 by Kim Barrett, Bob Cassel, Paul Haahr,
1505 David A. Moon, Keith Playford, and P. Tucker Withington. 1509 David A. Moon, Keith Playford, and P. Tucker Withington.
1506 (OOPSLA 1996) 1510 (OOPSLA 1996)
1507 1511
1508 Some notes about the rules implied by C3: 1512 Some notes about the rules implied by C3:
1509 1513
1510 No duplicate bases. 1514 No duplicate bases.
1511 It isn't legal to repeat a class in a list of base classes. 1515 It isn't legal to repeat a class in a list of base classes.
1512 1516
1513 The next three properties are the 3 constraints in "C3". 1517 The next three properties are the 3 constraints in "C3".
1514 1518
1515 Local precendece order. 1519 Local precedence order.
1516 If A precedes B in C's MRO, then A will precede B in the MRO of all 1520 If A precedes B in C's MRO, then A will precede B in the MRO of all
1517 subclasses of C. 1521 subclasses of C.
1518 1522
1519 Monotonicity. 1523 Monotonicity.
1520 The MRO of a class must be an extension without reordering of the 1524 The MRO of a class must be an extension without reordering of the
1521 MRO of each of its superclasses. 1525 MRO of each of its superclasses.
1522 1526
1523 Extended Precedence Graph (EPG). 1527 Extended Precedence Graph (EPG).
1524 Linearization is consistent if there is a path in the EPG from 1528 Linearization is consistent if there is a path in the EPG from
1525 each class to all its successors in the linearization. See 1529 each class to all its successors in the linearization. See
(...skipping 11 matching lines...) Expand all
1537 } 1541 }
1538 return 0; 1542 return 0;
1539 } 1543 }
1540 1544
1541 static PyObject * 1545 static PyObject *
1542 class_name(PyObject *cls) 1546 class_name(PyObject *cls)
1543 { 1547 {
1544 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__); 1548 PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__);
1545 if (name == NULL) { 1549 if (name == NULL) {
1546 PyErr_Clear(); 1550 PyErr_Clear();
1547 Py_XDECREF(name);
1548 name = PyObject_Repr(cls); 1551 name = PyObject_Repr(cls);
1549 } 1552 }
1550 if (name == NULL) 1553 if (name == NULL)
1551 return NULL; 1554 return NULL;
1552 if (!PyUnicode_Check(name)) { 1555 if (!PyUnicode_Check(name)) {
1553 Py_DECREF(name); 1556 Py_DECREF(name);
1554 return NULL; 1557 return NULL;
1555 } 1558 }
1556 return name; 1559 return name;
1557 } 1560 }
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
1616 } 1619 }
1617 n = PyDict_Size(set); 1620 n = PyDict_Size(set);
1618 1621
1619 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ 1622 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1620 consistent method resolution\norder (MRO) for bases"); 1623 consistent method resolution\norder (MRO) for bases");
1621 i = 0; 1624 i = 0;
1622 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { 1625 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
1623 PyObject *name = class_name(k); 1626 PyObject *name = class_name(k);
1624 char *name_str; 1627 char *name_str;
1625 if (name != NULL) { 1628 if (name != NULL) {
1626 name_str = _PyUnicode_AsString(name); 1629 name_str = PyUnicode_AsUTF8(name);
1627 if (name_str == NULL) 1630 if (name_str == NULL)
1628 name_str = "?"; 1631 name_str = "?";
1629 } else 1632 } else
1630 name_str = "?"; 1633 name_str = "?";
1631 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str); 1634 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str);
1632 Py_XDECREF(name); 1635 Py_XDECREF(name);
1633 if (--n && (size_t)(off+1) < sizeof(buf)) { 1636 if (--n && (size_t)(off+1) < sizeof(buf)) {
1634 buf[off++] = ','; 1637 buf[off++] = ',';
1635 buf[off] = '\0'; 1638 buf[off] = '\0';
1636 } 1639 }
(...skipping 321 matching lines...) Expand 10 before | Expand all | Expand 10 after
1958 PyErr_SetString( 1961 PyErr_SetString(
1959 PyExc_TypeError, 1962 PyExc_TypeError,
1960 "bases must be types"); 1963 "bases must be types");
1961 return NULL; 1964 return NULL;
1962 } 1965 }
1963 base_i = (PyTypeObject *)base_proto; 1966 base_i = (PyTypeObject *)base_proto;
1964 if (base_i->tp_dict == NULL) { 1967 if (base_i->tp_dict == NULL) {
1965 if (PyType_Ready(base_i) < 0) 1968 if (PyType_Ready(base_i) < 0)
1966 return NULL; 1969 return NULL;
1967 } 1970 }
1971 if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
1972 PyErr_Format(PyExc_TypeError,
1973 "type '%.100s' is not an acceptable base type",
1974 base_i->tp_name);
1975 return NULL;
1976 }
1968 candidate = solid_base(base_i); 1977 candidate = solid_base(base_i);
1969 if (winner == NULL) { 1978 if (winner == NULL) {
1970 winner = candidate; 1979 winner = candidate;
1971 base = base_i; 1980 base = base_i;
1972 } 1981 }
1973 else if (PyType_IsSubtype(winner, candidate)) 1982 else if (PyType_IsSubtype(winner, candidate))
1974 ; 1983 ;
1975 else if (PyType_IsSubtype(candidate, winner)) { 1984 else if (PyType_IsSubtype(candidate, winner)) {
1976 winner = candidate; 1985 winner = candidate;
1977 base = base_i; 1986 base = base_i;
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
2025 if (extra_ivars(type, base)) 2034 if (extra_ivars(type, base))
2026 return type; 2035 return type;
2027 else 2036 else
2028 return base; 2037 return base;
2029 } 2038 }
2030 2039
2031 static void object_dealloc(PyObject *); 2040 static void object_dealloc(PyObject *);
2032 static int object_init(PyObject *, PyObject *, PyObject *); 2041 static int object_init(PyObject *, PyObject *, PyObject *);
2033 static int update_slot(PyTypeObject *, PyObject *); 2042 static int update_slot(PyTypeObject *, PyObject *);
2034 static void fixup_slot_dispatchers(PyTypeObject *); 2043 static void fixup_slot_dispatchers(PyTypeObject *);
2044 static int set_names(PyTypeObject *);
2045 static int init_subclass(PyTypeObject *, PyObject *);
2035 2046
2036 /* 2047 /*
2037 * Helpers for __dict__ descriptor. We don't want to expose the dicts 2048 * Helpers for __dict__ descriptor. We don't want to expose the dicts
2038 * inherited from various builtin types. The builtin base usually provides 2049 * inherited from various builtin types. The builtin base usually provides
2039 * its own __dict__ descriptor, so we use that when we can. 2050 * its own __dict__ descriptor, so we use that when we can.
2040 */ 2051 */
2041 static PyTypeObject * 2052 static PyTypeObject *
2042 get_builtin_base_with_dict(PyTypeObject *type) 2053 get_builtin_base_with_dict(PyTypeObject *type)
2043 { 2054 {
2044 while (type->tp_base != NULL) { 2055 while (type->tp_base != NULL) {
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
2089 return NULL; 2100 return NULL;
2090 } 2101 }
2091 return func(descr, obj, (PyObject *)(Py_TYPE(obj))); 2102 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
2092 } 2103 }
2093 return PyObject_GenericGetDict(obj, context); 2104 return PyObject_GenericGetDict(obj, context);
2094 } 2105 }
2095 2106
2096 static int 2107 static int
2097 subtype_setdict(PyObject *obj, PyObject *value, void *context) 2108 subtype_setdict(PyObject *obj, PyObject *value, void *context)
2098 { 2109 {
2099 PyObject *dict, **dictptr; 2110 PyObject **dictptr;
2100 PyTypeObject *base; 2111 PyTypeObject *base;
2101 2112
2102 base = get_builtin_base_with_dict(Py_TYPE(obj)); 2113 base = get_builtin_base_with_dict(Py_TYPE(obj));
2103 if (base != NULL) { 2114 if (base != NULL) {
2104 descrsetfunc func; 2115 descrsetfunc func;
2105 PyObject *descr = get_dict_descriptor(base); 2116 PyObject *descr = get_dict_descriptor(base);
2106 if (descr == NULL) { 2117 if (descr == NULL) {
2107 raise_dict_descr_error(obj); 2118 raise_dict_descr_error(obj);
2108 return -1; 2119 return -1;
2109 } 2120 }
(...skipping 10 matching lines...) Expand all
2120 PyErr_SetString(PyExc_AttributeError, 2131 PyErr_SetString(PyExc_AttributeError,
2121 "This object has no __dict__"); 2132 "This object has no __dict__");
2122 return -1; 2133 return -1;
2123 } 2134 }
2124 if (value != NULL && !PyDict_Check(value)) { 2135 if (value != NULL && !PyDict_Check(value)) {
2125 PyErr_Format(PyExc_TypeError, 2136 PyErr_Format(PyExc_TypeError,
2126 "__dict__ must be set to a dictionary, " 2137 "__dict__ must be set to a dictionary, "
2127 "not a '%.200s'", Py_TYPE(value)->tp_name); 2138 "not a '%.200s'", Py_TYPE(value)->tp_name);
2128 return -1; 2139 return -1;
2129 } 2140 }
2130 dict = *dictptr;
2131 Py_XINCREF(value); 2141 Py_XINCREF(value);
2132 *dictptr = value; 2142 Py_XSETREF(*dictptr, value);
2133 Py_XDECREF(dict);
2134 return 0; 2143 return 0;
2135 } 2144 }
2136 2145
2137 static PyObject * 2146 static PyObject *
2138 subtype_getweakref(PyObject *obj, void *context) 2147 subtype_getweakref(PyObject *obj, void *context)
2139 { 2148 {
2140 PyObject **weaklistptr; 2149 PyObject **weaklistptr;
2141 PyObject *result; 2150 PyObject *result;
2142 2151
2143 if (Py_TYPE(obj)->tp_weaklistoffset == 0) { 2152 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
2202 object_init(PyObject *self, PyObject *args, PyObject *kwds); 2211 object_init(PyObject *self, PyObject *args, PyObject *kwds);
2203 2212
2204 static int 2213 static int
2205 type_init(PyObject *cls, PyObject *args, PyObject *kwds) 2214 type_init(PyObject *cls, PyObject *args, PyObject *kwds)
2206 { 2215 {
2207 int res; 2216 int res;
2208 2217
2209 assert(args != NULL && PyTuple_Check(args)); 2218 assert(args != NULL && PyTuple_Check(args));
2210 assert(kwds == NULL || PyDict_Check(kwds)); 2219 assert(kwds == NULL || PyDict_Check(kwds));
2211 2220
2212 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) { 2221 if (kwds != NULL && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
2222 PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
2213 PyErr_SetString(PyExc_TypeError, 2223 PyErr_SetString(PyExc_TypeError,
2214 "type.__init__() takes no keyword arguments"); 2224 "type.__init__() takes no keyword arguments");
2215 return -1; 2225 return -1;
2216 } 2226 }
2217 2227
2218 if (args != NULL && PyTuple_Check(args) && 2228 if (args != NULL && PyTuple_Check(args) &&
2219 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) { 2229 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
2220 PyErr_SetString(PyExc_TypeError, 2230 PyErr_SetString(PyExc_TypeError,
2221 "type.__init__() takes 1 or 3 arguments"); 2231 "type.__init__() takes 1 or 3 arguments");
2222 return -1; 2232 return -1;
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
2269 "of the metaclasses of all its bases"); 2279 "of the metaclasses of all its bases");
2270 return NULL; 2280 return NULL;
2271 } 2281 }
2272 return winner; 2282 return winner;
2273 } 2283 }
2274 2284
2275 static PyObject * 2285 static PyObject *
2276 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) 2286 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
2277 { 2287 {
2278 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL; 2288 PyObject *name, *bases = NULL, *orig_dict, *dict = NULL;
2279 static char *kwlist[] = {"name", "bases", "dict", 0};
2280 PyObject *qualname, *slots = NULL, *tmp, *newslots, *cell; 2289 PyObject *qualname, *slots = NULL, *tmp, *newslots, *cell;
2281 PyTypeObject *type = NULL, *base, *tmptype, *winner; 2290 PyTypeObject *type = NULL, *base, *tmptype, *winner;
2282 PyHeapTypeObject *et; 2291 PyHeapTypeObject *et;
2283 PyMemberDef *mp; 2292 PyMemberDef *mp;
2284 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak; 2293 Py_ssize_t i, nbases, nslots, slotoffset, name_size;
2285 int j, may_add_dict, may_add_weak; 2294 int j, may_add_dict, may_add_weak, add_dict, add_weak;
2286 _Py_IDENTIFIER(__qualname__); 2295 _Py_IDENTIFIER(__qualname__);
2287 _Py_IDENTIFIER(__slots__); 2296 _Py_IDENTIFIER(__slots__);
2288 _Py_IDENTIFIER(__cell__); 2297 _Py_IDENTIFIER(__classcell__);
2289 2298
2290 assert(args != NULL && PyTuple_Check(args)); 2299 assert(args != NULL && PyTuple_Check(args));
2291 assert(kwds == NULL || PyDict_Check(kwds)); 2300 assert(kwds == NULL || PyDict_Check(kwds));
2292 2301
2293 /* Special case: type(x) should return x->ob_type */ 2302 /* Special case: type(x) should return x->ob_type */
2294 { 2303 /* We only want type itself to accept the one-argument form (#27157)
2304 Note: We don't call PyType_CheckExact as that also allows subclasses */
2305 if (metatype == &PyType_Type) {
2295 const Py_ssize_t nargs = PyTuple_GET_SIZE(args); 2306 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
2296 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); 2307 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
2297 2308
2298 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { 2309 if (nargs == 1 && nkwds == 0) {
2299 PyObject *x = PyTuple_GET_ITEM(args, 0); 2310 PyObject *x = PyTuple_GET_ITEM(args, 0);
2300 Py_INCREF(Py_TYPE(x)); 2311 Py_INCREF(Py_TYPE(x));
2301 return (PyObject *) Py_TYPE(x); 2312 return (PyObject *) Py_TYPE(x);
2302 } 2313 }
2303 2314
2304 /* SF bug 475327 -- if that didn't trigger, we need 3 2315 /* SF bug 475327 -- if that didn't trigger, we need 3
2305 arguments. but PyArg_ParseTupleAndKeywords below may give 2316 arguments. but PyArg_ParseTupleAndKeywords below may give
2306 a msg saying type() needs exactly 3. */ 2317 a msg saying type() needs exactly 3. */
2307 if (nargs + nkwds != 3) { 2318 if (nargs != 3) {
2308 PyErr_SetString(PyExc_TypeError, 2319 PyErr_SetString(PyExc_TypeError,
2309 "type() takes 1 or 3 arguments"); 2320 "type() takes 1 or 3 arguments");
2310 return NULL; 2321 return NULL;
2311 } 2322 }
2312 } 2323 }
2313 2324
2314 /* Check arguments: (name, bases, dict) */ 2325 /* Check arguments: (name, bases, dict) */
2315 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, 2326 if (!PyArg_ParseTuple(args, "UO!O!:type.__new__", &name, &PyTuple_Type,
2316 &name, 2327 &bases, &PyDict_Type, &orig_dict))
2317 &PyTuple_Type, &bases,
2318 &PyDict_Type, &orig_dict))
2319 return NULL; 2328 return NULL;
2320 2329
2321 /* Determine the proper metatype to deal with this: */ 2330 /* Determine the proper metatype to deal with this: */
2322 winner = _PyType_CalculateMetaclass(metatype, bases); 2331 winner = _PyType_CalculateMetaclass(metatype, bases);
2323 if (winner == NULL) { 2332 if (winner == NULL) {
2324 return NULL; 2333 return NULL;
2325 } 2334 }
2326 2335
2327 if (winner != metatype) { 2336 if (winner != metatype) {
2328 if (winner->tp_new != type_new) /* Pass it to the winner */ 2337 if (winner->tp_new != type_new) /* Pass it to the winner */
2329 return winner->tp_new(winner, args, kwds); 2338 return winner->tp_new(winner, args, kwds);
2330 metatype = winner; 2339 metatype = winner;
2331 } 2340 }
2332 2341
2333 /* Adjust for empty tuple bases */ 2342 /* Adjust for empty tuple bases */
2334 nbases = PyTuple_GET_SIZE(bases); 2343 nbases = PyTuple_GET_SIZE(bases);
2335 if (nbases == 0) { 2344 if (nbases == 0) {
2336 bases = PyTuple_Pack(1, &PyBaseObject_Type); 2345 bases = PyTuple_Pack(1, &PyBaseObject_Type);
2337 if (bases == NULL) 2346 if (bases == NULL)
2338 goto error; 2347 goto error;
2339 nbases = 1; 2348 nbases = 1;
2340 } 2349 }
2341 else 2350 else
2342 Py_INCREF(bases); 2351 Py_INCREF(bases);
2343 2352
2344 /* Calculate best base, and check that all bases are type objects */ 2353 /* Calculate best base, and check that all bases are type objects */
2345 base = best_base(bases); 2354 base = best_base(bases);
2346 if (base == NULL) { 2355 if (base == NULL) {
2347 goto error;
2348 }
2349 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2350 PyErr_Format(PyExc_TypeError,
2351 "type '%.100s' is not an acceptable base type",
2352 base->tp_name);
2353 goto error; 2356 goto error;
2354 } 2357 }
2355 2358
2356 dict = PyDict_Copy(orig_dict); 2359 dict = PyDict_Copy(orig_dict);
2357 if (dict == NULL) 2360 if (dict == NULL)
2358 goto error; 2361 goto error;
2359 2362
2360 /* Check for a __slots__ sequence variable in dict, and count it */ 2363 /* Check for a __slots__ sequence variable in dict, and count it */
2361 slots = _PyDict_GetItemId(dict, &PyId___slots__); 2364 slots = _PyDict_GetItemId(dict, &PyId___slots__);
2362 nslots = 0; 2365 nslots = 0;
(...skipping 30 matching lines...) Expand all
2393 base->tp_name); 2396 base->tp_name);
2394 goto error; 2397 goto error;
2395 } 2398 }
2396 2399
2397 /* Check for valid slot names and two special cases */ 2400 /* Check for valid slot names and two special cases */
2398 for (i = 0; i < nslots; i++) { 2401 for (i = 0; i < nslots; i++) {
2399 PyObject *tmp = PyTuple_GET_ITEM(slots, i); 2402 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
2400 if (!valid_identifier(tmp)) 2403 if (!valid_identifier(tmp))
2401 goto error; 2404 goto error;
2402 assert(PyUnicode_Check(tmp)); 2405 assert(PyUnicode_Check(tmp));
2403 if (_PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) { 2406 if (_PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) {
2404 if (!may_add_dict || add_dict) { 2407 if (!may_add_dict || add_dict) {
2405 PyErr_SetString(PyExc_TypeError, 2408 PyErr_SetString(PyExc_TypeError,
2406 "__dict__ slot disallowed: " 2409 "__dict__ slot disallowed: "
2407 "we already got one"); 2410 "we already got one");
2408 goto error; 2411 goto error;
2409 } 2412 }
2410 add_dict++; 2413 add_dict++;
2411 } 2414 }
2412 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) { 2415 if (_PyUnicode_EqualToASCIIString(tmp, "__weakref__")) {
2413 if (!may_add_weak || add_weak) { 2416 if (!may_add_weak || add_weak) {
2414 PyErr_SetString(PyExc_TypeError, 2417 PyErr_SetString(PyExc_TypeError,
2415 "__weakref__ slot disallowed: " 2418 "__weakref__ slot disallowed: "
2416 "either we already got one, " 2419 "either we already got one, "
2417 "or __itemsize__ != 0"); 2420 "or __itemsize__ != 0");
2418 goto error; 2421 goto error;
2419 } 2422 }
2420 add_weak++; 2423 add_weak++;
2421 } 2424 }
2422 } 2425 }
2423 2426
2424 /* Copy slots into a list, mangle names and sort them. 2427 /* Copy slots into a list, mangle names and sort them.
2425 Sorted names are needed for __class__ assignment. 2428 Sorted names are needed for __class__ assignment.
2426 Convert them back to tuple at the end. 2429 Convert them back to tuple at the end.
2427 */ 2430 */
2428 newslots = PyList_New(nslots - add_dict - add_weak); 2431 newslots = PyList_New(nslots - add_dict - add_weak);
2429 if (newslots == NULL) 2432 if (newslots == NULL)
2430 goto error; 2433 goto error;
2431 for (i = j = 0; i < nslots; i++) { 2434 for (i = j = 0; i < nslots; i++) {
2432 tmp = PyTuple_GET_ITEM(slots, i); 2435 tmp = PyTuple_GET_ITEM(slots, i);
2433 if ((add_dict && 2436 if ((add_dict &&
2434 _PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) || 2437 _PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) ||
2435 (add_weak && 2438 (add_weak &&
2436 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0)) 2439 _PyUnicode_EqualToASCIIString(tmp, "__weakref__")))
2437 continue; 2440 continue;
2438 tmp =_Py_Mangle(name, tmp); 2441 tmp =_Py_Mangle(name, tmp);
2439 if (!tmp) { 2442 if (!tmp) {
2440 Py_DECREF(newslots); 2443 Py_DECREF(newslots);
2441 goto error; 2444 goto error;
2442 } 2445 }
2443 PyList_SET_ITEM(newslots, j, tmp); 2446 PyList_SET_ITEM(newslots, j, tmp);
2444 if (PyDict_GetItem(dict, tmp)) { 2447 if (PyDict_GetItem(dict, tmp)) {
2445 PyErr_Format(PyExc_ValueError, 2448 PyErr_Format(PyExc_ValueError,
2446 "%R in __slots__ conflicts with class variable", 2449 "%R in __slots__ conflicts with class variable",
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after
2500 et->ht_slots = slots; 2503 et->ht_slots = slots;
2501 slots = NULL; 2504 slots = NULL;
2502 2505
2503 /* Initialize tp_flags */ 2506 /* Initialize tp_flags */
2504 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | 2507 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
2505 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE; 2508 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE;
2506 if (base->tp_flags & Py_TPFLAGS_HAVE_GC) 2509 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
2507 type->tp_flags |= Py_TPFLAGS_HAVE_GC; 2510 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2508 2511
2509 /* Initialize essential fields */ 2512 /* Initialize essential fields */
2513 type->tp_as_async = &et->as_async;
2510 type->tp_as_number = &et->as_number; 2514 type->tp_as_number = &et->as_number;
2511 type->tp_as_sequence = &et->as_sequence; 2515 type->tp_as_sequence = &et->as_sequence;
2512 type->tp_as_mapping = &et->as_mapping; 2516 type->tp_as_mapping = &et->as_mapping;
2513 type->tp_as_buffer = &et->as_buffer; 2517 type->tp_as_buffer = &et->as_buffer;
2514 type->tp_name = _PyUnicode_AsString(name); 2518 type->tp_name = PyUnicode_AsUTF8AndSize(name, &name_size);
2515 if (!type->tp_name) 2519 if (!type->tp_name)
2516 goto error; 2520 goto error;
2521 if (strlen(type->tp_name) != (size_t)name_size) {
2522 PyErr_SetString(PyExc_ValueError,
2523 "type name must not contain null characters");
2524 goto error;
2525 }
2517 2526
2518 /* Set tp_base and tp_bases */ 2527 /* Set tp_base and tp_bases */
2519 type->tp_bases = bases; 2528 type->tp_bases = bases;
2520 bases = NULL; 2529 bases = NULL;
2521 Py_INCREF(base); 2530 Py_INCREF(base);
2522 type->tp_base = base; 2531 type->tp_base = base;
2523 2532
2524 /* Initialize tp_dict from passed-in dict */ 2533 /* Initialize tp_dict from passed-in dict */
2525 Py_INCREF(dict); 2534 Py_INCREF(dict);
2526 type->tp_dict = dict; 2535 type->tp_dict = dict;
(...skipping 18 matching lines...) Expand all
2545 if (qualname != NULL) { 2554 if (qualname != NULL) {
2546 if (!PyUnicode_Check(qualname)) { 2555 if (!PyUnicode_Check(qualname)) {
2547 PyErr_Format(PyExc_TypeError, 2556 PyErr_Format(PyExc_TypeError,
2548 "type __qualname__ must be a str, not %s", 2557 "type __qualname__ must be a str, not %s",
2549 Py_TYPE(qualname)->tp_name); 2558 Py_TYPE(qualname)->tp_name);
2550 goto error; 2559 goto error;
2551 } 2560 }
2552 } 2561 }
2553 et->ht_qualname = qualname ? qualname : et->ht_name; 2562 et->ht_qualname = qualname ? qualname : et->ht_name;
2554 Py_INCREF(et->ht_qualname); 2563 Py_INCREF(et->ht_qualname);
2555 if (qualname != NULL && PyDict_DelItem(dict, PyId___qualname__.object) < 0) 2564 if (qualname != NULL && _PyDict_DelItemId(dict, &PyId___qualname__) < 0)
2556 goto error; 2565 goto error;
2557 2566
2558 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there 2567 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
2559 and is a string. The __doc__ accessor will first look for tp_doc; 2568 and is a string. The __doc__ accessor will first look for tp_doc;
2560 if that fails, it will still look into __dict__. 2569 if that fails, it will still look into __dict__.
2561 */ 2570 */
2562 { 2571 {
2563 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__); 2572 PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__);
2564 if (doc != NULL && PyUnicode_Check(doc)) { 2573 if (doc != NULL && PyUnicode_Check(doc)) {
2565 Py_ssize_t len; 2574 Py_ssize_t len;
2566 char *doc_str; 2575 char *doc_str;
2567 char *tp_doc; 2576 char *tp_doc;
2568 2577
2569 doc_str = _PyUnicode_AsString(doc); 2578 doc_str = PyUnicode_AsUTF8(doc);
2570 if (doc_str == NULL) 2579 if (doc_str == NULL)
2571 goto error; 2580 goto error;
2572 /* Silently truncate the docstring if it contains null bytes. */ 2581 /* Silently truncate the docstring if it contains null bytes. */
2573 len = strlen(doc_str); 2582 len = strlen(doc_str);
2574 tp_doc = (char *)PyObject_MALLOC(len + 1); 2583 tp_doc = (char *)PyObject_MALLOC(len + 1);
2575 if (tp_doc == NULL) { 2584 if (tp_doc == NULL) {
2576 PyErr_NoMemory(); 2585 PyErr_NoMemory();
2577 goto error; 2586 goto error;
2578 } 2587 }
2579 memcpy(tp_doc, doc_str, len + 1); 2588 memcpy(tp_doc, doc_str, len + 1);
2580 type->tp_doc = tp_doc; 2589 type->tp_doc = tp_doc;
2581 } 2590 }
2582 } 2591 }
2583 2592
2584 /* Special-case __new__: if it's a plain function, 2593 /* Special-case __new__: if it's a plain function,
2585 make it a static function */ 2594 make it a static function */
2586 tmp = _PyDict_GetItemId(dict, &PyId___new__); 2595 tmp = _PyDict_GetItemId(dict, &PyId___new__);
2587 if (tmp != NULL && PyFunction_Check(tmp)) { 2596 if (tmp != NULL && PyFunction_Check(tmp)) {
2588 tmp = PyStaticMethod_New(tmp); 2597 tmp = PyStaticMethod_New(tmp);
2589 if (tmp == NULL) 2598 if (tmp == NULL)
2590 goto error; 2599 goto error;
2591 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) 2600 if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) {
2601 Py_DECREF(tmp);
2592 goto error; 2602 goto error;
2603 }
2604 Py_DECREF(tmp);
2605 }
2606
2607 /* Special-case __init_subclass__: if it's a plain function,
2608 make it a classmethod */
2609 tmp = _PyDict_GetItemId(dict, &PyId___init_subclass__);
2610 if (tmp != NULL && PyFunction_Check(tmp)) {
2611 tmp = PyClassMethod_New(tmp);
2612 if (tmp == NULL)
2613 goto error;
2614 if (_PyDict_SetItemId(dict, &PyId___init_subclass__, tmp) < 0) {
2615 Py_DECREF(tmp);
2616 goto error;
2617 }
2593 Py_DECREF(tmp); 2618 Py_DECREF(tmp);
2594 } 2619 }
2595 2620
2596 /* Add descriptors for custom slots from __slots__, or for __dict__ */ 2621 /* Add descriptors for custom slots from __slots__, or for __dict__ */
2597 mp = PyHeapType_GET_MEMBERS(et); 2622 mp = PyHeapType_GET_MEMBERS(et);
2598 slotoffset = base->tp_basicsize; 2623 slotoffset = base->tp_basicsize;
2599 if (et->ht_slots != NULL) { 2624 if (et->ht_slots != NULL) {
2600 for (i = 0; i < nslots; i++, mp++) { 2625 for (i = 0; i < nslots; i++, mp++) {
2601 mp->name = _PyUnicode_AsString( 2626 mp->name = PyUnicode_AsUTF8(
2602 PyTuple_GET_ITEM(et->ht_slots, i)); 2627 PyTuple_GET_ITEM(et->ht_slots, i));
2603 if (mp->name == NULL) 2628 if (mp->name == NULL)
2604 goto error; 2629 goto error;
2605 mp->type = T_OBJECT_EX; 2630 mp->type = T_OBJECT_EX;
2606 mp->offset = slotoffset; 2631 mp->offset = slotoffset;
2607 2632
2608 /* __dict__ and __weakref__ are already filtered out */ 2633 /* __dict__ and __weakref__ are already filtered out */
2609 assert(strcmp(mp->name, "__dict__") != 0); 2634 assert(strcmp(mp->name, "__dict__") != 0);
2610 assert(strcmp(mp->name, "__weakref__") != 0); 2635 assert(strcmp(mp->name, "__weakref__") != 0);
2611 2636
(...skipping 27 matching lines...) Expand all
2639 2664
2640 /* Special case some slots */ 2665 /* Special case some slots */
2641 if (type->tp_dictoffset != 0 || nslots > 0) { 2666 if (type->tp_dictoffset != 0 || nslots > 0) {
2642 if (base->tp_getattr == NULL && base->tp_getattro == NULL) 2667 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2643 type->tp_getattro = PyObject_GenericGetAttr; 2668 type->tp_getattro = PyObject_GenericGetAttr;
2644 if (base->tp_setattr == NULL && base->tp_setattro == NULL) 2669 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2645 type->tp_setattro = PyObject_GenericSetAttr; 2670 type->tp_setattro = PyObject_GenericSetAttr;
2646 } 2671 }
2647 type->tp_dealloc = subtype_dealloc; 2672 type->tp_dealloc = subtype_dealloc;
2648 2673
2649 /* Enable GC unless there are really no instance variables possible */ 2674 /* Enable GC unless this class is not adding new instance variables and
2650 if (!(type->tp_basicsize == sizeof(PyObject) && 2675 the base class did not use GC. */
2651 type->tp_itemsize == 0)) 2676 if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) ||
2677 type->tp_basicsize > base->tp_basicsize)
2652 type->tp_flags |= Py_TPFLAGS_HAVE_GC; 2678 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2653 2679
2654 /* Always override allocation strategy to use regular heap */ 2680 /* Always override allocation strategy to use regular heap */
2655 type->tp_alloc = PyType_GenericAlloc; 2681 type->tp_alloc = PyType_GenericAlloc;
2656 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { 2682 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
2657 type->tp_free = PyObject_GC_Del; 2683 type->tp_free = PyObject_GC_Del;
2658 type->tp_traverse = subtype_traverse; 2684 type->tp_traverse = subtype_traverse;
2659 type->tp_clear = subtype_clear; 2685 type->tp_clear = subtype_clear;
2660 } 2686 }
2661 else 2687 else
2662 type->tp_free = PyObject_Del; 2688 type->tp_free = PyObject_Del;
2663 2689
2664 /* store type in class' cell */ 2690 /* store type in class' cell if one is supplied */
2665 cell = _PyDict_GetItemId(dict, &PyId___cell__); 2691 cell = _PyDict_GetItemId(dict, &PyId___classcell__);
2666 if (cell != NULL && PyCell_Check(cell)) { 2692 if (cell != NULL) {
2693 /* At least one method requires a reference to its defining class */
2694 if (!PyCell_Check(cell)) {
2695 PyErr_Format(PyExc_TypeError,
2696 "__classcell__ must be a nonlocal cell, not %.200R",
2697 Py_TYPE(cell));
2698 goto error;
2699 }
2667 PyCell_Set(cell, (PyObject *) type); 2700 PyCell_Set(cell, (PyObject *) type);
2668 PyDict_DelItem(dict, PyId___cell__.object); 2701 _PyDict_DelItemId(dict, &PyId___classcell__);
2669 PyErr_Clear(); 2702 PyErr_Clear();
2670 } 2703 }
2671 2704
2672 /* Initialize the rest */ 2705 /* Initialize the rest */
2673 if (PyType_Ready(type) < 0) 2706 if (PyType_Ready(type) < 0)
2674 goto error; 2707 goto error;
2675 2708
2676 /* Put the proper slots in place */ 2709 /* Put the proper slots in place */
2677 fixup_slot_dispatchers(type); 2710 fixup_slot_dispatchers(type);
2678 2711
2679 if (type->tp_dictoffset) { 2712 if (type->tp_dictoffset) {
2680 et->ht_cached_keys = _PyDict_NewKeysForClass(); 2713 et->ht_cached_keys = _PyDict_NewKeysForClass();
2681 } 2714 }
2715
2716 if (set_names(type) < 0)
2717 goto error;
2718
2719 if (init_subclass(type, kwds) < 0)
2720 goto error;
2682 2721
2683 Py_DECREF(dict); 2722 Py_DECREF(dict);
2684 return (PyObject *)type; 2723 return (PyObject *)type;
2685 2724
2686 error: 2725 error:
2687 Py_XDECREF(dict); 2726 Py_XDECREF(dict);
2688 Py_XDECREF(bases); 2727 Py_XDECREF(bases);
2689 Py_XDECREF(slots); 2728 Py_XDECREF(slots);
2690 Py_XDECREF(type); 2729 Py_XDECREF(type);
2691 return NULL; 2730 return NULL;
2692 } 2731 }
2693 2732
2694 static short slotoffsets[] = { 2733 static const short slotoffsets[] = {
2695 -1, /* invalid slot */ 2734 -1, /* invalid slot */
2696 #include "typeslots.inc" 2735 #include "typeslots.inc"
2697 }; 2736 };
2698 2737
2699 PyObject * 2738 PyObject *
2700 PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases) 2739 PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
2701 { 2740 {
2702 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0); 2741 PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
2703 PyTypeObject *type, *base; 2742 PyTypeObject *type, *base;
2743 PyObject *modname;
2704 char *s; 2744 char *s;
2705 char *res_start = (char*)res; 2745 char *res_start = (char*)res;
2706 PyType_Slot *slot; 2746 PyType_Slot *slot;
2707 2747
2708 /* Set the type name and qualname */ 2748 /* Set the type name and qualname */
2709 s = strrchr(spec->name, '.'); 2749 s = strrchr(spec->name, '.');
2710 if (s == NULL) 2750 if (s == NULL)
2711 s = (char*)spec->name; 2751 s = (char*)spec->name;
2712 else 2752 else
2713 s++; 2753 s++;
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
2752 goto fail; 2792 goto fail;
2753 } 2793 }
2754 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { 2794 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
2755 PyErr_Format(PyExc_TypeError, 2795 PyErr_Format(PyExc_TypeError,
2756 "type '%.100s' is not an acceptable base type", 2796 "type '%.100s' is not an acceptable base type",
2757 base->tp_name); 2797 base->tp_name);
2758 goto fail; 2798 goto fail;
2759 } 2799 }
2760 2800
2761 /* Initialize essential fields */ 2801 /* Initialize essential fields */
2802 type->tp_as_async = &res->as_async;
2762 type->tp_as_number = &res->as_number; 2803 type->tp_as_number = &res->as_number;
2763 type->tp_as_sequence = &res->as_sequence; 2804 type->tp_as_sequence = &res->as_sequence;
2764 type->tp_as_mapping = &res->as_mapping; 2805 type->tp_as_mapping = &res->as_mapping;
2765 type->tp_as_buffer = &res->as_buffer; 2806 type->tp_as_buffer = &res->as_buffer;
2766 /* Set tp_base and tp_bases */ 2807 /* Set tp_base and tp_bases */
2767 type->tp_bases = bases; 2808 type->tp_bases = bases;
2768 bases = NULL; 2809 bases = NULL;
2769 Py_INCREF(base); 2810 Py_INCREF(base);
2770 type->tp_base = base; 2811 type->tp_base = base;
2771 2812
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
2806 2847
2807 if (PyType_Ready(type) < 0) 2848 if (PyType_Ready(type) < 0)
2808 goto fail; 2849 goto fail;
2809 2850
2810 if (type->tp_dictoffset) { 2851 if (type->tp_dictoffset) {
2811 res->ht_cached_keys = _PyDict_NewKeysForClass(); 2852 res->ht_cached_keys = _PyDict_NewKeysForClass();
2812 } 2853 }
2813 2854
2814 /* Set type.__module__ */ 2855 /* Set type.__module__ */
2815 s = strrchr(spec->name, '.'); 2856 s = strrchr(spec->name, '.');
2816 if (s != NULL) 2857 if (s != NULL) {
2817 _PyDict_SetItemId(type->tp_dict, &PyId___module__, 2858 int err;
2818 PyUnicode_FromStringAndSize( 2859 modname = PyUnicode_FromStringAndSize(
2819 spec->name, (Py_ssize_t)(s - spec->name))); 2860 spec->name, (Py_ssize_t)(s - spec->name));
2820 else { 2861 if (modname == NULL) {
2862 goto fail;
2863 }
2864 err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
2865 Py_DECREF(modname);
2866 if (err != 0)
2867 goto fail;
2868 } else {
2821 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, 2869 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
2822 "builtin type %.200s has no __module__ attribute", 2870 "builtin type %.200s has no __module__ attribute",
2823 spec->name)) 2871 spec->name))
2824 goto fail; 2872 goto fail;
2825 } 2873 }
2826 2874
2827 return (PyObject*)res; 2875 return (PyObject*)res;
2828 2876
2829 fail: 2877 fail:
2830 Py_DECREF(res); 2878 Py_DECREF(res);
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
2869 #if MCACHE_STATS 2917 #if MCACHE_STATS
2870 method_cache_hits++; 2918 method_cache_hits++;
2871 #endif 2919 #endif
2872 return method_cache[h].value; 2920 return method_cache[h].value;
2873 } 2921 }
2874 } 2922 }
2875 2923
2876 /* Look in tp_dict of types in MRO */ 2924 /* Look in tp_dict of types in MRO */
2877 mro = type->tp_mro; 2925 mro = type->tp_mro;
2878 2926
2879 /* If mro is NULL, the type is either not yet initialized 2927 if (mro == NULL) {
2880 by PyType_Ready(), or already cleared by type_clear(). 2928 if ((type->tp_flags & Py_TPFLAGS_READYING) == 0 &&
2881 Either way the safest thing to do is to return NULL. */ 2929 PyType_Ready(type) < 0) {
2882 if (mro == NULL) 2930 /* It's not ideal to clear the error condition,
2883 return NULL; 2931 but this function is documented as not setting
2932 an exception, and I don't want to change that.
2933 When PyType_Ready() can't proceed, it won't
2934 set the "ready" flag, so future attempts to ready
2935 the same type will call it again -- hopefully
2936 in a context that propagates the exception out.
2937 */
2938 PyErr_Clear();
2939 return NULL;
2940 }
2941 mro = type->tp_mro;
2942 if (mro == NULL) {
2943 return NULL;
2944 }
2945 }
2884 2946
2885 res = NULL; 2947 res = NULL;
2886 /* keep a strong reference to mro because type->tp_mro can be replaced 2948 /* keep a strong reference to mro because type->tp_mro can be replaced
2887 during PyDict_GetItem(dict, name) */ 2949 during PyDict_GetItem(dict, name) */
2888 Py_INCREF(mro); 2950 Py_INCREF(mro);
2889 assert(PyTuple_Check(mro)); 2951 assert(PyTuple_Check(mro));
2890 n = PyTuple_GET_SIZE(mro); 2952 n = PyTuple_GET_SIZE(mro);
2891 for (i = 0; i < n; i++) { 2953 for (i = 0; i < n; i++) {
2892 base = PyTuple_GET_ITEM(mro, i); 2954 base = PyTuple_GET_ITEM(mro, i);
2893 assert(PyType_Check(base)); 2955 assert(PyType_Check(base));
(...skipping 10 matching lines...) Expand all
2904 method_cache[h].version = type->tp_version_tag; 2966 method_cache[h].version = type->tp_version_tag;
2905 method_cache[h].value = res; /* borrowed */ 2967 method_cache[h].value = res; /* borrowed */
2906 Py_INCREF(name); 2968 Py_INCREF(name);
2907 assert(((PyASCIIObject *)(name))->hash != -1); 2969 assert(((PyASCIIObject *)(name))->hash != -1);
2908 #if MCACHE_STATS 2970 #if MCACHE_STATS
2909 if (method_cache[h].name != Py_None && method_cache[h].name != name) 2971 if (method_cache[h].name != Py_None && method_cache[h].name != name)
2910 method_cache_collisions++; 2972 method_cache_collisions++;
2911 else 2973 else
2912 method_cache_misses++; 2974 method_cache_misses++;
2913 #endif 2975 #endif
2914 Py_DECREF(method_cache[h].name); 2976 Py_SETREF(method_cache[h].name, name);
2915 method_cache[h].name = name;
2916 } 2977 }
2917 return res; 2978 return res;
2918 } 2979 }
2919 2980
2920 PyObject * 2981 PyObject *
2921 _PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name) 2982 _PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name)
2922 { 2983 {
2923 PyObject *oname; 2984 PyObject *oname;
2924 oname = _PyUnicode_FromId(name); /* borrowed */ 2985 oname = _PyUnicode_FromId(name); /* borrowed */
2925 if (oname == NULL) 2986 if (oname == NULL)
(...skipping 551 matching lines...) Expand 10 before | Expand all | Expand 10 after
3477 PyErr_Clear(); 3538 PyErr_Clear();
3478 else if (!PyUnicode_Check(mod)) { 3539 else if (!PyUnicode_Check(mod)) {
3479 Py_DECREF(mod); 3540 Py_DECREF(mod);
3480 mod = NULL; 3541 mod = NULL;
3481 } 3542 }
3482 name = type_qualname(type, NULL); 3543 name = type_qualname(type, NULL);
3483 if (name == NULL) { 3544 if (name == NULL) {
3484 Py_XDECREF(mod); 3545 Py_XDECREF(mod);
3485 return NULL; 3546 return NULL;
3486 } 3547 }
3487 if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins)) 3548 if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
3488 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self); 3549 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
3489 else 3550 else
3490 rtn = PyUnicode_FromFormat("<%s object at %p>", 3551 rtn = PyUnicode_FromFormat("<%s object at %p>",
3491 type->tp_name, self); 3552 type->tp_name, self);
3492 Py_XDECREF(mod); 3553 Py_XDECREF(mod);
3493 Py_DECREF(name); 3554 Py_DECREF(name);
3494 return rtn; 3555 return rtn;
3495 } 3556 }
3496 3557
3497 static PyObject * 3558 static PyObject *
(...skipping 100 matching lines...) Expand 10 before | Expand all | Expand 10 after
3598 slots_b = ((PyHeapTypeObject *)b)->ht_slots; 3659 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
3599 if (slots_a && slots_b) { 3660 if (slots_a && slots_b) {
3600 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1) 3661 if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
3601 return 0; 3662 return 0;
3602 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a); 3663 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
3603 } 3664 }
3604 return size == a->tp_basicsize && size == b->tp_basicsize; 3665 return size == a->tp_basicsize && size == b->tp_basicsize;
3605 } 3666 }
3606 3667
3607 static int 3668 static int
3608 compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr) 3669 compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr)
3609 { 3670 {
3610 PyTypeObject *newbase, *oldbase; 3671 PyTypeObject *newbase, *oldbase;
3611 3672
3612 if (newto->tp_free != oldto->tp_free) { 3673 if (newto->tp_free != oldto->tp_free) {
3613 PyErr_Format(PyExc_TypeError, 3674 PyErr_Format(PyExc_TypeError,
3614 "%s assignment: " 3675 "%s assignment: "
3615 "'%s' deallocator differs from '%s'", 3676 "'%s' deallocator differs from '%s'",
3616 attr, 3677 attr,
3617 newto->tp_name, 3678 newto->tp_name,
3618 oldto->tp_name); 3679 oldto->tp_name);
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
3660 "can't delete __class__ attribute"); 3721 "can't delete __class__ attribute");
3661 return -1; 3722 return -1;
3662 } 3723 }
3663 if (!PyType_Check(value)) { 3724 if (!PyType_Check(value)) {
3664 PyErr_Format(PyExc_TypeError, 3725 PyErr_Format(PyExc_TypeError,
3665 "__class__ must be set to a class, not '%s' object", 3726 "__class__ must be set to a class, not '%s' object",
3666 Py_TYPE(value)->tp_name); 3727 Py_TYPE(value)->tp_name);
3667 return -1; 3728 return -1;
3668 } 3729 }
3669 newto = (PyTypeObject *)value; 3730 newto = (PyTypeObject *)value;
3731 /* In versions of CPython prior to 3.5, the code in
3732 compatible_for_assignment was not set up to correctly check for memory
3733 layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just
3734 disallowed __class__ assignment in any case that wasn't HEAPTYPE ->
3735 HEAPTYPE.
3736
3737 During the 3.5 development cycle, we fixed the code in
3738 compatible_for_assignment to correctly check compatibility between
3739 arbitrary types, and started allowing __class__ assignment in all cases
3740 where the old and new types did in fact have compatible slots and
3741 memory layout (regardless of whether they were implemented as HEAPTYPEs
3742 or not).
3743
3744 Just before 3.5 was released, though, we discovered that this led to
3745 problems with immutable types like int, where the interpreter assumes
3746 they are immutable and interns some values. Formerly this wasn't a
3747 problem, because they really were immutable -- in particular, all the
3748 types where the interpreter applied this interning trick happened to
3749 also be statically allocated, so the old HEAPTYPE rules were
3750 "accidentally" stopping them from allowing __class__ assignment. But
3751 with the changes to __class__ assignment, we started allowing code like
3752
3753 class MyInt(int):
3754 ...
3755 # Modifies the type of *all* instances of 1 in the whole program,
3756 # including future instances (!), because the 1 object is interned.
3757 (1).__class__ = MyInt
3758
3759 (see https://bugs.python.org/issue24912).
3760
3761 In theory the proper fix would be to identify which classes rely on
3762 this invariant and somehow disallow __class__ assignment only for them,
3763 perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a
3764 "blacklisting" approach). But in practice, since this problem wasn't
3765 noticed late in the 3.5 RC cycle, we're taking the conservative
3766 approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used
3767 to have, plus a "whitelist". For now, the whitelist consists only of
3768 ModuleType subtypes, since those are the cases that motivated the patch
3769 in the first place -- see https://bugs.python.org/issue22986 -- and
3770 since module objects are mutable we can be sure that they are
3771 definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or*
3772 ModuleType subtype -> ModuleType subtype.
3773
3774 So far as we know, all the code beyond the following 'if' statement
3775 will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is
3776 needed only to protect that subset of non-HEAPTYPE classes for which
3777 the interpreter has baked in the assumption that all instances are
3778 truly immutable.
3779 */
3780 if (!(PyType_IsSubtype(newto, &PyModule_Type) &&
3781 PyType_IsSubtype(oldto, &PyModule_Type)) &&
3782 (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
3783 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) {
3784 PyErr_Format(PyExc_TypeError,
3785 "__class__ assignment only supported for heap types "
3786 "or ModuleType subclasses");
3787 return -1;
3788 }
3789
3670 if (compatible_for_assignment(oldto, newto, "__class__")) { 3790 if (compatible_for_assignment(oldto, newto, "__class__")) {
3671 if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE) 3791 if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3672 Py_INCREF(newto); 3792 Py_INCREF(newto);
3673 Py_TYPE(self) = newto; 3793 Py_TYPE(self) = newto;
3674 if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE) 3794 if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)
3675 Py_DECREF(oldto); 3795 Py_DECREF(oldto);
3676 return 0; 3796 return 0;
3677 } 3797 }
3678 else { 3798 else {
3679 return -1; 3799 return -1;
(...skipping 22 matching lines...) Expand all
3702 PyInterpreterState *interp = PyThreadState_GET()->interp; 3822 PyInterpreterState *interp = PyThreadState_GET()->interp;
3703 _Py_IDENTIFIER(copyreg); 3823 _Py_IDENTIFIER(copyreg);
3704 3824
3705 copyreg_str = _PyUnicode_FromId(&PyId_copyreg); 3825 copyreg_str = _PyUnicode_FromId(&PyId_copyreg);
3706 if (copyreg_str == NULL) { 3826 if (copyreg_str == NULL) {
3707 return NULL; 3827 return NULL;
3708 } 3828 }
3709 /* Try to fetch cached copy of copyreg from sys.modules first in an 3829 /* Try to fetch cached copy of copyreg from sys.modules first in an
3710 attempt to avoid the import overhead. Previously this was implemented 3830 attempt to avoid the import overhead. Previously this was implemented
3711 by storing a reference to the cached module in a static variable, but 3831 by storing a reference to the cached module in a static variable, but
3712 this broke when multiple embeded interpreters were in use (see issue 3832 this broke when multiple embedded interpreters were in use (see issue
3713 #17408 and #19088). */ 3833 #17408 and #19088). */
3714 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str); 3834 copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
3715 if (copyreg_module != NULL) { 3835 if (copyreg_module != NULL) {
3716 Py_INCREF(copyreg_module); 3836 Py_INCREF(copyreg_module);
3717 return copyreg_module; 3837 return copyreg_module;
3718 } 3838 }
3719 if (PyErr_Occurred()) { 3839 if (PyErr_Occurred()) {
3720 return NULL; 3840 return NULL;
3721 } 3841 }
3722 return PyImport_Import(copyreg_str); 3842 return PyImport_Import(copyreg_str);
3723 } 3843 }
3724 3844
3725 Py_LOCAL(PyObject *) 3845 static PyObject *
3726 _PyType_GetSlotNames(PyTypeObject *cls) 3846 _PyType_GetSlotNames(PyTypeObject *cls)
3727 { 3847 {
3728 PyObject *copyreg; 3848 PyObject *copyreg;
3729 PyObject *slotnames; 3849 PyObject *slotnames;
3730 _Py_IDENTIFIER(__slotnames__); 3850 _Py_IDENTIFIER(__slotnames__);
3731 _Py_IDENTIFIER(_slotnames); 3851 _Py_IDENTIFIER(_slotnames);
3732 3852
3733 assert(PyType_Check(cls)); 3853 assert(PyType_Check(cls));
3734 3854
3735 /* Get the slot names from the cache in the class if possible. */ 3855 /* Get the slot names from the cache in the class if possible. */
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
3768 if (slotnames != Py_None && !PyList_Check(slotnames)) { 3888 if (slotnames != Py_None && !PyList_Check(slotnames)) {
3769 PyErr_SetString(PyExc_TypeError, 3889 PyErr_SetString(PyExc_TypeError,
3770 "copyreg._slotnames didn't return a list or None"); 3890 "copyreg._slotnames didn't return a list or None");
3771 Py_DECREF(slotnames); 3891 Py_DECREF(slotnames);
3772 return NULL; 3892 return NULL;
3773 } 3893 }
3774 3894
3775 return slotnames; 3895 return slotnames;
3776 } 3896 }
3777 3897
3778 Py_LOCAL(PyObject *) 3898 static PyObject *
3779 _PyObject_GetState(PyObject *obj) 3899 _PyObject_GetState(PyObject *obj, int required)
3780 { 3900 {
3781 PyObject *state; 3901 PyObject *state;
3782 PyObject *getstate; 3902 PyObject *getstate;
3783 _Py_IDENTIFIER(__getstate__); 3903 _Py_IDENTIFIER(__getstate__);
3784 3904
3785 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__); 3905 getstate = _PyObject_GetAttrId(obj, &PyId___getstate__);
3786 if (getstate == NULL) { 3906 if (getstate == NULL) {
3787 PyObject *slotnames; 3907 PyObject *slotnames;
3788 3908
3789 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { 3909 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3790 return NULL; 3910 return NULL;
3791 } 3911 }
3792 PyErr_Clear(); 3912 PyErr_Clear();
3913
3914 if (required && obj->ob_type->tp_itemsize) {
3915 PyErr_Format(PyExc_TypeError,
3916 "can't pickle %.200s objects",
3917 Py_TYPE(obj)->tp_name);
3918 return NULL;
3919 }
3793 3920
3794 { 3921 {
3795 PyObject **dict; 3922 PyObject **dict;
3796 dict = _PyObject_GetDictPtr(obj); 3923 dict = _PyObject_GetDictPtr(obj);
3797 /* It is possible that the object's dict is not initialized 3924 /* It is possible that the object's dict is not initialized
3798 yet. In this case, we will return None for the state. 3925 yet. In this case, we will return None for the state.
3799 We also return None if the dict is empty to make the behavior 3926 We also return None if the dict is empty to make the behavior
3800 consistent regardless whether the dict was initialized or not. 3927 consistent regardless whether the dict was initialized or not.
3801 This make unit testing easier. */ 3928 This make unit testing easier. */
3802 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) { 3929 if (dict != NULL && *dict != NULL && PyDict_Size(*dict) > 0) {
3803 state = *dict; 3930 state = *dict;
3804 } 3931 }
3805 else { 3932 else {
3806 state = Py_None; 3933 state = Py_None;
3807 } 3934 }
3808 Py_INCREF(state); 3935 Py_INCREF(state);
3809 } 3936 }
3810 3937
3811 slotnames = _PyType_GetSlotNames(Py_TYPE(obj)); 3938 slotnames = _PyType_GetSlotNames(Py_TYPE(obj));
3812 if (slotnames == NULL) { 3939 if (slotnames == NULL) {
3813 Py_DECREF(state); 3940 Py_DECREF(state);
3814 return NULL; 3941 return NULL;
3815 } 3942 }
3816 3943
3817 assert(slotnames == Py_None || PyList_Check(slotnames)); 3944 assert(slotnames == Py_None || PyList_Check(slotnames));
3945 if (required) {
3946 Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize;
3947 if (obj->ob_type->tp_dictoffset)
3948 basicsize += sizeof(PyObject *);
3949 if (obj->ob_type->tp_weaklistoffset)
3950 basicsize += sizeof(PyObject *);
3951 if (slotnames != Py_None)
3952 basicsize += sizeof(PyObject *) * Py_SIZE(slotnames);
3953 if (obj->ob_type->tp_basicsize > basicsize) {
3954 Py_DECREF(slotnames);
3955 Py_DECREF(state);
3956 PyErr_Format(PyExc_TypeError,
3957 "can't pickle %.200s objects",
3958 Py_TYPE(obj)->tp_name);
3959 return NULL;
3960 }
3961 }
3962
3818 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) { 3963 if (slotnames != Py_None && Py_SIZE(slotnames) > 0) {
3819 PyObject *slots; 3964 PyObject *slots;
3820 Py_ssize_t slotnames_size, i; 3965 Py_ssize_t slotnames_size, i;
3821 3966
3822 slots = PyDict_New(); 3967 slots = PyDict_New();
3823 if (slots == NULL) { 3968 if (slots == NULL) {
3824 Py_DECREF(slotnames); 3969 Py_DECREF(slotnames);
3825 Py_DECREF(state); 3970 Py_DECREF(state);
3826 return NULL; 3971 return NULL;
3827 } 3972 }
3828 3973
3829 slotnames_size = Py_SIZE(slotnames); 3974 slotnames_size = Py_SIZE(slotnames);
3830 for (i = 0; i < slotnames_size; i++) { 3975 for (i = 0; i < slotnames_size; i++) {
3831 PyObject *name, *value; 3976 PyObject *name, *value;
3832 3977
3833 name = PyList_GET_ITEM(slotnames, i); 3978 name = PyList_GET_ITEM(slotnames, i);
3979 Py_INCREF(name);
3834 value = PyObject_GetAttr(obj, name); 3980 value = PyObject_GetAttr(obj, name);
3835 if (value == NULL) { 3981 if (value == NULL) {
3982 Py_DECREF(name);
3836 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { 3983 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
3837 goto error; 3984 goto error;
3838 } 3985 }
3839 /* It is not an error if the attribute is not present. */ 3986 /* It is not an error if the attribute is not present. */
3840 PyErr_Clear(); 3987 PyErr_Clear();
3841 } 3988 }
3842 else { 3989 else {
3843 int err = PyDict_SetItem(slots, name, value); 3990 int err = PyDict_SetItem(slots, name, value);
3991 Py_DECREF(name);
3844 Py_DECREF(value); 3992 Py_DECREF(value);
3845 if (err) { 3993 if (err) {
3846 goto error; 3994 goto error;
3847 } 3995 }
3848 } 3996 }
3849 3997
3850 /* The list is stored on the class so it may mutates while we 3998 /* The list is stored on the class so it may mutate while we
3851 iterate over it */ 3999 iterate over it */
3852 if (slotnames_size != Py_SIZE(slotnames)) { 4000 if (slotnames_size != Py_SIZE(slotnames)) {
3853 PyErr_Format(PyExc_RuntimeError, 4001 PyErr_Format(PyExc_RuntimeError,
3854 "__slotsname__ changed size during iteration"); 4002 "__slotsname__ changed size during iteration");
3855 goto error; 4003 goto error;
3856 } 4004 }
3857 4005
3858 /* We handle errors within the loop here. */ 4006 /* We handle errors within the loop here. */
3859 if (0) { 4007 if (0) {
3860 error: 4008 error:
3861 Py_DECREF(slotnames); 4009 Py_DECREF(slotnames);
3862 Py_DECREF(slots); 4010 Py_DECREF(slots);
3863 Py_DECREF(state); 4011 Py_DECREF(state);
3864 return NULL; 4012 return NULL;
3865 } 4013 }
3866 } 4014 }
3867 4015
3868 /* If we found some slot attributes, pack them in a tuple along 4016 /* If we found some slot attributes, pack them in a tuple along
3869 the orginal attribute dictionary. */ 4017 the original attribute dictionary. */
3870 if (PyDict_Size(slots) > 0) { 4018 if (PyDict_Size(slots) > 0) {
3871 PyObject *state2; 4019 PyObject *state2;
3872 4020
3873 state2 = PyTuple_Pack(2, state, slots); 4021 state2 = PyTuple_Pack(2, state, slots);
3874 Py_DECREF(state); 4022 Py_DECREF(state);
3875 if (state2 == NULL) { 4023 if (state2 == NULL) {
3876 Py_DECREF(slotnames); 4024 Py_DECREF(slotnames);
3877 Py_DECREF(slots); 4025 Py_DECREF(slots);
3878 return NULL; 4026 return NULL;
3879 } 4027 }
3880 state = state2; 4028 state = state2;
3881 } 4029 }
3882 Py_DECREF(slots); 4030 Py_DECREF(slots);
3883 } 4031 }
3884 Py_DECREF(slotnames); 4032 Py_DECREF(slotnames);
3885 } 4033 }
3886 else { /* getstate != NULL */ 4034 else { /* getstate != NULL */
3887 state = PyObject_CallObject(getstate, NULL); 4035 state = PyObject_CallObject(getstate, NULL);
3888 Py_DECREF(getstate); 4036 Py_DECREF(getstate);
3889 if (state == NULL) 4037 if (state == NULL)
3890 return NULL; 4038 return NULL;
3891 } 4039 }
3892 4040
3893 return state; 4041 return state;
3894 } 4042 }
3895 4043
3896 Py_LOCAL(int) 4044 static int
3897 _PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs) 4045 _PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs)
3898 { 4046 {
3899 PyObject *getnewargs, *getnewargs_ex; 4047 PyObject *getnewargs, *getnewargs_ex;
3900 _Py_IDENTIFIER(__getnewargs_ex__); 4048 _Py_IDENTIFIER(__getnewargs_ex__);
3901 _Py_IDENTIFIER(__getnewargs__); 4049 _Py_IDENTIFIER(__getnewargs__);
3902 4050
3903 if (args == NULL || kwargs == NULL) { 4051 if (args == NULL || kwargs == NULL) {
3904 PyErr_BadInternalCall(); 4052 PyErr_BadInternalCall();
3905 return -1; 4053 return -1;
3906 } 4054 }
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
3974 Py_CLEAR(*args); 4122 Py_CLEAR(*args);
3975 return -1; 4123 return -1;
3976 } 4124 }
3977 *kwargs = NULL; 4125 *kwargs = NULL;
3978 return 0; 4126 return 0;
3979 } else if (PyErr_Occurred()) { 4127 } else if (PyErr_Occurred()) {
3980 return -1; 4128 return -1;
3981 } 4129 }
3982 4130
3983 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may 4131 /* The object does not have __getnewargs_ex__ and __getnewargs__. This may
3984 means __new__ does not takes any arguments on this object, or that the 4132 mean __new__ does not takes any arguments on this object, or that the
3985 object does not implement the reduce protocol for pickling or 4133 object does not implement the reduce protocol for pickling or
3986 copying. */ 4134 copying. */
3987 *args = NULL; 4135 *args = NULL;
3988 *kwargs = NULL; 4136 *kwargs = NULL;
3989 return 0; 4137 return 0;
3990 } 4138 }
3991 4139
3992 Py_LOCAL(int) 4140 static int
3993 _PyObject_GetItemsIter(PyObject *obj, PyObject **listitems, 4141 _PyObject_GetItemsIter(PyObject *obj, PyObject **listitems,
3994 PyObject **dictitems) 4142 PyObject **dictitems)
3995 { 4143 {
3996 if (listitems == NULL || dictitems == NULL) { 4144 if (listitems == NULL || dictitems == NULL) {
3997 PyErr_BadInternalCall(); 4145 PyErr_BadInternalCall();
3998 return -1; 4146 return -1;
3999 } 4147 }
4000 4148
4001 if (!PyList_Check(obj)) { 4149 if (!PyList_Check(obj)) {
4002 *listitems = Py_None; 4150 *listitems = Py_None;
(...skipping 25 matching lines...) Expand all
4028 return -1; 4176 return -1;
4029 } 4177 }
4030 } 4178 }
4031 4179
4032 assert(*listitems != NULL && *dictitems != NULL); 4180 assert(*listitems != NULL && *dictitems != NULL);
4033 4181
4034 return 0; 4182 return 0;
4035 } 4183 }
4036 4184
4037 static PyObject * 4185 static PyObject *
4038 reduce_newobj(PyObject *obj, int proto) 4186 reduce_newobj(PyObject *obj)
4039 { 4187 {
4040 PyObject *args = NULL, *kwargs = NULL; 4188 PyObject *args = NULL, *kwargs = NULL;
4041 PyObject *copyreg; 4189 PyObject *copyreg;
4042 PyObject *newobj, *newargs, *state, *listitems, *dictitems; 4190 PyObject *newobj, *newargs, *state, *listitems, *dictitems;
4043 PyObject *result; 4191 PyObject *result;
4044 4192 int hasargs;
4193
4194 if (Py_TYPE(obj)->tp_new == NULL) {
4195 PyErr_Format(PyExc_TypeError,
4196 "can't pickle %.200s objects",
4197 Py_TYPE(obj)->tp_name);
4198 return NULL;
4199 }
4045 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0) 4200 if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0)
4046 return NULL; 4201 return NULL;
4047 4202
4048 if (args == NULL) {
4049 args = PyTuple_New(0);
4050 if (args == NULL) {
4051 Py_XDECREF(kwargs);
4052 return NULL;
4053 }
4054 }
4055 copyreg = import_copyreg(); 4203 copyreg = import_copyreg();
4056 if (copyreg == NULL) { 4204 if (copyreg == NULL) {
4057 Py_DECREF(args); 4205 Py_XDECREF(args);
4058 Py_XDECREF(kwargs); 4206 Py_XDECREF(kwargs);
4059 return NULL; 4207 return NULL;
4060 } 4208 }
4209 hasargs = (args != NULL);
4061 if (kwargs == NULL || PyDict_Size(kwargs) == 0) { 4210 if (kwargs == NULL || PyDict_Size(kwargs) == 0) {
4062 _Py_IDENTIFIER(__newobj__); 4211 _Py_IDENTIFIER(__newobj__);
4063 PyObject *cls; 4212 PyObject *cls;
4064 Py_ssize_t i, n; 4213 Py_ssize_t i, n;
4065 4214
4066 Py_XDECREF(kwargs); 4215 Py_XDECREF(kwargs);
4067 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__); 4216 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__);
4068 Py_DECREF(copyreg); 4217 Py_DECREF(copyreg);
4069 if (newobj == NULL) { 4218 if (newobj == NULL) {
4070 Py_DECREF(args); 4219 Py_XDECREF(args);
4071 return NULL; 4220 return NULL;
4072 } 4221 }
4073 n = PyTuple_GET_SIZE(args); 4222 n = args ? PyTuple_GET_SIZE(args) : 0;
4074 newargs = PyTuple_New(n+1); 4223 newargs = PyTuple_New(n+1);
4075 if (newargs == NULL) { 4224 if (newargs == NULL) {
4076 Py_DECREF(args); 4225 Py_XDECREF(args);
4077 Py_DECREF(newobj); 4226 Py_DECREF(newobj);
4078 return NULL; 4227 return NULL;
4079 } 4228 }
4080 cls = (PyObject *) Py_TYPE(obj); 4229 cls = (PyObject *) Py_TYPE(obj);
4081 Py_INCREF(cls); 4230 Py_INCREF(cls);
4082 PyTuple_SET_ITEM(newargs, 0, cls); 4231 PyTuple_SET_ITEM(newargs, 0, cls);
4083 for (i = 0; i < n; i++) { 4232 for (i = 0; i < n; i++) {
4084 PyObject *v = PyTuple_GET_ITEM(args, i); 4233 PyObject *v = PyTuple_GET_ITEM(args, i);
4085 Py_INCREF(v); 4234 Py_INCREF(v);
4086 PyTuple_SET_ITEM(newargs, i+1, v); 4235 PyTuple_SET_ITEM(newargs, i+1, v);
4087 } 4236 }
4088 Py_DECREF(args); 4237 Py_XDECREF(args);
4089 } 4238 }
4090 else if (proto >= 4) { 4239 else if (args != NULL) {
4091 _Py_IDENTIFIER(__newobj_ex__); 4240 _Py_IDENTIFIER(__newobj_ex__);
4092 4241
4093 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__); 4242 newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__);
4094 Py_DECREF(copyreg); 4243 Py_DECREF(copyreg);
4095 if (newobj == NULL) { 4244 if (newobj == NULL) {
4096 Py_DECREF(args); 4245 Py_DECREF(args);
4097 Py_DECREF(kwargs); 4246 Py_DECREF(kwargs);
4098 return NULL; 4247 return NULL;
4099 } 4248 }
4100 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs); 4249 newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs);
4101 Py_DECREF(args); 4250 Py_DECREF(args);
4102 Py_DECREF(kwargs); 4251 Py_DECREF(kwargs);
4103 if (newargs == NULL) { 4252 if (newargs == NULL) {
4104 Py_DECREF(newobj); 4253 Py_DECREF(newobj);
4105 return NULL; 4254 return NULL;
4106 } 4255 }
4107 } 4256 }
4108 else { 4257 else {
4109 PyErr_SetString(PyExc_ValueError, 4258 /* args == NULL */
4110 "must use protocol 4 or greater to copy this "
4111 "object; since __getnewargs_ex__ returned "
4112 "keyword arguments.");
4113 Py_DECREF(args);
4114 Py_DECREF(kwargs); 4259 Py_DECREF(kwargs);
4115 Py_DECREF(copyreg); 4260 PyErr_BadInternalCall();
4116 return NULL; 4261 return NULL;
4117 } 4262 }
4118 4263
4119 state = _PyObject_GetState(obj); 4264 state = _PyObject_GetState(obj,
4265 !hasargs && !PyList_Check(obj) && !PyDict_Check(obj));
4120 if (state == NULL) { 4266 if (state == NULL) {
4121 Py_DECREF(newobj); 4267 Py_DECREF(newobj);
4122 Py_DECREF(newargs); 4268 Py_DECREF(newargs);
4123 return NULL; 4269 return NULL;
4124 } 4270 }
4125 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) { 4271 if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) {
4126 Py_DECREF(newobj); 4272 Py_DECREF(newobj);
4127 Py_DECREF(newargs); 4273 Py_DECREF(newargs);
4128 Py_DECREF(state); 4274 Py_DECREF(state);
4129 return NULL; 4275 return NULL;
4130 } 4276 }
4131 4277
4132 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems); 4278 result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems);
4133 Py_DECREF(newobj); 4279 Py_DECREF(newobj);
4134 Py_DECREF(newargs); 4280 Py_DECREF(newargs);
4135 Py_DECREF(state); 4281 Py_DECREF(state);
4136 Py_DECREF(listitems); 4282 Py_DECREF(listitems);
4137 Py_DECREF(dictitems); 4283 Py_DECREF(dictitems);
4138 return result; 4284 return result;
4139 } 4285 }
4140 4286
4141 /* 4287 /*
4142 * There were two problems when object.__reduce__ and object.__reduce_ex__ 4288 * There were two problems when object.__reduce__ and object.__reduce_ex__
4143 * were implemented in the same function: 4289 * were implemented in the same function:
4144 * - trying to pickle an object with a custom __reduce__ method that 4290 * - trying to pickle an object with a custom __reduce__ method that
4145 * fell back to object.__reduce__ in certain circumstances led to 4291 * fell back to object.__reduce__ in certain circumstances led to
4146 * infinite recursion at Python level and eventual RuntimeError. 4292 * infinite recursion at Python level and eventual RecursionError.
4147 * - Pickling objects that lied about their type by overwriting the 4293 * - Pickling objects that lied about their type by overwriting the
4148 * __class__ descriptor could lead to infinite recursion at C level 4294 * __class__ descriptor could lead to infinite recursion at C level
4149 * and eventual segfault. 4295 * and eventual segfault.
4150 * 4296 *
4151 * Because of backwards compatibility, the two methods still have to 4297 * Because of backwards compatibility, the two methods still have to
4152 * behave in the same way, even if this is not required by the pickle 4298 * behave in the same way, even if this is not required by the pickle
4153 * protocol. This common functionality was moved to the _common_reduce 4299 * protocol. This common functionality was moved to the _common_reduce
4154 * function. 4300 * function.
4155 */ 4301 */
4156 static PyObject * 4302 static PyObject *
4157 _common_reduce(PyObject *self, int proto) 4303 _common_reduce(PyObject *self, int proto)
4158 { 4304 {
4159 PyObject *copyreg, *res; 4305 PyObject *copyreg, *res;
4160 4306
4161 if (proto >= 2) 4307 if (proto >= 2)
4162 return reduce_newobj(self, proto); 4308 return reduce_newobj(self);
4163 4309
4164 copyreg = import_copyreg(); 4310 copyreg = import_copyreg();
4165 if (!copyreg) 4311 if (!copyreg)
4166 return NULL; 4312 return NULL;
4167 4313
4168 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto); 4314 res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
4169 Py_DECREF(copyreg); 4315 Py_DECREF(copyreg);
4170 4316
4171 return res; 4317 return res;
4172 } 4318 }
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
4234 } 4380 }
4235 4381
4236 PyDoc_STRVAR(object_subclasshook_doc, 4382 PyDoc_STRVAR(object_subclasshook_doc,
4237 "Abstract classes can override this to customize issubclass().\n" 4383 "Abstract classes can override this to customize issubclass().\n"
4238 "\n" 4384 "\n"
4239 "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" 4385 "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n"
4240 "It should return True, False or NotImplemented. If it returns\n" 4386 "It should return True, False or NotImplemented. If it returns\n"
4241 "NotImplemented, the normal algorithm is used. Otherwise, it\n" 4387 "NotImplemented, the normal algorithm is used. Otherwise, it\n"
4242 "overrides the normal algorithm (and the outcome is cached).\n"); 4388 "overrides the normal algorithm (and the outcome is cached).\n");
4243 4389
4244 /* 4390 static PyObject *
4245 from PEP 3101, this code implements: 4391 object_init_subclass(PyObject *cls, PyObject *arg)
4246 4392 {
4247 class object: 4393 Py_RETURN_NONE;
4248 def __format__(self, format_spec): 4394 }
4249 return format(str(self), format_spec) 4395
4250 */ 4396 PyDoc_STRVAR(object_init_subclass_doc,
4397 "This method is called when a class is subclassed.\n"
4398 "\n"
4399 "The default implementation does nothing. It may be\n"
4400 "overridden to extend subclasses.\n");
4401
4251 static PyObject * 4402 static PyObject *
4252 object_format(PyObject *self, PyObject *args) 4403 object_format(PyObject *self, PyObject *args)
4253 { 4404 {
4254 PyObject *format_spec; 4405 PyObject *format_spec;
4255 PyObject *self_as_str = NULL; 4406 PyObject *self_as_str = NULL;
4256 PyObject *result = NULL; 4407 PyObject *result = NULL;
4257 4408
4258 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) 4409 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4259 return NULL; 4410 return NULL;
4260 4411
4412 /* Issue 7994: If we're converting to a string, we
4413 should reject format specifications */
4414 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
4415 PyErr_Format(PyExc_TypeError,
4416 "unsupported format string passed to %.200s.__format__",
4417 self->ob_type->tp_name);
4418 return NULL;
4419 }
4261 self_as_str = PyObject_Str(self); 4420 self_as_str = PyObject_Str(self);
4262 if (self_as_str != NULL) { 4421 if (self_as_str != NULL) {
4263 /* Issue 7994: If we're converting to a string, we
4264 should reject format specifications */
4265 if (PyUnicode_GET_LENGTH(format_spec) > 0) {
4266 PyErr_SetString(PyExc_TypeError,
4267 "non-empty format string passed to object.__format__");
4268 goto done;
4269 }
4270
4271 result = PyObject_Format(self_as_str, format_spec); 4422 result = PyObject_Format(self_as_str, format_spec);
4272 } 4423 Py_DECREF(self_as_str);
4273 4424 }
4274 done:
4275 Py_XDECREF(self_as_str);
4276
4277 return result; 4425 return result;
4278 } 4426 }
4279 4427
4280 static PyObject * 4428 static PyObject *
4281 object_sizeof(PyObject *self, PyObject *args) 4429 object_sizeof(PyObject *self, PyObject *args)
4282 { 4430 {
4283 Py_ssize_t res, isize; 4431 Py_ssize_t res, isize;
4284 4432
4285 res = 0; 4433 res = 0;
4286 isize = self->ob_type->tp_itemsize; 4434 isize = self->ob_type->tp_itemsize;
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after
4338 return result; 4486 return result;
4339 } 4487 }
4340 4488
4341 static PyMethodDef object_methods[] = { 4489 static PyMethodDef object_methods[] = {
4342 {"__reduce_ex__", object_reduce_ex, METH_VARARGS, 4490 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
4343 PyDoc_STR("helper for pickle")}, 4491 PyDoc_STR("helper for pickle")},
4344 {"__reduce__", object_reduce, METH_VARARGS, 4492 {"__reduce__", object_reduce, METH_VARARGS,
4345 PyDoc_STR("helper for pickle")}, 4493 PyDoc_STR("helper for pickle")},
4346 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, 4494 {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
4347 object_subclasshook_doc}, 4495 object_subclasshook_doc},
4496 {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS,
4497 object_init_subclass_doc},
4348 {"__format__", object_format, METH_VARARGS, 4498 {"__format__", object_format, METH_VARARGS,
4349 PyDoc_STR("default object formatter")}, 4499 PyDoc_STR("default object formatter")},
4350 {"__sizeof__", object_sizeof, METH_NOARGS, 4500 {"__sizeof__", object_sizeof, METH_NOARGS,
4351 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")}, 4501 PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
4352 {"__dir__", object_dir, METH_NOARGS, 4502 {"__dir__", object_dir, METH_NOARGS,
4353 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")}, 4503 PyDoc_STR("__dir__() -> list\ndefault dir() implementation")},
4354 {0} 4504 {0}
4355 }; 4505 };
4356 4506
4357 4507
(...skipping 86 matching lines...) Expand 10 before | Expand all | Expand 10 after
4444 { 4594 {
4445 PyObject *dict = type->tp_dict; 4595 PyObject *dict = type->tp_dict;
4446 4596
4447 for (; memb->name != NULL; memb++) { 4597 for (; memb->name != NULL; memb++) {
4448 PyObject *descr; 4598 PyObject *descr;
4449 if (PyDict_GetItemString(dict, memb->name)) 4599 if (PyDict_GetItemString(dict, memb->name))
4450 continue; 4600 continue;
4451 descr = PyDescr_NewMember(type, memb); 4601 descr = PyDescr_NewMember(type, memb);
4452 if (descr == NULL) 4602 if (descr == NULL)
4453 return -1; 4603 return -1;
4454 if (PyDict_SetItemString(dict, memb->name, descr) < 0) 4604 if (PyDict_SetItemString(dict, memb->name, descr) < 0) {
4605 Py_DECREF(descr);
4455 return -1; 4606 return -1;
4607 }
4456 Py_DECREF(descr); 4608 Py_DECREF(descr);
4457 } 4609 }
4458 return 0; 4610 return 0;
4459 } 4611 }
4460 4612
4461 static int 4613 static int
4462 add_getset(PyTypeObject *type, PyGetSetDef *gsp) 4614 add_getset(PyTypeObject *type, PyGetSetDef *gsp)
4463 { 4615 {
4464 PyObject *dict = type->tp_dict; 4616 PyObject *dict = type->tp_dict;
4465 4617
4466 for (; gsp->name != NULL; gsp++) { 4618 for (; gsp->name != NULL; gsp++) {
4467 PyObject *descr; 4619 PyObject *descr;
4468 if (PyDict_GetItemString(dict, gsp->name)) 4620 if (PyDict_GetItemString(dict, gsp->name))
4469 continue; 4621 continue;
4470 descr = PyDescr_NewGetSet(type, gsp); 4622 descr = PyDescr_NewGetSet(type, gsp);
4471 4623
4472 if (descr == NULL) 4624 if (descr == NULL)
4473 return -1; 4625 return -1;
4474 if (PyDict_SetItemString(dict, gsp->name, descr) < 0) 4626 if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
4627 Py_DECREF(descr);
4475 return -1; 4628 return -1;
4629 }
4476 Py_DECREF(descr); 4630 Py_DECREF(descr);
4477 } 4631 }
4478 return 0; 4632 return 0;
4479 } 4633 }
4480 4634
4481 static void 4635 static void
4482 inherit_special(PyTypeObject *type, PyTypeObject *base) 4636 inherit_special(PyTypeObject *type, PyTypeObject *base)
4483 { 4637 {
4484 4638
4485 /* Copying basicsize is connected to the GC flags */ 4639 /* Copying basicsize is connected to the GC flags */
(...skipping 81 matching lines...) Expand 10 before | Expand all | Expand 10 after
4567 #undef COPYMAP 4721 #undef COPYMAP
4568 #undef COPYBUF 4722 #undef COPYBUF
4569 4723
4570 #define SLOTDEFINED(SLOT) \ 4724 #define SLOTDEFINED(SLOT) \
4571 (base->SLOT != 0 && \ 4725 (base->SLOT != 0 && \
4572 (basebase == NULL || base->SLOT != basebase->SLOT)) 4726 (basebase == NULL || base->SLOT != basebase->SLOT))
4573 4727
4574 #define COPYSLOT(SLOT) \ 4728 #define COPYSLOT(SLOT) \
4575 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT 4729 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
4576 4730
4731 #define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT)
4577 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT) 4732 #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
4578 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT) 4733 #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
4579 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT) 4734 #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
4580 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT) 4735 #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
4581 4736
4582 /* This won't inherit indirect slots (from tp_as_number etc.) 4737 /* This won't inherit indirect slots (from tp_as_number etc.)
4583 if type doesn't provide the space. */ 4738 if type doesn't provide the space. */
4584 4739
4585 if (type->tp_as_number != NULL && base->tp_as_number != NULL) { 4740 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
4586 basebase = base->tp_base; 4741 basebase = base->tp_base;
(...skipping 29 matching lines...) Expand all
4616 COPYNUM(nb_inplace_or); 4771 COPYNUM(nb_inplace_or);
4617 COPYNUM(nb_true_divide); 4772 COPYNUM(nb_true_divide);
4618 COPYNUM(nb_floor_divide); 4773 COPYNUM(nb_floor_divide);
4619 COPYNUM(nb_inplace_true_divide); 4774 COPYNUM(nb_inplace_true_divide);
4620 COPYNUM(nb_inplace_floor_divide); 4775 COPYNUM(nb_inplace_floor_divide);
4621 COPYNUM(nb_index); 4776 COPYNUM(nb_index);
4622 COPYNUM(nb_matrix_multiply); 4777 COPYNUM(nb_matrix_multiply);
4623 COPYNUM(nb_inplace_matrix_multiply); 4778 COPYNUM(nb_inplace_matrix_multiply);
4624 } 4779 }
4625 4780
4781 if (type->tp_as_async != NULL && base->tp_as_async != NULL) {
4782 basebase = base->tp_base;
4783 if (basebase->tp_as_async == NULL)
4784 basebase = NULL;
4785 COPYASYNC(am_await);
4786 COPYASYNC(am_aiter);
4787 COPYASYNC(am_anext);
4788 }
4789
4626 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { 4790 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
4627 basebase = base->tp_base; 4791 basebase = base->tp_base;
4628 if (basebase->tp_as_sequence == NULL) 4792 if (basebase->tp_as_sequence == NULL)
4629 basebase = NULL; 4793 basebase = NULL;
4630 COPYSEQ(sq_length); 4794 COPYSEQ(sq_length);
4631 COPYSEQ(sq_concat); 4795 COPYSEQ(sq_concat);
4632 COPYSEQ(sq_repeat); 4796 COPYSEQ(sq_repeat);
4633 COPYSEQ(sq_item); 4797 COPYSEQ(sq_item);
4634 COPYSEQ(sq_ass_item); 4798 COPYSEQ(sq_ass_item);
4635 COPYSEQ(sq_contains); 4799 COPYSEQ(sq_contains);
(...skipping 99 matching lines...) Expand 10 before | Expand all | Expand 10 after
4735 type->tp_flags |= Py_TPFLAGS_READYING; 4899 type->tp_flags |= Py_TPFLAGS_READYING;
4736 4900
4737 #ifdef Py_TRACE_REFS 4901 #ifdef Py_TRACE_REFS
4738 /* PyType_Ready is the closest thing we have to a choke point 4902 /* PyType_Ready is the closest thing we have to a choke point
4739 * for type objects, so is the best place I can think of to try 4903 * for type objects, so is the best place I can think of to try
4740 * to get type objects into the doubly-linked list of all objects. 4904 * to get type objects into the doubly-linked list of all objects.
4741 * Still, not all type objects go thru PyType_Ready. 4905 * Still, not all type objects go thru PyType_Ready.
4742 */ 4906 */
4743 _Py_AddToAllObjects((PyObject *)type, 0); 4907 _Py_AddToAllObjects((PyObject *)type, 0);
4744 #endif 4908 #endif
4909
4910 if (type->tp_name == NULL) {
4911 PyErr_Format(PyExc_SystemError,
4912 "Type does not define the tp_name field.");
4913 goto error;
4914 }
4745 4915
4746 /* Initialize tp_base (defaults to BaseObject unless that's us) */ 4916 /* Initialize tp_base (defaults to BaseObject unless that's us) */
4747 base = type->tp_base; 4917 base = type->tp_base;
4748 if (base == NULL && type != &PyBaseObject_Type) { 4918 if (base == NULL && type != &PyBaseObject_Type) {
4749 base = type->tp_base = &PyBaseObject_Type; 4919 base = type->tp_base = &PyBaseObject_Type;
4750 Py_INCREF(base); 4920 Py_INCREF(base);
4751 } 4921 }
4752 4922
4753 /* Now the only way base can still be NULL is if type is 4923 /* Now the only way base can still be NULL is if type is
4754 * &PyBaseObject_Type. 4924 * &PyBaseObject_Type.
(...skipping 130 matching lines...) Expand 10 before | Expand all | Expand 10 after
4885 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) { 5055 if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) {
4886 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0) 5056 if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0)
4887 goto error; 5057 goto error;
4888 type->tp_hash = PyObject_HashNotImplemented; 5058 type->tp_hash = PyObject_HashNotImplemented;
4889 } 5059 }
4890 } 5060 }
4891 5061
4892 /* Some more special stuff */ 5062 /* Some more special stuff */
4893 base = type->tp_base; 5063 base = type->tp_base;
4894 if (base != NULL) { 5064 if (base != NULL) {
5065 if (type->tp_as_async == NULL)
5066 type->tp_as_async = base->tp_as_async;
4895 if (type->tp_as_number == NULL) 5067 if (type->tp_as_number == NULL)
4896 type->tp_as_number = base->tp_as_number; 5068 type->tp_as_number = base->tp_as_number;
4897 if (type->tp_as_sequence == NULL) 5069 if (type->tp_as_sequence == NULL)
4898 type->tp_as_sequence = base->tp_as_sequence; 5070 type->tp_as_sequence = base->tp_as_sequence;
4899 if (type->tp_as_mapping == NULL) 5071 if (type->tp_as_mapping == NULL)
4900 type->tp_as_mapping = base->tp_as_mapping; 5072 type->tp_as_mapping = base->tp_as_mapping;
4901 if (type->tp_as_buffer == NULL) 5073 if (type->tp_as_buffer == NULL)
4902 type->tp_as_buffer = base->tp_as_buffer; 5074 type->tp_as_buffer = base->tp_as_buffer;
4903 } 5075 }
4904 5076
4905 /* Link into each base class's list of subclasses */ 5077 /* Link into each base class's list of subclasses */
4906 bases = type->tp_bases; 5078 bases = type->tp_bases;
4907 n = PyTuple_GET_SIZE(bases); 5079 n = PyTuple_GET_SIZE(bases);
4908 for (i = 0; i < n; i++) { 5080 for (i = 0; i < n; i++) {
4909 PyObject *b = PyTuple_GET_ITEM(bases, i); 5081 PyObject *b = PyTuple_GET_ITEM(bases, i);
4910 if (PyType_Check(b) && 5082 if (PyType_Check(b) &&
4911 add_subclass((PyTypeObject *)b, type) < 0) 5083 add_subclass((PyTypeObject *)b, type) < 0)
4912 goto error; 5084 goto error;
4913 }
4914
4915 /* Warn for a type that implements tp_compare (now known as
4916 tp_reserved) but not tp_richcompare. */
4917 if (type->tp_reserved && !type->tp_richcompare) {
4918 PyErr_Format(PyExc_TypeError,
4919 "Type %.100s defines tp_reserved (formerly tp_compare) "
4920 "but not tp_richcompare. Comparisons may not behave as intended.",
4921 type->tp_name);
4922 goto error;
4923 } 5085 }
4924 5086
4925 /* All done -- set the ready flag */ 5087 /* All done -- set the ready flag */
4926 assert(type->tp_dict != NULL); 5088 assert(type->tp_dict != NULL);
4927 type->tp_flags = 5089 type->tp_flags =
4928 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; 5090 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
4929 return 0; 5091 return 0;
4930 5092
4931 error: 5093 error:
4932 type->tp_flags &= ~Py_TPFLAGS_READYING; 5094 type->tp_flags &= ~Py_TPFLAGS_READYING;
(...skipping 344 matching lines...) Expand 10 before | Expand all | Expand 10 after
5277 res = (*func)(self, key, NULL); 5439 res = (*func)(self, key, NULL);
5278 if (res == -1 && PyErr_Occurred()) 5440 if (res == -1 && PyErr_Occurred())
5279 return NULL; 5441 return NULL;
5280 Py_INCREF(Py_None); 5442 Py_INCREF(Py_None);
5281 return Py_None; 5443 return Py_None;
5282 } 5444 }
5283 5445
5284 /* Helper to check for object.__setattr__ or __delattr__ applied to a type. 5446 /* Helper to check for object.__setattr__ or __delattr__ applied to a type.
5285 This is called the Carlo Verre hack after its discoverer. */ 5447 This is called the Carlo Verre hack after its discoverer. */
5286 static int 5448 static int
5287 hackcheck(PyObject *self, setattrofunc func, char *what) 5449 hackcheck(PyObject *self, setattrofunc func, const char *what)
5288 { 5450 {
5289 PyTypeObject *type = Py_TYPE(self); 5451 PyTypeObject *type = Py_TYPE(self);
5290 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) 5452 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
5291 type = type->tp_base; 5453 type = type->tp_base;
5292 /* If type is NULL now, this is a really weird type. 5454 /* If type is NULL now, this is a really weird type.
5293 In the spirit of backwards compatibility (?), just shut up. */ 5455 In the spirit of backwards compatibility (?), just shut up. */
5294 if (type && type->tp_setattro != func) { 5456 if (type && type->tp_setattro != func) {
5295 PyErr_Format(PyExc_TypeError, 5457 PyErr_Format(PyExc_TypeError,
5296 "can't apply this %s to %s object", 5458 "can't apply this %s to %s object",
5297 what, 5459 what,
(...skipping 266 matching lines...) Expand 10 before | Expand all | Expand 10 after
5564 } 5726 }
5565 5727
5566 /* Slot wrappers that call the corresponding __foo__ slot. See comments 5728 /* Slot wrappers that call the corresponding __foo__ slot. See comments
5567 below at override_slots() for more explanation. */ 5729 below at override_slots() for more explanation. */
5568 5730
5569 #define SLOT0(FUNCNAME, OPSTR) \ 5731 #define SLOT0(FUNCNAME, OPSTR) \
5570 static PyObject * \ 5732 static PyObject * \
5571 FUNCNAME(PyObject *self) \ 5733 FUNCNAME(PyObject *self) \
5572 { \ 5734 { \
5573 _Py_static_string(id, OPSTR); \ 5735 _Py_static_string(id, OPSTR); \
5574 return call_method(self, &id, "()"); \ 5736 return call_method(self, &id, NULL); \
5575 } 5737 }
5576 5738
5577 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \ 5739 #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
5578 static PyObject * \ 5740 static PyObject * \
5579 FUNCNAME(PyObject *self, ARG1TYPE arg1) \ 5741 FUNCNAME(PyObject *self, ARG1TYPE arg1) \
5580 { \ 5742 { \
5581 _Py_static_string(id, OPSTR); \ 5743 _Py_static_string(id, OPSTR); \
5582 return call_method(self, &id, "(" ARGCODES ")", arg1); \ 5744 return call_method(self, &id, "(" ARGCODES ")", arg1); \
5583 } 5745 }
5584 5746
(...skipping 72 matching lines...) Expand 10 before | Expand all | Expand 10 after
5657 static PyObject * \ 5819 static PyObject * \
5658 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \ 5820 FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
5659 { \ 5821 { \
5660 _Py_static_string(id, #OPSTR); \ 5822 _Py_static_string(id, #OPSTR); \
5661 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \ 5823 return call_method(self, &id, "(" ARGCODES ")", arg1, arg2); \
5662 } 5824 }
5663 5825
5664 static Py_ssize_t 5826 static Py_ssize_t
5665 slot_sq_length(PyObject *self) 5827 slot_sq_length(PyObject *self)
5666 { 5828 {
5667 PyObject *res = call_method(self, &PyId___len__, "()"); 5829 PyObject *res = call_method(self, &PyId___len__, NULL);
5668 Py_ssize_t len; 5830 Py_ssize_t len;
5669 5831
5670 if (res == NULL) 5832 if (res == NULL)
5671 return -1; 5833 return -1;
5672 len = PyNumber_AsSsize_t(res, PyExc_OverflowError); 5834 len = PyNumber_AsSsize_t(res, PyExc_OverflowError);
5673 Py_DECREF(res); 5835 Py_DECREF(res);
5674 if (len < 0) { 5836 if (len < 0) {
5675 if (!PyErr_Occurred()) 5837 if (!PyErr_Occurred())
5676 PyErr_SetString(PyExc_ValueError, 5838 PyErr_SetString(PyExc_ValueError,
5677 "__len__() should return >= 0"); 5839 "__len__() should return >= 0");
5678 return -1; 5840 return -1;
5679 } 5841 }
5680 return len; 5842 return len;
5681 } 5843 }
5682 5844
5683 /* Super-optimized version of slot_sq_item. 5845 /* Super-optimized version of slot_sq_item.
5684 Other slots could do the same... */ 5846 Other slots could do the same... */
5685 static PyObject * 5847 static PyObject *
5686 slot_sq_item(PyObject *self, Py_ssize_t i) 5848 slot_sq_item(PyObject *self, Py_ssize_t i)
5687 { 5849 {
5688 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL; 5850 PyObject *func, *ival = NULL, *retval = NULL;
5689 descrgetfunc f; 5851 descrgetfunc f;
5690 5852
5691 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__); 5853 func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__);
5692 if (func != NULL) { 5854 if (func == NULL) {
5693 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
5694 Py_INCREF(func);
5695 else {
5696 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5697 if (func == NULL) {
5698 return NULL;
5699 }
5700 }
5701 ival = PyLong_FromSsize_t(i);
5702 if (ival != NULL) {
5703 args = PyTuple_New(1);
5704 if (args != NULL) {
5705 PyTuple_SET_ITEM(args, 0, ival);
5706 retval = PyObject_Call(func, args, NULL);
5707 Py_XDECREF(args);
5708 Py_XDECREF(func);
5709 return retval;
5710 }
5711 }
5712 }
5713 else {
5714 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__); 5855 PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__);
5715 PyErr_SetObject(PyExc_AttributeError, getitem_str); 5856 PyErr_SetObject(PyExc_AttributeError, getitem_str);
5716 } 5857 return NULL;
5717 Py_XDECREF(args); 5858 }
5718 Py_XDECREF(ival); 5859
5719 Py_XDECREF(func); 5860 f = Py_TYPE(func)->tp_descr_get;
5861 if (f == NULL) {
5862 Py_INCREF(func);
5863 }
5864 else {
5865 func = f(func, self, (PyObject *)(Py_TYPE(self)));
5866 if (func == NULL) {
5867 return NULL;
5868 }
5869 }
5870
5871 ival = PyLong_FromSsize_t(i);
5872 if (ival == NULL) {
5873 goto error;
5874 }
5875
5876 retval = _PyObject_CallArg1(func, ival);
5877 Py_DECREF(func);
5878 Py_DECREF(ival);
5879 return retval;
5880
5881 error:
5882 Py_DECREF(func);
5720 return NULL; 5883 return NULL;
5721 } 5884 }
5722 5885
5723 static int 5886 static int
5724 slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value) 5887 slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
5725 { 5888 {
5726 PyObject *res; 5889 PyObject *res;
5727 5890
5728 if (value == NULL) 5891 if (value == NULL)
5729 res = call_method(self, &PyId___delitem__, "(n)", index); 5892 res = call_method(self, &PyId___delitem__, "(n)", index);
5730 else 5893 else
5731 res = call_method(self, &PyId___setitem__, "(nO)", index, value); 5894 res = call_method(self, &PyId___setitem__, "(nO)", index, value);
5732 if (res == NULL) 5895 if (res == NULL)
5733 return -1; 5896 return -1;
5734 Py_DECREF(res); 5897 Py_DECREF(res);
5735 return 0; 5898 return 0;
5736 } 5899 }
5737 5900
5738 static int 5901 static int
5739 slot_sq_contains(PyObject *self, PyObject *value) 5902 slot_sq_contains(PyObject *self, PyObject *value)
5740 { 5903 {
5741 PyObject *func, *res, *args; 5904 PyObject *func, *res;
5742 int result = -1; 5905 int result = -1;
5743 _Py_IDENTIFIER(__contains__); 5906 _Py_IDENTIFIER(__contains__);
5744 5907
5745 func = lookup_maybe(self, &PyId___contains__); 5908 func = lookup_maybe(self, &PyId___contains__);
5909 if (func == Py_None) {
5910 Py_DECREF(func);
5911 PyErr_Format(PyExc_TypeError,
5912 "'%.200s' object is not a container",
5913 Py_TYPE(self)->tp_name);
5914 return -1;
5915 }
5746 if (func != NULL) { 5916 if (func != NULL) {
5747 args = PyTuple_Pack(1, value); 5917 res = _PyObject_CallArg1(func, value);
5748 if (args == NULL)
5749 res = NULL;
5750 else {
5751 res = PyObject_Call(func, args, NULL);
5752 Py_DECREF(args);
5753 }
5754 Py_DECREF(func); 5918 Py_DECREF(func);
5755 if (res != NULL) { 5919 if (res != NULL) {
5756 result = PyObject_IsTrue(res); 5920 result = PyObject_IsTrue(res);
5757 Py_DECREF(res); 5921 Py_DECREF(res);
5758 } 5922 }
5759 } 5923 }
5760 else if (! PyErr_Occurred()) { 5924 else if (! PyErr_Occurred()) {
5761 /* Possible results: -1 and 1 */ 5925 /* Possible results: -1 and 1 */
5762 result = (int)_PySequence_IterSearch(self, value, 5926 result = (int)_PySequence_IterSearch(self, value,
5763 PY_ITERSEARCH_CONTAINS); 5927 PY_ITERSEARCH_CONTAINS);
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
5814 Py_RETURN_NOTIMPLEMENTED; 5978 Py_RETURN_NOTIMPLEMENTED;
5815 } 5979 }
5816 5980
5817 SLOT0(slot_nb_negative, "__neg__") 5981 SLOT0(slot_nb_negative, "__neg__")
5818 SLOT0(slot_nb_positive, "__pos__") 5982 SLOT0(slot_nb_positive, "__pos__")
5819 SLOT0(slot_nb_absolute, "__abs__") 5983 SLOT0(slot_nb_absolute, "__abs__")
5820 5984
5821 static int 5985 static int
5822 slot_nb_bool(PyObject *self) 5986 slot_nb_bool(PyObject *self)
5823 { 5987 {
5824 PyObject *func, *args; 5988 PyObject *func, *value;
5825 int result = -1; 5989 int result;
5826 int using_len = 0; 5990 int using_len = 0;
5827 _Py_IDENTIFIER(__bool__); 5991 _Py_IDENTIFIER(__bool__);
5828 5992
5829 func = lookup_maybe(self, &PyId___bool__); 5993 func = lookup_maybe(self, &PyId___bool__);
5830 if (func == NULL) { 5994 if (func == NULL) {
5831 if (PyErr_Occurred()) 5995 if (PyErr_Occurred()) {
5832 return -1; 5996 return -1;
5997 }
5998
5833 func = lookup_maybe(self, &PyId___len__); 5999 func = lookup_maybe(self, &PyId___len__);
5834 if (func == NULL) 6000 if (func == NULL) {
5835 return PyErr_Occurred() ? -1 : 1; 6001 if (PyErr_Occurred()) {
6002 return -1;
6003 }
6004 return 1;
6005 }
5836 using_len = 1; 6006 using_len = 1;
5837 } 6007 }
5838 args = PyTuple_New(0); 6008
5839 if (args != NULL) { 6009 value = _PyObject_CallNoArg(func);
5840 PyObject *temp = PyObject_Call(func, args, NULL); 6010 if (value == NULL) {
5841 Py_DECREF(args); 6011 goto error;
5842 if (temp != NULL) { 6012 }
5843 if (using_len) { 6013
5844 /* enforced by slot_nb_len */ 6014 if (using_len) {
5845 result = PyObject_IsTrue(temp); 6015 /* bool type enforced by slot_nb_len */
5846 } 6016 result = PyObject_IsTrue(value);
5847 else if (PyBool_Check(temp)) { 6017 }
5848 result = PyObject_IsTrue(temp); 6018 else if (PyBool_Check(value)) {
5849 } 6019 result = PyObject_IsTrue(value);
5850 else { 6020 }
5851 PyErr_Format(PyExc_TypeError, 6021 else {
5852 "__bool__ should return " 6022 PyErr_Format(PyExc_TypeError,
5853 "bool, returned %s", 6023 "__bool__ should return "
5854 Py_TYPE(temp)->tp_name); 6024 "bool, returned %s",
5855 result = -1; 6025 Py_TYPE(value)->tp_name);
5856 } 6026 result = -1;
5857 Py_DECREF(temp); 6027 }
5858 } 6028
5859 } 6029 Py_DECREF(value);
5860 Py_DECREF(func); 6030 Py_DECREF(func);
5861 return result; 6031 return result;
6032
6033 error:
6034 Py_DECREF(func);
6035 return -1;
5862 } 6036 }
5863 6037
5864 6038
5865 static PyObject * 6039 static PyObject *
5866 slot_nb_index(PyObject *self) 6040 slot_nb_index(PyObject *self)
5867 { 6041 {
5868 _Py_IDENTIFIER(__index__); 6042 _Py_IDENTIFIER(__index__);
5869 return call_method(self, &PyId___index__, "()"); 6043 return call_method(self, &PyId___index__, NULL);
5870 } 6044 }
5871 6045
5872 6046
5873 SLOT0(slot_nb_invert, "__invert__") 6047 SLOT0(slot_nb_invert, "__invert__")
5874 SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__") 6048 SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
5875 SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__") 6049 SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
5876 SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__") 6050 SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
5877 SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__") 6051 SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
5878 SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__") 6052 SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
5879 6053
(...skipping 216 matching lines...) Expand 10 before | Expand all | Expand 10 after
6096 {0, "__le__", 0}, 6270 {0, "__le__", 0},
6097 {0, "__eq__", 0}, 6271 {0, "__eq__", 0},
6098 {0, "__ne__", 0}, 6272 {0, "__ne__", 0},
6099 {0, "__gt__", 0}, 6273 {0, "__gt__", 0},
6100 {0, "__ge__", 0} 6274 {0, "__ge__", 0}
6101 }; 6275 };
6102 6276
6103 static PyObject * 6277 static PyObject *
6104 slot_tp_richcompare(PyObject *self, PyObject *other, int op) 6278 slot_tp_richcompare(PyObject *self, PyObject *other, int op)
6105 { 6279 {
6106 PyObject *func, *args, *res; 6280 PyObject *func, *res;
6107 6281
6108 func = lookup_method(self, &name_op[op]); 6282 func = lookup_method(self, &name_op[op]);
6109 if (func == NULL) { 6283 if (func == NULL) {
6110 PyErr_Clear(); 6284 PyErr_Clear();
6111 Py_RETURN_NOTIMPLEMENTED; 6285 Py_RETURN_NOTIMPLEMENTED;
6112 } 6286 }
6113 args = PyTuple_Pack(1, other); 6287 res = _PyObject_CallArg1(func, other);
6114 if (args == NULL)
6115 res = NULL;
6116 else {
6117 res = PyObject_Call(func, args, NULL);
6118 Py_DECREF(args);
6119 }
6120 Py_DECREF(func); 6288 Py_DECREF(func);
6121 return res; 6289 return res;
6122 } 6290 }
6123 6291
6124 static PyObject * 6292 static PyObject *
6125 slot_tp_iter(PyObject *self) 6293 slot_tp_iter(PyObject *self)
6126 { 6294 {
6127 PyObject *func, *res; 6295 PyObject *func, *res;
6128 _Py_IDENTIFIER(__iter__); 6296 _Py_IDENTIFIER(__iter__);
6129 6297
6130 func = lookup_method(self, &PyId___iter__); 6298 func = lookup_method(self, &PyId___iter__);
6299 if (func == Py_None) {
6300 Py_DECREF(func);
6301 PyErr_Format(PyExc_TypeError,
6302 "'%.200s' object is not iterable",
6303 Py_TYPE(self)->tp_name);
6304 return NULL;
6305 }
6306
6131 if (func != NULL) { 6307 if (func != NULL) {
6132 PyObject *args; 6308 res = _PyObject_CallNoArg(func);
6133 args = res = PyTuple_New(0);
6134 if (args != NULL) {
6135 res = PyObject_Call(func, args, NULL);
6136 Py_DECREF(args);
6137 }
6138 Py_DECREF(func); 6309 Py_DECREF(func);
6139 return res; 6310 return res;
6140 } 6311 }
6312
6141 PyErr_Clear(); 6313 PyErr_Clear();
6142 func = lookup_method(self, &PyId___getitem__); 6314 func = lookup_method(self, &PyId___getitem__);
6143 if (func == NULL) { 6315 if (func == NULL) {
6144 PyErr_Format(PyExc_TypeError, 6316 PyErr_Format(PyExc_TypeError,
6145 "'%.200s' object is not iterable", 6317 "'%.200s' object is not iterable",
6146 Py_TYPE(self)->tp_name); 6318 Py_TYPE(self)->tp_name);
6147 return NULL; 6319 return NULL;
6148 } 6320 }
6149 Py_DECREF(func); 6321 Py_DECREF(func);
6150 return PySeqIter_New(self); 6322 return PySeqIter_New(self);
6151 } 6323 }
6152 6324
6153 static PyObject * 6325 static PyObject *
6154 slot_tp_iternext(PyObject *self) 6326 slot_tp_iternext(PyObject *self)
6155 { 6327 {
6156 _Py_IDENTIFIER(__next__); 6328 _Py_IDENTIFIER(__next__);
6157 return call_method(self, &PyId___next__, "()"); 6329 return call_method(self, &PyId___next__, NULL);
6158 } 6330 }
6159 6331
6160 static PyObject * 6332 static PyObject *
6161 slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type) 6333 slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6162 { 6334 {
6163 PyTypeObject *tp = Py_TYPE(self); 6335 PyTypeObject *tp = Py_TYPE(self);
6164 PyObject *get; 6336 PyObject *get;
6165 _Py_IDENTIFIER(__get__); 6337 _Py_IDENTIFIER(__get__);
6166 6338
6167 get = _PyType_LookupId(tp, &PyId___get__); 6339 get = _PyType_LookupId(tp, &PyId___get__);
(...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after
6216 Py_DECREF(res); 6388 Py_DECREF(res);
6217 return -1; 6389 return -1;
6218 } 6390 }
6219 Py_DECREF(res); 6391 Py_DECREF(res);
6220 return 0; 6392 return 0;
6221 } 6393 }
6222 6394
6223 static PyObject * 6395 static PyObject *
6224 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 6396 slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
6225 { 6397 {
6226 PyObject *func; 6398 PyObject *func, *result;
6227 PyObject *newargs, *x;
6228 Py_ssize_t i, n;
6229 6399
6230 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__); 6400 func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__);
6231 if (func == NULL) 6401 if (func == NULL) {
6232 return NULL; 6402 return NULL;
6233 assert(PyTuple_Check(args)); 6403 }
6234 n = PyTuple_GET_SIZE(args); 6404
6235 newargs = PyTuple_New(n+1); 6405 result = _PyObject_Call_Prepend(func, (PyObject *)type, args, kwds);
6236 if (newargs == NULL)
6237 return NULL;
6238 Py_INCREF(type);
6239 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
6240 for (i = 0; i < n; i++) {
6241 x = PyTuple_GET_ITEM(args, i);
6242 Py_INCREF(x);
6243 PyTuple_SET_ITEM(newargs, i+1, x);
6244 }
6245 x = PyObject_Call(func, newargs, kwds);
6246 Py_DECREF(newargs);
6247 Py_DECREF(func); 6406 Py_DECREF(func);
6248 return x; 6407 return result;
6249 } 6408 }
6250 6409
6251 static void 6410 static void
6252 slot_tp_finalize(PyObject *self) 6411 slot_tp_finalize(PyObject *self)
6253 { 6412 {
6254 _Py_IDENTIFIER(__del__); 6413 _Py_IDENTIFIER(__del__);
6255 PyObject *del, *res; 6414 PyObject *del, *res;
6256 PyObject *error_type, *error_value, *error_traceback; 6415 PyObject *error_type, *error_value, *error_traceback;
6257 6416
6258 /* Save the current exception, if any. */ 6417 /* Save the current exception, if any. */
6259 PyErr_Fetch(&error_type, &error_value, &error_traceback); 6418 PyErr_Fetch(&error_type, &error_value, &error_traceback);
6260 6419
6261 /* Execute __del__ method, if any. */ 6420 /* Execute __del__ method, if any. */
6262 del = lookup_maybe(self, &PyId___del__); 6421 del = lookup_maybe(self, &PyId___del__);
6263 if (del != NULL) { 6422 if (del != NULL) {
6264 res = PyEval_CallObject(del, NULL); 6423 res = PyEval_CallObject(del, NULL);
6265 if (res == NULL) 6424 if (res == NULL)
6266 PyErr_WriteUnraisable(del); 6425 PyErr_WriteUnraisable(del);
6267 else 6426 else
6268 Py_DECREF(res); 6427 Py_DECREF(res);
6269 Py_DECREF(del); 6428 Py_DECREF(del);
6270 } 6429 }
6271 6430
6272 /* Restore the saved exception. */ 6431 /* Restore the saved exception. */
6273 PyErr_Restore(error_type, error_value, error_traceback); 6432 PyErr_Restore(error_type, error_value, error_traceback);
6274 } 6433 }
6275 6434
6435 static PyObject *
6436 slot_am_await(PyObject *self)
6437 {
6438 PyObject *func, *res;
6439 _Py_IDENTIFIER(__await__);
6440
6441 func = lookup_method(self, &PyId___await__);
6442 if (func != NULL) {
6443 res = PyEval_CallObject(func, NULL);
6444 Py_DECREF(func);
6445 return res;
6446 }
6447 PyErr_Format(PyExc_AttributeError,
6448 "object %.50s does not have __await__ method",
6449 Py_TYPE(self)->tp_name);
6450 return NULL;
6451 }
6452
6453 static PyObject *
6454 slot_am_aiter(PyObject *self)
6455 {
6456 PyObject *func, *res;
6457 _Py_IDENTIFIER(__aiter__);
6458
6459 func = lookup_method(self, &PyId___aiter__);
6460 if (func != NULL) {
6461 res = PyEval_CallObject(func, NULL);
6462 Py_DECREF(func);
6463 return res;
6464 }
6465 PyErr_Format(PyExc_AttributeError,
6466 "object %.50s does not have __aiter__ method",
6467 Py_TYPE(self)->tp_name);
6468 return NULL;
6469 }
6470
6471 static PyObject *
6472 slot_am_anext(PyObject *self)
6473 {
6474 PyObject *func, *res;
6475 _Py_IDENTIFIER(__anext__);
6476
6477 func = lookup_method(self, &PyId___anext__);
6478 if (func != NULL) {
6479 res = PyEval_CallObject(func, NULL);
6480 Py_DECREF(func);
6481 return res;
6482 }
6483 PyErr_Format(PyExc_AttributeError,
6484 "object %.50s does not have __anext__ method",
6485 Py_TYPE(self)->tp_name);
6486 return NULL;
6487 }
6276 6488
6277 /* 6489 /*
6278 Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions. 6490 Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions.
6279 6491
6280 The table is ordered by offsets relative to the 'PyHeapTypeObject' structure, 6492 The table is ordered by offsets relative to the 'PyHeapTypeObject' structure,
6281 which incorporates the additional structures used for numbers, sequences and 6493 which incorporates the additional structures used for numbers, sequences and
6282 mappings. Note that multiple names may map to the same slot (e.g. __eq__, 6494 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
6283 __ne__ etc. all map to tp_richcompare) and one name may map to multiple slots 6495 __ne__ etc. all map to tp_richcompare) and one name may map to multiple slots
6284 (e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with 6496 (e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with
6285 an all-zero entry. (This table is further initialized in init_slotdefs().) 6497 an all-zero entry. (This table is further initialized in init_slotdefs().)
6286 */ 6498 */
6287 6499
6288 typedef struct wrapperbase slotdef; 6500 typedef struct wrapperbase slotdef;
6289 6501
6290 #undef TPSLOT 6502 #undef TPSLOT
6291 #undef FLSLOT 6503 #undef FLSLOT
6504 #undef AMSLOT
6292 #undef ETSLOT 6505 #undef ETSLOT
6293 #undef SQSLOT 6506 #undef SQSLOT
6294 #undef MPSLOT 6507 #undef MPSLOT
6295 #undef NBSLOT 6508 #undef NBSLOT
6296 #undef UNSLOT 6509 #undef UNSLOT
6297 #undef IBSLOT 6510 #undef IBSLOT
6298 #undef BINSLOT 6511 #undef BINSLOT
6299 #undef RBINSLOT 6512 #undef RBINSLOT
6300 6513
6301 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 6514 #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6302 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ 6515 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6303 PyDoc_STR(DOC)} 6516 PyDoc_STR(DOC)}
6304 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \ 6517 #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
6305 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ 6518 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6306 PyDoc_STR(DOC), FLAGS} 6519 PyDoc_STR(DOC), FLAGS}
6307 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 6520 #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6308 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ 6521 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
6309 PyDoc_STR(DOC)} 6522 PyDoc_STR(DOC)}
6523 #define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6524 ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC)
6310 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 6525 #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6311 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) 6526 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
6312 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 6527 #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6313 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) 6528 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
6314 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 6529 #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6315 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) 6530 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
6316 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 6531 #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
6317 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ 6532 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
6318 NAME "($self, /)\n--\n\n" DOC) 6533 NAME "($self, /)\n--\n\n" DOC)
6319 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 6534 #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
6378 wrap_descr_delete, 6593 wrap_descr_delete,
6379 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instanc e."), 6594 "__delete__($self, instance, /)\n--\n\nDelete an attribute of instanc e."),
6380 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, 6595 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
6381 "__init__($self, /, *args, **kwargs)\n--\n\n" 6596 "__init__($self, /, *args, **kwargs)\n--\n\n"
6382 "Initialize self. See help(type(self)) for accurate signature.", 6597 "Initialize self. See help(type(self)) for accurate signature.",
6383 PyWrapperFlag_KEYWORDS), 6598 PyWrapperFlag_KEYWORDS),
6384 TPSLOT("__new__", tp_new, slot_tp_new, NULL, 6599 TPSLOT("__new__", tp_new, slot_tp_new, NULL,
6385 "__new__(type, /, *args, **kwargs)\n--\n\n" 6600 "__new__(type, /, *args, **kwargs)\n--\n\n"
6386 "Create and return new object. See help(type) for accurate signature ."), 6601 "Create and return new object. See help(type) for accurate signature ."),
6387 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""), 6602 TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""),
6603
6604 AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc,
6605 "__await__($self, /)\n--\n\nReturn an iterator to be used in await ex pression."),
6606 AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc,
6607 "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asy nchronous iterator."),
6608 AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc,
6609 "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteratio n."),
6388 6610
6389 BINSLOT("__add__", nb_add, slot_nb_add, 6611 BINSLOT("__add__", nb_add, slot_nb_add,
6390 "+"), 6612 "+"),
6391 RBINSLOT("__radd__", nb_add, slot_nb_add, 6613 RBINSLOT("__radd__", nb_add, slot_nb_add,
6392 "+"), 6614 "+"),
6393 BINSLOT("__sub__", nb_subtract, slot_nb_subtract, 6615 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
6394 "-"), 6616 "-"),
6395 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, 6617 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
6396 "-"), 6618 "-"),
6397 BINSLOT("__mul__", nb_multiply, slot_nb_multiply, 6619 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
(...skipping 133 matching lines...) Expand 10 before | Expand all | Expand 10 after
6531 offset -= offsetof(PyHeapTypeObject, as_sequence); 6753 offset -= offsetof(PyHeapTypeObject, as_sequence);
6532 } 6754 }
6533 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { 6755 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
6534 ptr = (char *)type->tp_as_mapping; 6756 ptr = (char *)type->tp_as_mapping;
6535 offset -= offsetof(PyHeapTypeObject, as_mapping); 6757 offset -= offsetof(PyHeapTypeObject, as_mapping);
6536 } 6758 }
6537 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { 6759 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
6538 ptr = (char *)type->tp_as_number; 6760 ptr = (char *)type->tp_as_number;
6539 offset -= offsetof(PyHeapTypeObject, as_number); 6761 offset -= offsetof(PyHeapTypeObject, as_number);
6540 } 6762 }
6763 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) {
6764 ptr = (char *)type->tp_as_async;
6765 offset -= offsetof(PyHeapTypeObject, as_async);
6766 }
6541 else { 6767 else {
6542 ptr = (char *)type; 6768 ptr = (char *)type;
6543 } 6769 }
6544 if (ptr != NULL) 6770 if (ptr != NULL)
6545 ptr += offset; 6771 ptr += offset;
6546 return (void **)ptr; 6772 return (void **)ptr;
6547 } 6773 }
6548 6774
6549 /* Length of array of slotdef pointers used to store slots with the 6775 /* Length of array of slotdef pointers used to store slots with the
6550 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with 6776 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
(...skipping 223 matching lines...) Expand 10 before | Expand all | Expand 10 after
6774 { 7000 {
6775 slotdef *p; 7001 slotdef *p;
6776 7002
6777 init_slotdefs(); 7003 init_slotdefs();
6778 for (p = slotdefs; p->name; p++) { 7004 for (p = slotdefs; p->name; p++) {
6779 /* update_slot returns int but can't actually fail */ 7005 /* update_slot returns int but can't actually fail */
6780 update_slot(type, p->name_strobj); 7006 update_slot(type, p->name_strobj);
6781 } 7007 }
6782 } 7008 }
6783 7009
7010 /* Call __set_name__ on all descriptors in a newly generated type */
7011 static int
7012 set_names(PyTypeObject *type)
7013 {
7014 PyObject *names_to_set, *key, *value, *set_name, *tmp;
7015 Py_ssize_t i = 0;
7016
7017 names_to_set = PyDict_Copy(type->tp_dict);
7018 if (names_to_set == NULL)
7019 return -1;
7020
7021 while (PyDict_Next(names_to_set, &i, &key, &value)) {
7022 set_name = lookup_maybe(value, &PyId___set_name__);
7023 if (set_name != NULL) {
7024 tmp = PyObject_CallFunctionObjArgs(set_name, type, key, NULL);
7025 Py_DECREF(set_name);
7026 if (tmp == NULL) {
7027 _PyErr_FormatFromCause(PyExc_RuntimeError,
7028 "Error calling __set_name__ on '%.100s' instance %R "
7029 "in '%.100s'",
7030 value->ob_type->tp_name, key, type->tp_name);
7031 Py_DECREF(names_to_set);
7032 return -1;
7033 }
7034 else
7035 Py_DECREF(tmp);
7036 }
7037 else if (PyErr_Occurred()) {
7038 Py_DECREF(names_to_set);
7039 return -1;
7040 }
7041 }
7042
7043 Py_DECREF(names_to_set);
7044 return 0;
7045 }
7046
7047 /* Call __init_subclass__ on the parent of a newly generated type */
7048 static int
7049 init_subclass(PyTypeObject *type, PyObject *kwds)
7050 {
7051 PyObject *super, *func, *result;
7052 PyObject *args[2] = {(PyObject *)type, (PyObject *)type};
7053
7054 super = _PyObject_FastCall((PyObject *)&PySuper_Type, args, 2);
7055 if (super == NULL) {
7056 return -1;
7057 }
7058
7059 func = _PyObject_GetAttrId(super, &PyId___init_subclass__);
7060 Py_DECREF(super);
7061 if (func == NULL) {
7062 return -1;
7063 }
7064
7065
7066 result = _PyObject_FastCallDict(func, NULL, 0, kwds);
7067 Py_DECREF(func);
7068 if (result == NULL) {
7069 return -1;
7070 }
7071
7072 Py_DECREF(result);
7073 return 0;
7074 }
7075
6784 /* recurse_down_subclasses() and update_subclasses() are mutually 7076 /* recurse_down_subclasses() and update_subclasses() are mutually
6785 recursive functions to call a callback for all subclasses, 7077 recursive functions to call a callback for all subclasses,
6786 but refraining from recursing into subclasses that define 'name'. */ 7078 but refraining from recursing into subclasses that define 'name'. */
6787 7079
6788 static int 7080 static int
6789 update_subclasses(PyTypeObject *type, PyObject *name, 7081 update_subclasses(PyTypeObject *type, PyObject *name,
6790 update_callback callback, void *data) 7082 update_callback callback, void *data)
6791 { 7083 {
6792 if (callback(type, data) < 0) 7084 if (callback(type, data) < 0)
6793 return -1; 7085 return -1;
(...skipping 82 matching lines...) Expand 10 before | Expand all | Expand 10 after
6876 /* Classes may prevent the inheritance of the tp_hash 7168 /* Classes may prevent the inheritance of the tp_hash
6877 slot by storing PyObject_HashNotImplemented in it. Make it 7169 slot by storing PyObject_HashNotImplemented in it. Make it
6878 visible as a None value for the __hash__ attribute. */ 7170 visible as a None value for the __hash__ attribute. */
6879 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0) 7171 if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
6880 return -1; 7172 return -1;
6881 } 7173 }
6882 else { 7174 else {
6883 descr = PyDescr_NewWrapper(type, p, *ptr); 7175 descr = PyDescr_NewWrapper(type, p, *ptr);
6884 if (descr == NULL) 7176 if (descr == NULL)
6885 return -1; 7177 return -1;
6886 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) 7178 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
7179 Py_DECREF(descr);
6887 return -1; 7180 return -1;
7181 }
6888 Py_DECREF(descr); 7182 Py_DECREF(descr);
6889 } 7183 }
6890 } 7184 }
6891 if (type->tp_new != NULL) { 7185 if (type->tp_new != NULL) {
6892 if (add_tp_new_wrapper(type) < 0) 7186 if (add_tp_new_wrapper(type) < 0)
6893 return -1; 7187 return -1;
6894 } 7188 }
6895 return 0; 7189 return 0;
6896 } 7190 }
6897 7191
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
6952 Py_ssize_t i, n; 7246 Py_ssize_t i, n;
6953 7247
6954 starttype = su->obj_type; 7248 starttype = su->obj_type;
6955 if (starttype == NULL) 7249 if (starttype == NULL)
6956 goto skip; 7250 goto skip;
6957 7251
6958 /* We want __class__ to return the class of the super object 7252 /* We want __class__ to return the class of the super object
6959 (i.e. super, or a subclass), not the class of su->obj. */ 7253 (i.e. super, or a subclass), not the class of su->obj. */
6960 if (PyUnicode_Check(name) && 7254 if (PyUnicode_Check(name) &&
6961 PyUnicode_GET_LENGTH(name) == 9 && 7255 PyUnicode_GET_LENGTH(name) == 9 &&
6962 _PyUnicode_CompareWithId(name, &PyId___class__) == 0) 7256 _PyUnicode_EqualToASCIIId(name, &PyId___class__))
6963 goto skip; 7257 goto skip;
6964 7258
6965 mro = starttype->tp_mro; 7259 mro = starttype->tp_mro;
6966 if (mro == NULL) 7260 if (mro == NULL)
6967 goto skip; 7261 goto skip;
6968 7262
6969 assert(PyTuple_Check(mro)); 7263 assert(PyTuple_Check(mro));
6970 n = PyTuple_GET_SIZE(mro); 7264 n = PyTuple_GET_SIZE(mro);
6971 7265
6972 /* No need to check the last one: it's gonna be skipped anyway. */ 7266 /* No need to check the last one: it's gonna be skipped anyway. */
(...skipping 191 matching lines...) Expand 10 before | Expand all | Expand 10 after
7164 } 7458 }
7165 if (co->co_freevars == NULL) 7459 if (co->co_freevars == NULL)
7166 n = 0; 7460 n = 0;
7167 else { 7461 else {
7168 assert(PyTuple_Check(co->co_freevars)); 7462 assert(PyTuple_Check(co->co_freevars));
7169 n = PyTuple_GET_SIZE(co->co_freevars); 7463 n = PyTuple_GET_SIZE(co->co_freevars);
7170 } 7464 }
7171 for (i = 0; i < n; i++) { 7465 for (i = 0; i < n; i++) {
7172 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); 7466 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
7173 assert(PyUnicode_Check(name)); 7467 assert(PyUnicode_Check(name));
7174 if (!_PyUnicode_CompareWithId(name, &PyId___class__)) { 7468 if (_PyUnicode_EqualToASCIIId(name, &PyId___class__)) {
7175 Py_ssize_t index = co->co_nlocals + 7469 Py_ssize_t index = co->co_nlocals +
7176 PyTuple_GET_SIZE(co->co_cellvars) + i; 7470 PyTuple_GET_SIZE(co->co_cellvars) + i;
7177 PyObject *cell = f->f_localsplus[index]; 7471 PyObject *cell = f->f_localsplus[index];
7178 if (cell == NULL || !PyCell_Check(cell)) { 7472 if (cell == NULL || !PyCell_Check(cell)) {
7179 PyErr_SetString(PyExc_RuntimeError, 7473 PyErr_SetString(PyExc_RuntimeError,
7180 "super(): bad __class__ cell"); 7474 "super(): bad __class__ cell");
7181 return -1; 7475 return -1;
7182 } 7476 }
7183 type = (PyTypeObject *) PyCell_GET(cell); 7477 type = (PyTypeObject *) PyCell_GET(cell);
7184 if (type == NULL) { 7478 if (type == NULL) {
(...skipping 19 matching lines...) Expand all
7204 7498
7205 if (obj == Py_None) 7499 if (obj == Py_None)
7206 obj = NULL; 7500 obj = NULL;
7207 if (obj != NULL) { 7501 if (obj != NULL) {
7208 obj_type = supercheck(type, obj); 7502 obj_type = supercheck(type, obj);
7209 if (obj_type == NULL) 7503 if (obj_type == NULL)
7210 return -1; 7504 return -1;
7211 Py_INCREF(obj); 7505 Py_INCREF(obj);
7212 } 7506 }
7213 Py_INCREF(type); 7507 Py_INCREF(type);
7214 su->type = type; 7508 Py_XSETREF(su->type, type);
7215 su->obj = obj; 7509 Py_XSETREF(su->obj, obj);
7216 su->obj_type = obj_type; 7510 Py_XSETREF(su->obj_type, obj_type);
7217 return 0; 7511 return 0;
7218 } 7512 }
7219 7513
7220 PyDoc_STRVAR(super_doc, 7514 PyDoc_STRVAR(super_doc,
7221 "super() -> same as super(__class__, <first argument>)\n" 7515 "super() -> same as super(__class__, <first argument>)\n"
7222 "super(type) -> unbound super object\n" 7516 "super(type) -> unbound super object\n"
7223 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n" 7517 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
7224 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n" 7518 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
7225 "Typical use to call a cooperative superclass method:\n" 7519 "Typical use to call a cooperative superclass method:\n"
7226 "class C(B):\n" 7520 "class C(B):\n"
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after
7280 0, /* tp_base */ 7574 0, /* tp_base */
7281 0, /* tp_dict */ 7575 0, /* tp_dict */
7282 super_descr_get, /* tp_descr_get */ 7576 super_descr_get, /* tp_descr_get */
7283 0, /* tp_descr_set */ 7577 0, /* tp_descr_set */
7284 0, /* tp_dictoffset */ 7578 0, /* tp_dictoffset */
7285 super_init, /* tp_init */ 7579 super_init, /* tp_init */
7286 PyType_GenericAlloc, /* tp_alloc */ 7580 PyType_GenericAlloc, /* tp_alloc */
7287 PyType_GenericNew, /* tp_new */ 7581 PyType_GenericNew, /* tp_new */
7288 PyObject_GC_Del, /* tp_free */ 7582 PyObject_GC_Del, /* tp_free */
7289 }; 7583 };
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+