typeobject.c revision 2309498595cb5a69547ad87a66b4574971684ec3
1/* Type object implementation */ 2 3#include "Python.h" 4#include "structmember.h" 5 6#include <ctype.h> 7 8/* The *real* layout of a type object when allocated on the heap */ 9/* XXX Should we publish this in a header file? */ 10typedef struct { 11 PyTypeObject type; 12 PyNumberMethods as_number; 13 PySequenceMethods as_sequence; 14 PyMappingMethods as_mapping; 15 PyBufferProcs as_buffer; 16 PyObject *name, *slots; 17 PyMemberDef members[1]; 18} etype; 19 20static PyMemberDef type_members[] = { 21 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY}, 22 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY}, 23 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY}, 24 {"__weakrefoffset__", T_LONG, 25 offsetof(PyTypeObject, tp_weaklistoffset), READONLY}, 26 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY}, 27 {"__dictoffset__", T_LONG, 28 offsetof(PyTypeObject, tp_dictoffset), READONLY}, 29 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY}, 30 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY}, 31 {0} 32}; 33 34static PyObject * 35type_name(PyTypeObject *type, void *context) 36{ 37 char *s; 38 39 s = strrchr(type->tp_name, '.'); 40 if (s == NULL) 41 s = type->tp_name; 42 else 43 s++; 44 return PyString_FromString(s); 45} 46 47static PyObject * 48type_module(PyTypeObject *type, void *context) 49{ 50 PyObject *mod; 51 char *s; 52 53 s = strrchr(type->tp_name, '.'); 54 if (s != NULL) 55 return PyString_FromStringAndSize(type->tp_name, 56 (int)(s - type->tp_name)); 57 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) 58 return PyString_FromString("__builtin__"); 59 mod = PyDict_GetItemString(type->tp_dict, "__module__"); 60 if (mod != NULL && PyString_Check(mod)) { 61 Py_INCREF(mod); 62 return mod; 63 } 64 PyErr_SetString(PyExc_AttributeError, "__module__"); 65 return NULL; 66} 67 68static int 69type_set_module(PyTypeObject *type, PyObject *value, void *context) 70{ 71 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) || 72 strrchr(type->tp_name, '.')) { 73 PyErr_Format(PyExc_TypeError, 74 "can't set %s.__module__", type->tp_name); 75 return -1; 76 } 77 if (!value) { 78 PyErr_Format(PyExc_TypeError, 79 "can't delete %s.__module__", type->tp_name); 80 return -1; 81 } 82 return PyDict_SetItemString(type->tp_dict, "__module__", value); 83} 84 85static PyObject * 86type_dict(PyTypeObject *type, void *context) 87{ 88 if (type->tp_dict == NULL) { 89 Py_INCREF(Py_None); 90 return Py_None; 91 } 92 return PyDictProxy_New(type->tp_dict); 93} 94 95static PyObject * 96type_get_doc(PyTypeObject *type, void *context) 97{ 98 PyObject *result; 99 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) 100 return PyString_FromString(type->tp_doc); 101 result = PyDict_GetItemString(type->tp_dict, "__doc__"); 102 if (result == NULL) { 103 result = Py_None; 104 Py_INCREF(result); 105 } 106 else if (result->ob_type->tp_descr_get) { 107 result = result->ob_type->tp_descr_get(result, NULL, 108 (PyObject *)type); 109 } 110 else { 111 Py_INCREF(result); 112 } 113 return result; 114} 115 116static PyGetSetDef type_getsets[] = { 117 {"__name__", (getter)type_name, NULL, NULL}, 118 {"__module__", (getter)type_module, (setter)type_set_module, NULL}, 119 {"__dict__", (getter)type_dict, NULL, NULL}, 120 {"__doc__", (getter)type_get_doc, NULL, NULL}, 121 {0} 122}; 123 124static int 125type_compare(PyObject *v, PyObject *w) 126{ 127 /* This is called with type objects only. So we 128 can just compare the addresses. */ 129 Py_uintptr_t vv = (Py_uintptr_t)v; 130 Py_uintptr_t ww = (Py_uintptr_t)w; 131 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0; 132} 133 134static PyObject * 135type_repr(PyTypeObject *type) 136{ 137 PyObject *mod, *name, *rtn; 138 char *kind; 139 140 mod = type_module(type, NULL); 141 if (mod == NULL) 142 PyErr_Clear(); 143 else if (!PyString_Check(mod)) { 144 Py_DECREF(mod); 145 mod = NULL; 146 } 147 name = type_name(type, NULL); 148 if (name == NULL) 149 return NULL; 150 151 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) 152 kind = "class"; 153 else 154 kind = "type"; 155 156 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) { 157 rtn = PyString_FromFormat("<%s '%s.%s'>", 158 kind, 159 PyString_AS_STRING(mod), 160 PyString_AS_STRING(name)); 161 } 162 else 163 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name); 164 165 Py_XDECREF(mod); 166 Py_DECREF(name); 167 return rtn; 168} 169 170static PyObject * 171type_call(PyTypeObject *type, PyObject *args, PyObject *kwds) 172{ 173 PyObject *obj; 174 175 if (type->tp_new == NULL) { 176 PyErr_Format(PyExc_TypeError, 177 "cannot create '%.100s' instances", 178 type->tp_name); 179 return NULL; 180 } 181 182 obj = type->tp_new(type, args, kwds); 183 if (obj != NULL) { 184 /* Ugly exception: when the call was type(something), 185 don't call tp_init on the result. */ 186 if (type == &PyType_Type && 187 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && 188 (kwds == NULL || 189 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) 190 return obj; 191 /* If the returned object is not an instance of type, 192 it won't be initialized. */ 193 if (!PyType_IsSubtype(obj->ob_type, type)) 194 return obj; 195 type = obj->ob_type; 196 if (type->tp_init != NULL && 197 type->tp_init(obj, args, kwds) < 0) { 198 Py_DECREF(obj); 199 obj = NULL; 200 } 201 } 202 return obj; 203} 204 205PyObject * 206PyType_GenericAlloc(PyTypeObject *type, int nitems) 207{ 208 PyObject *obj; 209 const size_t size = _PyObject_VAR_SIZE(type, nitems); 210 211 if (PyType_IS_GC(type)) 212 obj = _PyObject_GC_Malloc(size); 213 else 214 obj = PyObject_MALLOC(size); 215 216 if (obj == NULL) 217 return PyErr_NoMemory(); 218 219 memset(obj, '\0', size); 220 221 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) 222 Py_INCREF(type); 223 224 if (type->tp_itemsize == 0) 225 PyObject_INIT(obj, type); 226 else 227 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); 228 229 if (PyType_IS_GC(type)) 230 _PyObject_GC_TRACK(obj); 231 return obj; 232} 233 234PyObject * 235PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) 236{ 237 return type->tp_alloc(type, 0); 238} 239 240/* Helpers for subtyping */ 241 242static int 243traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg) 244{ 245 int i, n; 246 PyMemberDef *mp; 247 248 n = type->ob_size; 249 mp = ((etype *)type)->members; 250 for (i = 0; i < n; i++, mp++) { 251 if (mp->type == T_OBJECT_EX) { 252 char *addr = (char *)self + mp->offset; 253 PyObject *obj = *(PyObject **)addr; 254 if (obj != NULL) { 255 int err = visit(obj, arg); 256 if (err) 257 return err; 258 } 259 } 260 } 261 return 0; 262} 263 264static int 265subtype_traverse(PyObject *self, visitproc visit, void *arg) 266{ 267 PyTypeObject *type, *base; 268 traverseproc basetraverse; 269 270 /* Find the nearest base with a different tp_traverse, 271 and traverse slots while we're at it */ 272 type = self->ob_type; 273 base = type; 274 while ((basetraverse = base->tp_traverse) == subtype_traverse) { 275 if (base->ob_size) { 276 int err = traverse_slots(base, self, visit, arg); 277 if (err) 278 return err; 279 } 280 base = base->tp_base; 281 assert(base); 282 } 283 284 if (type->tp_dictoffset != base->tp_dictoffset) { 285 PyObject **dictptr = _PyObject_GetDictPtr(self); 286 if (dictptr && *dictptr) { 287 int err = visit(*dictptr, arg); 288 if (err) 289 return err; 290 } 291 } 292 293 if (basetraverse) 294 return basetraverse(self, visit, arg); 295 return 0; 296} 297 298static void 299clear_slots(PyTypeObject *type, PyObject *self) 300{ 301 int i, n; 302 PyMemberDef *mp; 303 304 n = type->ob_size; 305 mp = ((etype *)type)->members; 306 for (i = 0; i < n; i++, mp++) { 307 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) { 308 char *addr = (char *)self + mp->offset; 309 PyObject *obj = *(PyObject **)addr; 310 if (obj != NULL) { 311 Py_DECREF(obj); 312 *(PyObject **)addr = NULL; 313 } 314 } 315 } 316} 317 318static int 319subtype_clear(PyObject *self) 320{ 321 PyTypeObject *type, *base; 322 inquiry baseclear; 323 324 /* Find the nearest base with a different tp_clear 325 and clear slots while we're at it */ 326 type = self->ob_type; 327 base = type; 328 while ((baseclear = base->tp_clear) == subtype_clear) { 329 if (base->ob_size) 330 clear_slots(base, self); 331 base = base->tp_base; 332 assert(base); 333 } 334 335 if (type->tp_dictoffset != base->tp_dictoffset) { 336 PyObject **dictptr = _PyObject_GetDictPtr(self); 337 if (dictptr && *dictptr) { 338 PyDict_Clear(*dictptr); 339 } 340 } 341 342 if (baseclear) 343 return baseclear(self); 344 return 0; 345} 346 347staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **); 348 349static int 350call_finalizer(PyObject *self) 351{ 352 static PyObject *del_str = NULL; 353 PyObject *del, *res; 354 PyObject *error_type, *error_value, *error_traceback; 355 356 /* Temporarily resurrect the object. */ 357#ifdef Py_TRACE_REFS 358#ifndef Py_REF_DEBUG 359# error "Py_TRACE_REFS defined but Py_REF_DEBUG not." 360#endif 361 /* much too complicated if Py_TRACE_REFS defined */ 362 _Py_NewReference((PyObject *)self); 363#ifdef COUNT_ALLOCS 364 /* compensate for boost in _Py_NewReference; note that 365 * _Py_RefTotal was also boosted; we'll knock that down later. 366 */ 367 self->ob_type->tp_allocs--; 368#endif 369#else /* !Py_TRACE_REFS */ 370 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */ 371 Py_INCREF(self); 372#endif /* !Py_TRACE_REFS */ 373 374 /* Save the current exception, if any. */ 375 PyErr_Fetch(&error_type, &error_value, &error_traceback); 376 377 /* Execute __del__ method, if any. */ 378 del = lookup_maybe(self, "__del__", &del_str); 379 if (del != NULL) { 380 res = PyEval_CallObject(del, NULL); 381 if (res == NULL) 382 PyErr_WriteUnraisable(del); 383 else 384 Py_DECREF(res); 385 Py_DECREF(del); 386 } 387 388 /* Restore the saved exception. */ 389 PyErr_Restore(error_type, error_value, error_traceback); 390 391 /* Undo the temporary resurrection; can't use DECREF here, it would 392 * cause a recursive call. 393 */ 394#ifdef Py_REF_DEBUG 395 /* _Py_RefTotal was boosted either by _Py_NewReference or 396 * Py_INCREF above. 397 */ 398 _Py_RefTotal--; 399#endif 400 if (--self->ob_refcnt > 0) { 401#ifdef COUNT_ALLOCS 402 self->ob_type->tp_frees--; 403#endif 404 _PyObject_GC_TRACK(self); 405 return -1; /* __del__ added a reference; don't delete now */ 406 } 407#ifdef Py_TRACE_REFS 408 _Py_ForgetReference((PyObject *)self); 409#ifdef COUNT_ALLOCS 410 /* compensate for increment in _Py_ForgetReference */ 411 self->ob_type->tp_frees--; 412#endif 413#endif 414 415 return 0; 416} 417 418static void 419subtype_dealloc(PyObject *self) 420{ 421 PyTypeObject *type, *base; 422 destructor basedealloc; 423 424 /* This exists so we can DECREF self->ob_type */ 425 426 if (call_finalizer(self) < 0) 427 return; 428 429 /* Find the nearest base with a different tp_dealloc 430 and clear slots while we're at it */ 431 type = self->ob_type; 432 base = type; 433 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { 434 if (base->ob_size) 435 clear_slots(base, self); 436 base = base->tp_base; 437 assert(base); 438 } 439 440 /* If we added a dict, DECREF it */ 441 if (type->tp_dictoffset && !base->tp_dictoffset) { 442 PyObject **dictptr = _PyObject_GetDictPtr(self); 443 if (dictptr != NULL) { 444 PyObject *dict = *dictptr; 445 if (dict != NULL) { 446 Py_DECREF(dict); 447 *dictptr = NULL; 448 } 449 } 450 } 451 452 /* If we added weaklist, we clear it */ 453 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) 454 PyObject_ClearWeakRefs(self); 455 456 /* Finalize GC if the base doesn't do GC and we do */ 457 if (PyType_IS_GC(type) && !PyType_IS_GC(base)) 458 _PyObject_GC_UNTRACK(self); 459 460 /* Call the base tp_dealloc() */ 461 assert(basedealloc); 462 basedealloc(self); 463 464 /* Can't reference self beyond this point */ 465 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { 466 Py_DECREF(type); 467 } 468} 469 470staticforward PyTypeObject *solid_base(PyTypeObject *type); 471 472/* type test with subclassing support */ 473 474int 475PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) 476{ 477 PyObject *mro; 478 479 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS)) 480 return b == a || b == &PyBaseObject_Type; 481 482 mro = a->tp_mro; 483 if (mro != NULL) { 484 /* Deal with multiple inheritance without recursion 485 by walking the MRO tuple */ 486 int i, n; 487 assert(PyTuple_Check(mro)); 488 n = PyTuple_GET_SIZE(mro); 489 for (i = 0; i < n; i++) { 490 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) 491 return 1; 492 } 493 return 0; 494 } 495 else { 496 /* a is not completely initilized yet; follow tp_base */ 497 do { 498 if (a == b) 499 return 1; 500 a = a->tp_base; 501 } while (a != NULL); 502 return b == &PyBaseObject_Type; 503 } 504} 505 506/* Internal routines to do a method lookup in the type 507 without looking in the instance dictionary 508 (so we can't use PyObject_GetAttr) but still binding 509 it to the instance. The arguments are the object, 510 the method name as a C string, and the address of a 511 static variable used to cache the interned Python string. 512 513 Two variants: 514 515 - lookup_maybe() returns NULL without raising an exception 516 when the _PyType_Lookup() call fails; 517 518 - lookup_method() always raises an exception upon errors. 519*/ 520 521static PyObject * 522lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj) 523{ 524 PyObject *res; 525 526 if (*attrobj == NULL) { 527 *attrobj = PyString_InternFromString(attrstr); 528 if (*attrobj == NULL) 529 return NULL; 530 } 531 res = _PyType_Lookup(self->ob_type, *attrobj); 532 if (res != NULL) { 533 descrgetfunc f; 534 if ((f = res->ob_type->tp_descr_get) == NULL) 535 Py_INCREF(res); 536 else 537 res = f(res, self, (PyObject *)(self->ob_type)); 538 } 539 return res; 540} 541 542static PyObject * 543lookup_method(PyObject *self, char *attrstr, PyObject **attrobj) 544{ 545 PyObject *res = lookup_maybe(self, attrstr, attrobj); 546 if (res == NULL && !PyErr_Occurred()) 547 PyErr_SetObject(PyExc_AttributeError, *attrobj); 548 return res; 549} 550 551/* A variation of PyObject_CallMethod that uses lookup_method() 552 instead of PyObject_GetAttrString(). This uses the same convention 553 as lookup_method to cache the interned name string object. */ 554 555static PyObject * 556call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...) 557{ 558 va_list va; 559 PyObject *args, *func = 0, *retval; 560 va_start(va, format); 561 562 func = lookup_maybe(o, name, nameobj); 563 if (func == NULL) { 564 va_end(va); 565 if (!PyErr_Occurred()) 566 PyErr_SetObject(PyExc_AttributeError, *nameobj); 567 return NULL; 568 } 569 570 if (format && *format) 571 args = Py_VaBuildValue(format, va); 572 else 573 args = PyTuple_New(0); 574 575 va_end(va); 576 577 if (args == NULL) 578 return NULL; 579 580 assert(PyTuple_Check(args)); 581 retval = PyObject_Call(func, args, NULL); 582 583 Py_DECREF(args); 584 Py_DECREF(func); 585 586 return retval; 587} 588 589/* Clone of call_method() that returns NotImplemented when the lookup fails. */ 590 591static PyObject * 592call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...) 593{ 594 va_list va; 595 PyObject *args, *func = 0, *retval; 596 va_start(va, format); 597 598 func = lookup_maybe(o, name, nameobj); 599 if (func == NULL) { 600 va_end(va); 601 if (!PyErr_Occurred()) { 602 Py_INCREF(Py_NotImplemented); 603 return Py_NotImplemented; 604 } 605 return NULL; 606 } 607 608 if (format && *format) 609 args = Py_VaBuildValue(format, va); 610 else 611 args = PyTuple_New(0); 612 613 va_end(va); 614 615 if (args == NULL) 616 return NULL; 617 618 assert(PyTuple_Check(args)); 619 retval = PyObject_Call(func, args, NULL); 620 621 Py_DECREF(args); 622 Py_DECREF(func); 623 624 return retval; 625} 626 627/* Method resolution order algorithm from "Putting Metaclasses to Work" 628 by Forman and Danforth (Addison-Wesley 1999). */ 629 630static int 631conservative_merge(PyObject *left, PyObject *right) 632{ 633 int left_size; 634 int right_size; 635 int i, j, r, ok; 636 PyObject *temp, *rr; 637 638 assert(PyList_Check(left)); 639 assert(PyList_Check(right)); 640 641 again: 642 left_size = PyList_GET_SIZE(left); 643 right_size = PyList_GET_SIZE(right); 644 for (i = 0; i < left_size; i++) { 645 for (j = 0; j < right_size; j++) { 646 if (PyList_GET_ITEM(left, i) == 647 PyList_GET_ITEM(right, j)) { 648 /* found a merge point */ 649 temp = PyList_New(0); 650 if (temp == NULL) 651 return -1; 652 for (r = 0; r < j; r++) { 653 rr = PyList_GET_ITEM(right, r); 654 ok = PySequence_Contains(left, rr); 655 if (ok < 0) { 656 Py_DECREF(temp); 657 return -1; 658 } 659 if (!ok) { 660 ok = PyList_Append(temp, rr); 661 if (ok < 0) { 662 Py_DECREF(temp); 663 return -1; 664 } 665 } 666 } 667 ok = PyList_SetSlice(left, i, i, temp); 668 Py_DECREF(temp); 669 if (ok < 0) 670 return -1; 671 ok = PyList_SetSlice(right, 0, j+1, NULL); 672 if (ok < 0) 673 return -1; 674 goto again; 675 } 676 } 677 } 678 return PyList_SetSlice(left, left_size, left_size, right); 679} 680 681static int 682serious_order_disagreements(PyObject *left, PyObject *right) 683{ 684 return 0; /* XXX later -- for now, we cheat: "don't do that" */ 685} 686 687static int 688fill_classic_mro(PyObject *mro, PyObject *cls) 689{ 690 PyObject *bases, *base; 691 int i, n; 692 693 assert(PyList_Check(mro)); 694 assert(PyClass_Check(cls)); 695 i = PySequence_Contains(mro, cls); 696 if (i < 0) 697 return -1; 698 if (!i) { 699 if (PyList_Append(mro, cls) < 0) 700 return -1; 701 } 702 bases = ((PyClassObject *)cls)->cl_bases; 703 assert(bases && PyTuple_Check(bases)); 704 n = PyTuple_GET_SIZE(bases); 705 for (i = 0; i < n; i++) { 706 base = PyTuple_GET_ITEM(bases, i); 707 if (fill_classic_mro(mro, base) < 0) 708 return -1; 709 } 710 return 0; 711} 712 713static PyObject * 714classic_mro(PyObject *cls) 715{ 716 PyObject *mro; 717 718 assert(PyClass_Check(cls)); 719 mro = PyList_New(0); 720 if (mro != NULL) { 721 if (fill_classic_mro(mro, cls) == 0) 722 return mro; 723 Py_DECREF(mro); 724 } 725 return NULL; 726} 727 728static PyObject * 729mro_implementation(PyTypeObject *type) 730{ 731 int i, n, ok; 732 PyObject *bases, *result; 733 734 bases = type->tp_bases; 735 n = PyTuple_GET_SIZE(bases); 736 result = Py_BuildValue("[O]", (PyObject *)type); 737 if (result == NULL) 738 return NULL; 739 for (i = 0; i < n; i++) { 740 PyObject *base = PyTuple_GET_ITEM(bases, i); 741 PyObject *parentMRO; 742 if (PyType_Check(base)) 743 parentMRO = PySequence_List( 744 ((PyTypeObject*)base)->tp_mro); 745 else 746 parentMRO = classic_mro(base); 747 if (parentMRO == NULL) { 748 Py_DECREF(result); 749 return NULL; 750 } 751 if (serious_order_disagreements(result, parentMRO)) { 752 Py_DECREF(result); 753 return NULL; 754 } 755 ok = conservative_merge(result, parentMRO); 756 Py_DECREF(parentMRO); 757 if (ok < 0) { 758 Py_DECREF(result); 759 return NULL; 760 } 761 } 762 return result; 763} 764 765static PyObject * 766mro_external(PyObject *self) 767{ 768 PyTypeObject *type = (PyTypeObject *)self; 769 770 return mro_implementation(type); 771} 772 773static int 774mro_internal(PyTypeObject *type) 775{ 776 PyObject *mro, *result, *tuple; 777 778 if (type->ob_type == &PyType_Type) { 779 result = mro_implementation(type); 780 } 781 else { 782 static PyObject *mro_str; 783 mro = lookup_method((PyObject *)type, "mro", &mro_str); 784 if (mro == NULL) 785 return -1; 786 result = PyObject_CallObject(mro, NULL); 787 Py_DECREF(mro); 788 } 789 if (result == NULL) 790 return -1; 791 tuple = PySequence_Tuple(result); 792 Py_DECREF(result); 793 type->tp_mro = tuple; 794 return 0; 795} 796 797 798/* Calculate the best base amongst multiple base classes. 799 This is the first one that's on the path to the "solid base". */ 800 801static PyTypeObject * 802best_base(PyObject *bases) 803{ 804 int i, n; 805 PyTypeObject *base, *winner, *candidate, *base_i; 806 PyObject *base_proto; 807 808 assert(PyTuple_Check(bases)); 809 n = PyTuple_GET_SIZE(bases); 810 assert(n > 0); 811 base = NULL; 812 winner = NULL; 813 for (i = 0; i < n; i++) { 814 base_proto = PyTuple_GET_ITEM(bases, i); 815 if (PyClass_Check(base_proto)) 816 continue; 817 if (!PyType_Check(base_proto)) { 818 PyErr_SetString( 819 PyExc_TypeError, 820 "bases must be types"); 821 return NULL; 822 } 823 base_i = (PyTypeObject *)base_proto; 824 if (base_i->tp_dict == NULL) { 825 if (PyType_Ready(base_i) < 0) 826 return NULL; 827 } 828 candidate = solid_base(base_i); 829 if (winner == NULL) { 830 winner = candidate; 831 base = base_i; 832 } 833 else if (PyType_IsSubtype(winner, candidate)) 834 ; 835 else if (PyType_IsSubtype(candidate, winner)) { 836 winner = candidate; 837 base = base_i; 838 } 839 else { 840 PyErr_SetString( 841 PyExc_TypeError, 842 "multiple bases have " 843 "instance lay-out conflict"); 844 return NULL; 845 } 846 } 847 if (base == NULL) 848 PyErr_SetString(PyExc_TypeError, 849 "a new-style class can't have only classic bases"); 850 return base; 851} 852 853static int 854extra_ivars(PyTypeObject *type, PyTypeObject *base) 855{ 856 size_t t_size = type->tp_basicsize; 857 size_t b_size = base->tp_basicsize; 858 859 assert(t_size >= b_size); /* Else type smaller than base! */ 860 if (type->tp_itemsize || base->tp_itemsize) { 861 /* If itemsize is involved, stricter rules */ 862 return t_size != b_size || 863 type->tp_itemsize != base->tp_itemsize; 864 } 865 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && 866 type->tp_weaklistoffset + sizeof(PyObject *) == t_size) 867 t_size -= sizeof(PyObject *); 868 if (type->tp_dictoffset && base->tp_dictoffset == 0 && 869 type->tp_dictoffset + sizeof(PyObject *) == t_size) 870 t_size -= sizeof(PyObject *); 871 872 return t_size != b_size; 873} 874 875static PyTypeObject * 876solid_base(PyTypeObject *type) 877{ 878 PyTypeObject *base; 879 880 if (type->tp_base) 881 base = solid_base(type->tp_base); 882 else 883 base = &PyBaseObject_Type; 884 if (extra_ivars(type, base)) 885 return type; 886 else 887 return base; 888} 889 890staticforward void object_dealloc(PyObject *); 891staticforward int object_init(PyObject *, PyObject *, PyObject *); 892staticforward int update_slot(PyTypeObject *, PyObject *); 893staticforward void fixup_slot_dispatchers(PyTypeObject *); 894 895static PyObject * 896subtype_dict(PyObject *obj, void *context) 897{ 898 PyObject **dictptr = _PyObject_GetDictPtr(obj); 899 PyObject *dict; 900 901 if (dictptr == NULL) { 902 PyErr_SetString(PyExc_AttributeError, 903 "This object has no __dict__"); 904 return NULL; 905 } 906 dict = *dictptr; 907 if (dict == NULL) 908 *dictptr = dict = PyDict_New(); 909 Py_XINCREF(dict); 910 return dict; 911} 912 913static int 914subtype_setdict(PyObject *obj, PyObject *value, void *context) 915{ 916 PyObject **dictptr = _PyObject_GetDictPtr(obj); 917 PyObject *dict; 918 919 if (dictptr == NULL) { 920 PyErr_SetString(PyExc_AttributeError, 921 "This object has no __dict__"); 922 return -1; 923 } 924 if (value != NULL && !PyDict_Check(value)) { 925 PyErr_SetString(PyExc_TypeError, 926 "__dict__ must be set to a dictionary"); 927 return -1; 928 } 929 dict = *dictptr; 930 Py_XINCREF(value); 931 *dictptr = value; 932 Py_XDECREF(dict); 933 return 0; 934} 935 936static PyGetSetDef subtype_getsets[] = { 937 {"__dict__", subtype_dict, subtype_setdict, NULL}, 938 {0}, 939}; 940 941/* bozo: __getstate__ that raises TypeError */ 942 943static PyObject * 944bozo_func(PyObject *self, PyObject *args) 945{ 946 PyErr_SetString(PyExc_TypeError, 947 "a class that defines __slots__ without " 948 "defining __getstate__ cannot be pickled"); 949 return NULL; 950} 951 952static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS}; 953 954static PyObject *bozo_obj = NULL; 955 956static int 957valid_identifier(PyObject *s) 958{ 959 char *p; 960 int i, n; 961 962 if (!PyString_Check(s)) { 963 PyErr_SetString(PyExc_TypeError, 964 "__slots__ must be strings"); 965 return 0; 966 } 967 p = PyString_AS_STRING(s); 968 n = PyString_GET_SIZE(s); 969 /* We must reject an empty name. As a hack, we bump the 970 length to 1 so that the loop will balk on the trailing \0. */ 971 if (n == 0) 972 n = 1; 973 for (i = 0; i < n; i++, p++) { 974 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') { 975 PyErr_SetString(PyExc_TypeError, 976 "__slots__ must be identifiers"); 977 return 0; 978 } 979 } 980 return 1; 981} 982 983static PyObject * 984type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) 985{ 986 PyObject *name, *bases, *dict; 987 static char *kwlist[] = {"name", "bases", "dict", 0}; 988 PyObject *slots, *tmp; 989 PyTypeObject *type, *base, *tmptype, *winner; 990 etype *et; 991 PyMemberDef *mp; 992 int i, nbases, nslots, slotoffset, add_dict, add_weak; 993 994 assert(args != NULL && PyTuple_Check(args)); 995 assert(kwds == NULL || PyDict_Check(kwds)); 996 997 /* Special case: type(x) should return x->ob_type */ 998 { 999 const int nargs = PyTuple_GET_SIZE(args); 1000 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); 1001 1002 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { 1003 PyObject *x = PyTuple_GET_ITEM(args, 0); 1004 Py_INCREF(x->ob_type); 1005 return (PyObject *) x->ob_type; 1006 } 1007 1008 /* SF bug 475327 -- if that didn't trigger, we need 3 1009 arguments. but PyArg_ParseTupleAndKeywords below may give 1010 a msg saying type() needs exactly 3. */ 1011 if (nargs + nkwds != 3) { 1012 PyErr_SetString(PyExc_TypeError, 1013 "type() takes 1 or 3 arguments"); 1014 return NULL; 1015 } 1016 } 1017 1018 /* Check arguments: (name, bases, dict) */ 1019 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist, 1020 &name, 1021 &PyTuple_Type, &bases, 1022 &PyDict_Type, &dict)) 1023 return NULL; 1024 1025 /* Determine the proper metatype to deal with this, 1026 and check for metatype conflicts while we're at it. 1027 Note that if some other metatype wins to contract, 1028 it's possible that its instances are not types. */ 1029 nbases = PyTuple_GET_SIZE(bases); 1030 winner = metatype; 1031 for (i = 0; i < nbases; i++) { 1032 tmp = PyTuple_GET_ITEM(bases, i); 1033 tmptype = tmp->ob_type; 1034 if (tmptype == &PyClass_Type) 1035 continue; /* Special case classic classes */ 1036 if (PyType_IsSubtype(winner, tmptype)) 1037 continue; 1038 if (PyType_IsSubtype(tmptype, winner)) { 1039 winner = tmptype; 1040 continue; 1041 } 1042 PyErr_SetString(PyExc_TypeError, 1043 "metatype conflict among bases"); 1044 return NULL; 1045 } 1046 if (winner != metatype) { 1047 if (winner->tp_new != type_new) /* Pass it to the winner */ 1048 return winner->tp_new(winner, args, kwds); 1049 metatype = winner; 1050 } 1051 1052 /* Adjust for empty tuple bases */ 1053 if (nbases == 0) { 1054 bases = Py_BuildValue("(O)", &PyBaseObject_Type); 1055 if (bases == NULL) 1056 return NULL; 1057 nbases = 1; 1058 } 1059 else 1060 Py_INCREF(bases); 1061 1062 /* XXX From here until type is allocated, "return NULL" leaks bases! */ 1063 1064 /* Calculate best base, and check that all bases are type objects */ 1065 base = best_base(bases); 1066 if (base == NULL) 1067 return NULL; 1068 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { 1069 PyErr_Format(PyExc_TypeError, 1070 "type '%.100s' is not an acceptable base type", 1071 base->tp_name); 1072 return NULL; 1073 } 1074 1075 /* Check for a __slots__ sequence variable in dict, and count it */ 1076 slots = PyDict_GetItemString(dict, "__slots__"); 1077 nslots = 0; 1078 add_dict = 0; 1079 add_weak = 0; 1080 if (slots != NULL) { 1081 /* Make it into a tuple */ 1082 if (PyString_Check(slots)) 1083 slots = Py_BuildValue("(O)", slots); 1084 else 1085 slots = PySequence_Tuple(slots); 1086 if (slots == NULL) 1087 return NULL; 1088 nslots = PyTuple_GET_SIZE(slots); 1089 if (nslots > 0 && base->tp_itemsize != 0) { 1090 PyErr_Format(PyExc_TypeError, 1091 "nonempty __slots__ " 1092 "not supported for subtype of '%s'", 1093 base->tp_name); 1094 return NULL; 1095 } 1096 for (i = 0; i < nslots; i++) { 1097 if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) { 1098 Py_DECREF(slots); 1099 return NULL; 1100 } 1101 } 1102 } 1103 if (slots != NULL) { 1104 /* See if *this* class defines __getstate__ */ 1105 PyObject *getstate = PyDict_GetItemString(dict, 1106 "__getstate__"); 1107 if (getstate == NULL) { 1108 /* If not, provide a bozo that raises TypeError */ 1109 if (bozo_obj == NULL) { 1110 bozo_obj = PyCFunction_New(&bozo_ml, NULL); 1111 if (bozo_obj == NULL) { 1112 /* XXX decref various things */ 1113 return NULL; 1114 } 1115 } 1116 if (PyDict_SetItemString(dict, 1117 "__getstate__", 1118 bozo_obj) < 0) { 1119 /* XXX decref various things */ 1120 return NULL; 1121 } 1122 } 1123 } 1124 if (slots == NULL && base->tp_dictoffset == 0 && 1125 (base->tp_setattro == PyObject_GenericSetAttr || 1126 base->tp_setattro == NULL)) { 1127 add_dict++; 1128 } 1129 if (slots == NULL && base->tp_weaklistoffset == 0 && 1130 base->tp_itemsize == 0) { 1131 nslots++; 1132 add_weak++; 1133 } 1134 1135 /* XXX From here until type is safely allocated, 1136 "return NULL" may leak slots! */ 1137 1138 /* Allocate the type object */ 1139 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots); 1140 if (type == NULL) 1141 return NULL; 1142 1143 /* Keep name and slots alive in the extended type object */ 1144 et = (etype *)type; 1145 Py_INCREF(name); 1146 et->name = name; 1147 et->slots = slots; 1148 1149 /* Initialize tp_flags */ 1150 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | 1151 Py_TPFLAGS_BASETYPE; 1152 if (base->tp_flags & Py_TPFLAGS_HAVE_GC) 1153 type->tp_flags |= Py_TPFLAGS_HAVE_GC; 1154 1155 /* It's a new-style number unless it specifically inherits any 1156 old-style numeric behavior */ 1157 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) || 1158 (base->tp_as_number == NULL)) 1159 type->tp_flags |= Py_TPFLAGS_CHECKTYPES; 1160 1161 /* Initialize essential fields */ 1162 type->tp_as_number = &et->as_number; 1163 type->tp_as_sequence = &et->as_sequence; 1164 type->tp_as_mapping = &et->as_mapping; 1165 type->tp_as_buffer = &et->as_buffer; 1166 type->tp_name = PyString_AS_STRING(name); 1167 1168 /* Set tp_base and tp_bases */ 1169 type->tp_bases = bases; 1170 Py_INCREF(base); 1171 type->tp_base = base; 1172 1173 /* Initialize tp_dict from passed-in dict */ 1174 type->tp_dict = dict = PyDict_Copy(dict); 1175 if (dict == NULL) { 1176 Py_DECREF(type); 1177 return NULL; 1178 } 1179 1180 /* Set __module__ in the dict */ 1181 if (PyDict_GetItemString(dict, "__module__") == NULL) { 1182 tmp = PyEval_GetGlobals(); 1183 if (tmp != NULL) { 1184 tmp = PyDict_GetItemString(tmp, "__name__"); 1185 if (tmp != NULL) { 1186 if (PyDict_SetItemString(dict, "__module__", 1187 tmp) < 0) 1188 return NULL; 1189 } 1190 } 1191 } 1192 1193 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there 1194 and is a string. The __doc__ accessor will first look for tp_doc; 1195 if that fails, it will still look into __dict__. 1196 */ 1197 { 1198 PyObject *doc = PyDict_GetItemString(dict, "__doc__"); 1199 if (doc != NULL && PyString_Check(doc)) { 1200 const size_t n = (size_t)PyString_GET_SIZE(doc); 1201 type->tp_doc = (char *)PyObject_MALLOC(n+1); 1202 if (type->tp_doc == NULL) { 1203 Py_DECREF(type); 1204 return NULL; 1205 } 1206 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1); 1207 } 1208 } 1209 1210 /* Special-case __new__: if it's a plain function, 1211 make it a static function */ 1212 tmp = PyDict_GetItemString(dict, "__new__"); 1213 if (tmp != NULL && PyFunction_Check(tmp)) { 1214 tmp = PyStaticMethod_New(tmp); 1215 if (tmp == NULL) { 1216 Py_DECREF(type); 1217 return NULL; 1218 } 1219 PyDict_SetItemString(dict, "__new__", tmp); 1220 Py_DECREF(tmp); 1221 } 1222 1223 /* Add descriptors for custom slots from __slots__, or for __dict__ */ 1224 mp = et->members; 1225 slotoffset = base->tp_basicsize; 1226 if (slots != NULL) { 1227 for (i = 0; i < nslots; i++, mp++) { 1228 mp->name = PyString_AS_STRING( 1229 PyTuple_GET_ITEM(slots, i)); 1230 mp->type = T_OBJECT_EX; 1231 mp->offset = slotoffset; 1232 if (base->tp_weaklistoffset == 0 && 1233 strcmp(mp->name, "__weakref__") == 0) { 1234 mp->type = T_OBJECT; 1235 mp->flags = READONLY; 1236 type->tp_weaklistoffset = slotoffset; 1237 } 1238 slotoffset += sizeof(PyObject *); 1239 } 1240 } 1241 else { 1242 if (add_dict) { 1243 if (base->tp_itemsize) 1244 type->tp_dictoffset = 1245 -(long)sizeof(PyObject *); 1246 else 1247 type->tp_dictoffset = slotoffset; 1248 slotoffset += sizeof(PyObject *); 1249 type->tp_getset = subtype_getsets; 1250 } 1251 if (add_weak) { 1252 assert(!base->tp_itemsize); 1253 type->tp_weaklistoffset = slotoffset; 1254 mp->name = "__weakref__"; 1255 mp->type = T_OBJECT; 1256 mp->offset = slotoffset; 1257 mp->flags = READONLY; 1258 mp++; 1259 slotoffset += sizeof(PyObject *); 1260 } 1261 } 1262 type->tp_basicsize = slotoffset; 1263 type->tp_itemsize = base->tp_itemsize; 1264 type->tp_members = et->members; 1265 1266 /* Special case some slots */ 1267 if (type->tp_dictoffset != 0 || nslots > 0) { 1268 if (base->tp_getattr == NULL && base->tp_getattro == NULL) 1269 type->tp_getattro = PyObject_GenericGetAttr; 1270 if (base->tp_setattr == NULL && base->tp_setattro == NULL) 1271 type->tp_setattro = PyObject_GenericSetAttr; 1272 } 1273 type->tp_dealloc = subtype_dealloc; 1274 1275 /* Enable GC unless there are really no instance variables possible */ 1276 if (!(type->tp_basicsize == sizeof(PyObject) && 1277 type->tp_itemsize == 0)) 1278 type->tp_flags |= Py_TPFLAGS_HAVE_GC; 1279 1280 /* Always override allocation strategy to use regular heap */ 1281 type->tp_alloc = PyType_GenericAlloc; 1282 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { 1283 type->tp_free = PyObject_GC_Del; 1284 type->tp_traverse = subtype_traverse; 1285 type->tp_clear = subtype_clear; 1286 } 1287 else 1288 type->tp_free = PyObject_Del; 1289 1290 /* Initialize the rest */ 1291 if (PyType_Ready(type) < 0) { 1292 Py_DECREF(type); 1293 return NULL; 1294 } 1295 1296 /* Put the proper slots in place */ 1297 fixup_slot_dispatchers(type); 1298 1299 return (PyObject *)type; 1300} 1301 1302/* Internal API to look for a name through the MRO. 1303 This returns a borrowed reference, and doesn't set an exception! */ 1304PyObject * 1305_PyType_Lookup(PyTypeObject *type, PyObject *name) 1306{ 1307 int i, n; 1308 PyObject *mro, *res, *base, *dict; 1309 1310 /* Look in tp_dict of types in MRO */ 1311 mro = type->tp_mro; 1312 1313 /* If mro is NULL, the type is either not yet initialized 1314 by PyType_Ready(), or already cleared by type_clear(). 1315 Either way the safest thing to do is to return NULL. */ 1316 if (mro == NULL) 1317 return NULL; 1318 1319 assert(PyTuple_Check(mro)); 1320 n = PyTuple_GET_SIZE(mro); 1321 for (i = 0; i < n; i++) { 1322 base = PyTuple_GET_ITEM(mro, i); 1323 if (PyClass_Check(base)) 1324 dict = ((PyClassObject *)base)->cl_dict; 1325 else { 1326 assert(PyType_Check(base)); 1327 dict = ((PyTypeObject *)base)->tp_dict; 1328 } 1329 assert(dict && PyDict_Check(dict)); 1330 res = PyDict_GetItem(dict, name); 1331 if (res != NULL) 1332 return res; 1333 } 1334 return NULL; 1335} 1336 1337/* This is similar to PyObject_GenericGetAttr(), 1338 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */ 1339static PyObject * 1340type_getattro(PyTypeObject *type, PyObject *name) 1341{ 1342 PyTypeObject *metatype = type->ob_type; 1343 PyObject *meta_attribute, *attribute; 1344 descrgetfunc meta_get; 1345 1346 /* Initialize this type (we'll assume the metatype is initialized) */ 1347 if (type->tp_dict == NULL) { 1348 if (PyType_Ready(type) < 0) 1349 return NULL; 1350 } 1351 1352 /* No readable descriptor found yet */ 1353 meta_get = NULL; 1354 1355 /* Look for the attribute in the metatype */ 1356 meta_attribute = _PyType_Lookup(metatype, name); 1357 1358 if (meta_attribute != NULL) { 1359 meta_get = meta_attribute->ob_type->tp_descr_get; 1360 1361 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { 1362 /* Data descriptors implement tp_descr_set to intercept 1363 * writes. Assume the attribute is not overridden in 1364 * type's tp_dict (and bases): call the descriptor now. 1365 */ 1366 return meta_get(meta_attribute, (PyObject *)type, 1367 (PyObject *)metatype); 1368 } 1369 } 1370 1371 /* No data descriptor found on metatype. Look in tp_dict of this 1372 * type and its bases */ 1373 attribute = _PyType_Lookup(type, name); 1374 if (attribute != NULL) { 1375 /* Implement descriptor functionality, if any */ 1376 descrgetfunc local_get = attribute->ob_type->tp_descr_get; 1377 if (local_get != NULL) { 1378 /* NULL 2nd argument indicates the descriptor was 1379 * found on the target object itself (or a base) */ 1380 return local_get(attribute, (PyObject *)NULL, 1381 (PyObject *)type); 1382 } 1383 1384 Py_INCREF(attribute); 1385 return attribute; 1386 } 1387 1388 /* No attribute found in local __dict__ (or bases): use the 1389 * descriptor from the metatype, if any */ 1390 if (meta_get != NULL) 1391 return meta_get(meta_attribute, (PyObject *)type, 1392 (PyObject *)metatype); 1393 1394 /* If an ordinary attribute was found on the metatype, return it now */ 1395 if (meta_attribute != NULL) { 1396 Py_INCREF(meta_attribute); 1397 return meta_attribute; 1398 } 1399 1400 /* Give up */ 1401 PyErr_Format(PyExc_AttributeError, 1402 "type object '%.50s' has no attribute '%.400s'", 1403 type->tp_name, PyString_AS_STRING(name)); 1404 return NULL; 1405} 1406 1407static int 1408type_setattro(PyTypeObject *type, PyObject *name, PyObject *value) 1409{ 1410 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { 1411 PyErr_Format( 1412 PyExc_TypeError, 1413 "can't set attributes of built-in/extension type '%s'", 1414 type->tp_name); 1415 return -1; 1416 } 1417 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0) 1418 return -1; 1419 return update_slot(type, name); 1420} 1421 1422static void 1423type_dealloc(PyTypeObject *type) 1424{ 1425 etype *et; 1426 1427 /* Assert this is a heap-allocated type object */ 1428 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); 1429 _PyObject_GC_UNTRACK(type); 1430 PyObject_ClearWeakRefs((PyObject *)type); 1431 et = (etype *)type; 1432 Py_XDECREF(type->tp_base); 1433 Py_XDECREF(type->tp_dict); 1434 Py_XDECREF(type->tp_bases); 1435 Py_XDECREF(type->tp_mro); 1436 Py_XDECREF(type->tp_cache); 1437 Py_XDECREF(type->tp_subclasses); 1438 Py_XDECREF(et->name); 1439 Py_XDECREF(et->slots); 1440 type->ob_type->tp_free((PyObject *)type); 1441} 1442 1443static PyObject * 1444type_subclasses(PyTypeObject *type, PyObject *args_ignored) 1445{ 1446 PyObject *list, *raw, *ref; 1447 int i, n; 1448 1449 list = PyList_New(0); 1450 if (list == NULL) 1451 return NULL; 1452 raw = type->tp_subclasses; 1453 if (raw == NULL) 1454 return list; 1455 assert(PyList_Check(raw)); 1456 n = PyList_GET_SIZE(raw); 1457 for (i = 0; i < n; i++) { 1458 ref = PyList_GET_ITEM(raw, i); 1459 assert(PyWeakref_CheckRef(ref)); 1460 ref = PyWeakref_GET_OBJECT(ref); 1461 if (ref != Py_None) { 1462 if (PyList_Append(list, ref) < 0) { 1463 Py_DECREF(list); 1464 return NULL; 1465 } 1466 } 1467 } 1468 return list; 1469} 1470 1471static PyMethodDef type_methods[] = { 1472 {"mro", (PyCFunction)mro_external, METH_NOARGS, 1473 "mro() -> list\nreturn a type's method resolution order"}, 1474 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS, 1475 "__subclasses__() -> list of immediate subclasses"}, 1476 {0} 1477}; 1478 1479static char type_doc[] = 1480"type(object) -> the object's type\n" 1481"type(name, bases, dict) -> a new type"; 1482 1483static int 1484type_traverse(PyTypeObject *type, visitproc visit, void *arg) 1485{ 1486 etype *et; 1487 int err; 1488 1489 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) 1490 return 0; 1491 1492 et = (etype *)type; 1493 1494#define VISIT(SLOT) \ 1495 if (SLOT) { \ 1496 err = visit((PyObject *)(SLOT), arg); \ 1497 if (err) \ 1498 return err; \ 1499 } 1500 1501 VISIT(type->tp_dict); 1502 VISIT(type->tp_cache); 1503 VISIT(type->tp_mro); 1504 VISIT(type->tp_bases); 1505 VISIT(type->tp_base); 1506 VISIT(type->tp_subclasses); 1507 VISIT(et->slots); 1508 1509#undef VISIT 1510 1511 return 0; 1512} 1513 1514static int 1515type_clear(PyTypeObject *type) 1516{ 1517 etype *et; 1518 PyObject *tmp; 1519 1520 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) 1521 return 0; 1522 1523 et = (etype *)type; 1524 1525#define CLEAR(SLOT) \ 1526 if (SLOT) { \ 1527 tmp = (PyObject *)(SLOT); \ 1528 SLOT = NULL; \ 1529 Py_DECREF(tmp); \ 1530 } 1531 1532 CLEAR(type->tp_dict); 1533 CLEAR(type->tp_cache); 1534 CLEAR(type->tp_mro); 1535 CLEAR(type->tp_bases); 1536 CLEAR(type->tp_base); 1537 CLEAR(type->tp_subclasses); 1538 CLEAR(et->slots); 1539 1540 if (type->tp_doc != NULL) { 1541 PyObject_FREE(type->tp_doc); 1542 type->tp_doc = NULL; 1543 } 1544 1545#undef CLEAR 1546 1547 return 0; 1548} 1549 1550static int 1551type_is_gc(PyTypeObject *type) 1552{ 1553 return type->tp_flags & Py_TPFLAGS_HEAPTYPE; 1554} 1555 1556PyTypeObject PyType_Type = { 1557 PyObject_HEAD_INIT(&PyType_Type) 1558 0, /* ob_size */ 1559 "type", /* tp_name */ 1560 sizeof(etype), /* tp_basicsize */ 1561 sizeof(PyMemberDef), /* tp_itemsize */ 1562 (destructor)type_dealloc, /* tp_dealloc */ 1563 0, /* tp_print */ 1564 0, /* tp_getattr */ 1565 0, /* tp_setattr */ 1566 type_compare, /* tp_compare */ 1567 (reprfunc)type_repr, /* tp_repr */ 1568 0, /* tp_as_number */ 1569 0, /* tp_as_sequence */ 1570 0, /* tp_as_mapping */ 1571 (hashfunc)_Py_HashPointer, /* tp_hash */ 1572 (ternaryfunc)type_call, /* tp_call */ 1573 0, /* tp_str */ 1574 (getattrofunc)type_getattro, /* tp_getattro */ 1575 (setattrofunc)type_setattro, /* tp_setattro */ 1576 0, /* tp_as_buffer */ 1577 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | 1578 Py_TPFLAGS_BASETYPE, /* tp_flags */ 1579 type_doc, /* tp_doc */ 1580 (traverseproc)type_traverse, /* tp_traverse */ 1581 (inquiry)type_clear, /* tp_clear */ 1582 0, /* tp_richcompare */ 1583 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */ 1584 0, /* tp_iter */ 1585 0, /* tp_iternext */ 1586 type_methods, /* tp_methods */ 1587 type_members, /* tp_members */ 1588 type_getsets, /* tp_getset */ 1589 0, /* tp_base */ 1590 0, /* tp_dict */ 1591 0, /* tp_descr_get */ 1592 0, /* tp_descr_set */ 1593 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */ 1594 0, /* tp_init */ 1595 0, /* tp_alloc */ 1596 type_new, /* tp_new */ 1597 PyObject_GC_Del, /* tp_free */ 1598 (inquiry)type_is_gc, /* tp_is_gc */ 1599}; 1600 1601 1602/* The base type of all types (eventually)... except itself. */ 1603 1604static int 1605object_init(PyObject *self, PyObject *args, PyObject *kwds) 1606{ 1607 return 0; 1608} 1609 1610static void 1611object_dealloc(PyObject *self) 1612{ 1613 self->ob_type->tp_free(self); 1614} 1615 1616static PyObject * 1617object_repr(PyObject *self) 1618{ 1619 PyTypeObject *type; 1620 PyObject *mod, *name, *rtn; 1621 1622 type = self->ob_type; 1623 mod = type_module(type, NULL); 1624 if (mod == NULL) 1625 PyErr_Clear(); 1626 else if (!PyString_Check(mod)) { 1627 Py_DECREF(mod); 1628 mod = NULL; 1629 } 1630 name = type_name(type, NULL); 1631 if (name == NULL) 1632 return NULL; 1633 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) 1634 rtn = PyString_FromFormat("<%s.%s object at %p>", 1635 PyString_AS_STRING(mod), 1636 PyString_AS_STRING(name), 1637 self); 1638 else 1639 rtn = PyString_FromFormat("<%s object at %p>", 1640 type->tp_name, self); 1641 Py_XDECREF(mod); 1642 Py_DECREF(name); 1643 return rtn; 1644} 1645 1646static PyObject * 1647object_str(PyObject *self) 1648{ 1649 unaryfunc f; 1650 1651 f = self->ob_type->tp_repr; 1652 if (f == NULL) 1653 f = object_repr; 1654 return f(self); 1655} 1656 1657static long 1658object_hash(PyObject *self) 1659{ 1660 return _Py_HashPointer(self); 1661} 1662 1663static PyObject * 1664object_get_class(PyObject *self, void *closure) 1665{ 1666 Py_INCREF(self->ob_type); 1667 return (PyObject *)(self->ob_type); 1668} 1669 1670static int 1671equiv_structs(PyTypeObject *a, PyTypeObject *b) 1672{ 1673 return a == b || 1674 (a != NULL && 1675 b != NULL && 1676 a->tp_basicsize == b->tp_basicsize && 1677 a->tp_itemsize == b->tp_itemsize && 1678 a->tp_dictoffset == b->tp_dictoffset && 1679 a->tp_weaklistoffset == b->tp_weaklistoffset && 1680 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == 1681 (b->tp_flags & Py_TPFLAGS_HAVE_GC))); 1682} 1683 1684static int 1685same_slots_added(PyTypeObject *a, PyTypeObject *b) 1686{ 1687 PyTypeObject *base = a->tp_base; 1688 int size; 1689 1690 if (base != b->tp_base) 1691 return 0; 1692 if (equiv_structs(a, base) && equiv_structs(b, base)) 1693 return 1; 1694 size = base->tp_basicsize; 1695 if (a->tp_dictoffset == size && b->tp_dictoffset == size) 1696 size += sizeof(PyObject *); 1697 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) 1698 size += sizeof(PyObject *); 1699 return size == a->tp_basicsize && size == b->tp_basicsize; 1700} 1701 1702static int 1703object_set_class(PyObject *self, PyObject *value, void *closure) 1704{ 1705 PyTypeObject *old = self->ob_type; 1706 PyTypeObject *new, *newbase, *oldbase; 1707 1708 if (value == NULL) { 1709 PyErr_SetString(PyExc_TypeError, 1710 "can't delete __class__ attribute"); 1711 return -1; 1712 } 1713 if (!PyType_Check(value)) { 1714 PyErr_Format(PyExc_TypeError, 1715 "__class__ must be set to new-style class, not '%s' object", 1716 value->ob_type->tp_name); 1717 return -1; 1718 } 1719 new = (PyTypeObject *)value; 1720 if (new->tp_dealloc != old->tp_dealloc || 1721 new->tp_free != old->tp_free) 1722 { 1723 PyErr_Format(PyExc_TypeError, 1724 "__class__ assignment: " 1725 "'%s' deallocator differs from '%s'", 1726 new->tp_name, 1727 old->tp_name); 1728 return -1; 1729 } 1730 newbase = new; 1731 oldbase = old; 1732 while (equiv_structs(newbase, newbase->tp_base)) 1733 newbase = newbase->tp_base; 1734 while (equiv_structs(oldbase, oldbase->tp_base)) 1735 oldbase = oldbase->tp_base; 1736 if (newbase != oldbase && 1737 (newbase->tp_base != oldbase->tp_base || 1738 !same_slots_added(newbase, oldbase))) { 1739 PyErr_Format(PyExc_TypeError, 1740 "__class__ assignment: " 1741 "'%s' object layout differs from '%s'", 1742 new->tp_name, 1743 old->tp_name); 1744 return -1; 1745 } 1746 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) { 1747 Py_INCREF(new); 1748 } 1749 self->ob_type = new; 1750 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) { 1751 Py_DECREF(old); 1752 } 1753 return 0; 1754} 1755 1756static PyGetSetDef object_getsets[] = { 1757 {"__class__", object_get_class, object_set_class, 1758 "the object's class"}, 1759 {0} 1760}; 1761 1762static PyObject * 1763object_reduce(PyObject *self, PyObject *args) 1764{ 1765 /* Call copy_reg._reduce(self) */ 1766 static PyObject *copy_reg_str; 1767 PyObject *copy_reg, *res; 1768 1769 if (!copy_reg_str) { 1770 copy_reg_str = PyString_InternFromString("copy_reg"); 1771 if (copy_reg_str == NULL) 1772 return NULL; 1773 } 1774 copy_reg = PyImport_Import(copy_reg_str); 1775 if (!copy_reg) 1776 return NULL; 1777 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self); 1778 Py_DECREF(copy_reg); 1779 return res; 1780} 1781 1782static PyMethodDef object_methods[] = { 1783 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"}, 1784 {0} 1785}; 1786 1787PyTypeObject PyBaseObject_Type = { 1788 PyObject_HEAD_INIT(&PyType_Type) 1789 0, /* ob_size */ 1790 "object", /* tp_name */ 1791 sizeof(PyObject), /* tp_basicsize */ 1792 0, /* tp_itemsize */ 1793 (destructor)object_dealloc, /* tp_dealloc */ 1794 0, /* tp_print */ 1795 0, /* tp_getattr */ 1796 0, /* tp_setattr */ 1797 0, /* tp_compare */ 1798 object_repr, /* tp_repr */ 1799 0, /* tp_as_number */ 1800 0, /* tp_as_sequence */ 1801 0, /* tp_as_mapping */ 1802 object_hash, /* tp_hash */ 1803 0, /* tp_call */ 1804 object_str, /* tp_str */ 1805 PyObject_GenericGetAttr, /* tp_getattro */ 1806 PyObject_GenericSetAttr, /* tp_setattro */ 1807 0, /* tp_as_buffer */ 1808 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ 1809 "The most base type", /* tp_doc */ 1810 0, /* tp_traverse */ 1811 0, /* tp_clear */ 1812 0, /* tp_richcompare */ 1813 0, /* tp_weaklistoffset */ 1814 0, /* tp_iter */ 1815 0, /* tp_iternext */ 1816 object_methods, /* tp_methods */ 1817 0, /* tp_members */ 1818 object_getsets, /* tp_getset */ 1819 0, /* tp_base */ 1820 0, /* tp_dict */ 1821 0, /* tp_descr_get */ 1822 0, /* tp_descr_set */ 1823 0, /* tp_dictoffset */ 1824 object_init, /* tp_init */ 1825 PyType_GenericAlloc, /* tp_alloc */ 1826 PyType_GenericNew, /* tp_new */ 1827 PyObject_Del, /* tp_free */ 1828}; 1829 1830 1831/* Initialize the __dict__ in a type object */ 1832 1833static PyObject * 1834create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *)) 1835{ 1836 PyObject *cfunc; 1837 PyObject *result; 1838 1839 cfunc = PyCFunction_New(meth, NULL); 1840 if (cfunc == NULL) 1841 return NULL; 1842 result = func(cfunc); 1843 Py_DECREF(cfunc); 1844 return result; 1845} 1846 1847static int 1848add_methods(PyTypeObject *type, PyMethodDef *meth) 1849{ 1850 PyObject *dict = type->tp_dict; 1851 1852 for (; meth->ml_name != NULL; meth++) { 1853 PyObject *descr; 1854 if (PyDict_GetItemString(dict, meth->ml_name)) 1855 continue; 1856 if (meth->ml_flags & METH_CLASS) { 1857 if (meth->ml_flags & METH_STATIC) { 1858 PyErr_SetString(PyExc_ValueError, 1859 "method cannot be both class and static"); 1860 return -1; 1861 } 1862 descr = create_specialmethod(meth, PyClassMethod_New); 1863 } 1864 else if (meth->ml_flags & METH_STATIC) { 1865 descr = create_specialmethod(meth, PyStaticMethod_New); 1866 } 1867 else { 1868 descr = PyDescr_NewMethod(type, meth); 1869 } 1870 if (descr == NULL) 1871 return -1; 1872 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) 1873 return -1; 1874 Py_DECREF(descr); 1875 } 1876 return 0; 1877} 1878 1879static int 1880add_members(PyTypeObject *type, PyMemberDef *memb) 1881{ 1882 PyObject *dict = type->tp_dict; 1883 1884 for (; memb->name != NULL; memb++) { 1885 PyObject *descr; 1886 if (PyDict_GetItemString(dict, memb->name)) 1887 continue; 1888 descr = PyDescr_NewMember(type, memb); 1889 if (descr == NULL) 1890 return -1; 1891 if (PyDict_SetItemString(dict, memb->name, descr) < 0) 1892 return -1; 1893 Py_DECREF(descr); 1894 } 1895 return 0; 1896} 1897 1898static int 1899add_getset(PyTypeObject *type, PyGetSetDef *gsp) 1900{ 1901 PyObject *dict = type->tp_dict; 1902 1903 for (; gsp->name != NULL; gsp++) { 1904 PyObject *descr; 1905 if (PyDict_GetItemString(dict, gsp->name)) 1906 continue; 1907 descr = PyDescr_NewGetSet(type, gsp); 1908 1909 if (descr == NULL) 1910 return -1; 1911 if (PyDict_SetItemString(dict, gsp->name, descr) < 0) 1912 return -1; 1913 Py_DECREF(descr); 1914 } 1915 return 0; 1916} 1917 1918static void 1919inherit_special(PyTypeObject *type, PyTypeObject *base) 1920{ 1921 int oldsize, newsize; 1922 1923 /* Special flag magic */ 1924 if (!type->tp_as_buffer && base->tp_as_buffer) { 1925 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER; 1926 type->tp_flags |= 1927 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER; 1928 } 1929 if (!type->tp_as_sequence && base->tp_as_sequence) { 1930 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN; 1931 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN; 1932 } 1933 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) != 1934 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) { 1935 if ((!type->tp_as_number && base->tp_as_number) || 1936 (!type->tp_as_sequence && base->tp_as_sequence)) { 1937 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS; 1938 if (!type->tp_as_number && !type->tp_as_sequence) { 1939 type->tp_flags |= base->tp_flags & 1940 Py_TPFLAGS_HAVE_INPLACEOPS; 1941 } 1942 } 1943 /* Wow */ 1944 } 1945 if (!type->tp_as_number && base->tp_as_number) { 1946 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES; 1947 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES; 1948 } 1949 1950 /* Copying basicsize is connected to the GC flags */ 1951 oldsize = base->tp_basicsize; 1952 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize; 1953 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && 1954 (base->tp_flags & Py_TPFLAGS_HAVE_GC) && 1955 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) && 1956 (!type->tp_traverse && !type->tp_clear)) { 1957 type->tp_flags |= Py_TPFLAGS_HAVE_GC; 1958 if (type->tp_traverse == NULL) 1959 type->tp_traverse = base->tp_traverse; 1960 if (type->tp_clear == NULL) 1961 type->tp_clear = base->tp_clear; 1962 } 1963 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) { 1964 /* The condition below could use some explanation. 1965 It appears that tp_new is not inherited for static types 1966 whose base class is 'object'; this seems to be a precaution 1967 so that old extension types don't suddenly become 1968 callable (object.__new__ wouldn't insure the invariants 1969 that the extension type's own factory function ensures). 1970 Heap types, of course, are under our control, so they do 1971 inherit tp_new; static extension types that specify some 1972 other built-in type as the default are considered 1973 new-style-aware so they also inherit object.__new__. */ 1974 if (base != &PyBaseObject_Type || 1975 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { 1976 if (type->tp_new == NULL) 1977 type->tp_new = base->tp_new; 1978 } 1979 } 1980 type->tp_basicsize = newsize; 1981 1982 /* Copy other non-function slots */ 1983 1984#undef COPYVAL 1985#define COPYVAL(SLOT) \ 1986 if (type->SLOT == 0) type->SLOT = base->SLOT 1987 1988 COPYVAL(tp_itemsize); 1989 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) { 1990 COPYVAL(tp_weaklistoffset); 1991 } 1992 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) { 1993 COPYVAL(tp_dictoffset); 1994 } 1995} 1996 1997static void 1998inherit_slots(PyTypeObject *type, PyTypeObject *base) 1999{ 2000 PyTypeObject *basebase; 2001 2002#undef SLOTDEFINED 2003#undef COPYSLOT 2004#undef COPYNUM 2005#undef COPYSEQ 2006#undef COPYMAP 2007#undef COPYBUF 2008 2009#define SLOTDEFINED(SLOT) \ 2010 (base->SLOT != 0 && \ 2011 (basebase == NULL || base->SLOT != basebase->SLOT)) 2012 2013#define COPYSLOT(SLOT) \ 2014 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT 2015 2016#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT) 2017#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT) 2018#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT) 2019#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT) 2020 2021 /* This won't inherit indirect slots (from tp_as_number etc.) 2022 if type doesn't provide the space. */ 2023 2024 if (type->tp_as_number != NULL && base->tp_as_number != NULL) { 2025 basebase = base->tp_base; 2026 if (basebase->tp_as_number == NULL) 2027 basebase = NULL; 2028 COPYNUM(nb_add); 2029 COPYNUM(nb_subtract); 2030 COPYNUM(nb_multiply); 2031 COPYNUM(nb_divide); 2032 COPYNUM(nb_remainder); 2033 COPYNUM(nb_divmod); 2034 COPYNUM(nb_power); 2035 COPYNUM(nb_negative); 2036 COPYNUM(nb_positive); 2037 COPYNUM(nb_absolute); 2038 COPYNUM(nb_nonzero); 2039 COPYNUM(nb_invert); 2040 COPYNUM(nb_lshift); 2041 COPYNUM(nb_rshift); 2042 COPYNUM(nb_and); 2043 COPYNUM(nb_xor); 2044 COPYNUM(nb_or); 2045 COPYNUM(nb_coerce); 2046 COPYNUM(nb_int); 2047 COPYNUM(nb_long); 2048 COPYNUM(nb_float); 2049 COPYNUM(nb_oct); 2050 COPYNUM(nb_hex); 2051 COPYNUM(nb_inplace_add); 2052 COPYNUM(nb_inplace_subtract); 2053 COPYNUM(nb_inplace_multiply); 2054 COPYNUM(nb_inplace_divide); 2055 COPYNUM(nb_inplace_remainder); 2056 COPYNUM(nb_inplace_power); 2057 COPYNUM(nb_inplace_lshift); 2058 COPYNUM(nb_inplace_rshift); 2059 COPYNUM(nb_inplace_and); 2060 COPYNUM(nb_inplace_xor); 2061 COPYNUM(nb_inplace_or); 2062 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) { 2063 COPYNUM(nb_true_divide); 2064 COPYNUM(nb_floor_divide); 2065 COPYNUM(nb_inplace_true_divide); 2066 COPYNUM(nb_inplace_floor_divide); 2067 } 2068 } 2069 2070 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { 2071 basebase = base->tp_base; 2072 if (basebase->tp_as_sequence == NULL) 2073 basebase = NULL; 2074 COPYSEQ(sq_length); 2075 COPYSEQ(sq_concat); 2076 COPYSEQ(sq_repeat); 2077 COPYSEQ(sq_item); 2078 COPYSEQ(sq_slice); 2079 COPYSEQ(sq_ass_item); 2080 COPYSEQ(sq_ass_slice); 2081 COPYSEQ(sq_contains); 2082 COPYSEQ(sq_inplace_concat); 2083 COPYSEQ(sq_inplace_repeat); 2084 } 2085 2086 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { 2087 basebase = base->tp_base; 2088 if (basebase->tp_as_mapping == NULL) 2089 basebase = NULL; 2090 COPYMAP(mp_length); 2091 COPYMAP(mp_subscript); 2092 COPYMAP(mp_ass_subscript); 2093 } 2094 2095 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { 2096 basebase = base->tp_base; 2097 if (basebase->tp_as_buffer == NULL) 2098 basebase = NULL; 2099 COPYBUF(bf_getreadbuffer); 2100 COPYBUF(bf_getwritebuffer); 2101 COPYBUF(bf_getsegcount); 2102 COPYBUF(bf_getcharbuffer); 2103 } 2104 2105 basebase = base->tp_base; 2106 2107 COPYSLOT(tp_dealloc); 2108 COPYSLOT(tp_print); 2109 if (type->tp_getattr == NULL && type->tp_getattro == NULL) { 2110 type->tp_getattr = base->tp_getattr; 2111 type->tp_getattro = base->tp_getattro; 2112 } 2113 if (type->tp_setattr == NULL && type->tp_setattro == NULL) { 2114 type->tp_setattr = base->tp_setattr; 2115 type->tp_setattro = base->tp_setattro; 2116 } 2117 /* tp_compare see tp_richcompare */ 2118 COPYSLOT(tp_repr); 2119 /* tp_hash see tp_richcompare */ 2120 COPYSLOT(tp_call); 2121 COPYSLOT(tp_str); 2122 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) { 2123 if (type->tp_compare == NULL && 2124 type->tp_richcompare == NULL && 2125 type->tp_hash == NULL) 2126 { 2127 type->tp_compare = base->tp_compare; 2128 type->tp_richcompare = base->tp_richcompare; 2129 type->tp_hash = base->tp_hash; 2130 } 2131 } 2132 else { 2133 COPYSLOT(tp_compare); 2134 } 2135 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) { 2136 COPYSLOT(tp_iter); 2137 COPYSLOT(tp_iternext); 2138 } 2139 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) { 2140 COPYSLOT(tp_descr_get); 2141 COPYSLOT(tp_descr_set); 2142 COPYSLOT(tp_dictoffset); 2143 COPYSLOT(tp_init); 2144 COPYSLOT(tp_alloc); 2145 COPYSLOT(tp_free); 2146 COPYSLOT(tp_is_gc); 2147 } 2148} 2149 2150staticforward int add_operators(PyTypeObject *); 2151staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type); 2152 2153int 2154PyType_Ready(PyTypeObject *type) 2155{ 2156 PyObject *dict, *bases; 2157 PyTypeObject *base; 2158 int i, n; 2159 2160 if (type->tp_flags & Py_TPFLAGS_READY) { 2161 assert(type->tp_dict != NULL); 2162 return 0; 2163 } 2164 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0); 2165 2166 type->tp_flags |= Py_TPFLAGS_READYING; 2167 2168 /* Initialize tp_base (defaults to BaseObject unless that's us) */ 2169 base = type->tp_base; 2170 if (base == NULL && type != &PyBaseObject_Type) 2171 base = type->tp_base = &PyBaseObject_Type; 2172 2173 /* Initialize ob_type if NULL. This means extensions that want to be 2174 compilable separately on Windows can call PyType_Ready() instead of 2175 initializing the ob_type field of their type objects. */ 2176 if (type->ob_type == NULL) 2177 type->ob_type = base->ob_type; 2178 2179 /* Initialize tp_bases */ 2180 bases = type->tp_bases; 2181 if (bases == NULL) { 2182 if (base == NULL) 2183 bases = PyTuple_New(0); 2184 else 2185 bases = Py_BuildValue("(O)", base); 2186 if (bases == NULL) 2187 goto error; 2188 type->tp_bases = bases; 2189 } 2190 2191 /* Initialize the base class */ 2192 if (base && base->tp_dict == NULL) { 2193 if (PyType_Ready(base) < 0) 2194 goto error; 2195 } 2196 2197 /* Initialize tp_dict */ 2198 dict = type->tp_dict; 2199 if (dict == NULL) { 2200 dict = PyDict_New(); 2201 if (dict == NULL) 2202 goto error; 2203 type->tp_dict = dict; 2204 } 2205 2206 /* Add type-specific descriptors to tp_dict */ 2207 if (add_operators(type) < 0) 2208 goto error; 2209 if (type->tp_methods != NULL) { 2210 if (add_methods(type, type->tp_methods) < 0) 2211 goto error; 2212 } 2213 if (type->tp_members != NULL) { 2214 if (add_members(type, type->tp_members) < 0) 2215 goto error; 2216 } 2217 if (type->tp_getset != NULL) { 2218 if (add_getset(type, type->tp_getset) < 0) 2219 goto error; 2220 } 2221 2222 /* Calculate method resolution order */ 2223 if (mro_internal(type) < 0) { 2224 goto error; 2225 } 2226 2227 /* Inherit special flags from dominant base */ 2228 if (type->tp_base != NULL) 2229 inherit_special(type, type->tp_base); 2230 2231 /* Initialize tp_dict properly */ 2232 bases = type->tp_mro; 2233 assert(bases != NULL); 2234 assert(PyTuple_Check(bases)); 2235 n = PyTuple_GET_SIZE(bases); 2236 for (i = 1; i < n; i++) { 2237 PyObject *b = PyTuple_GET_ITEM(bases, i); 2238 if (PyType_Check(b)) 2239 inherit_slots(type, (PyTypeObject *)b); 2240 } 2241 2242 /* if the type dictionary doesn't contain a __doc__, set it from 2243 the tp_doc slot. 2244 */ 2245 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) { 2246 if (type->tp_doc != NULL) { 2247 PyObject *doc = PyString_FromString(type->tp_doc); 2248 PyDict_SetItemString(type->tp_dict, "__doc__", doc); 2249 Py_DECREF(doc); 2250 } else { 2251 PyDict_SetItemString(type->tp_dict, 2252 "__doc__", Py_None); 2253 } 2254 } 2255 2256 /* Some more special stuff */ 2257 base = type->tp_base; 2258 if (base != NULL) { 2259 if (type->tp_as_number == NULL) 2260 type->tp_as_number = base->tp_as_number; 2261 if (type->tp_as_sequence == NULL) 2262 type->tp_as_sequence = base->tp_as_sequence; 2263 if (type->tp_as_mapping == NULL) 2264 type->tp_as_mapping = base->tp_as_mapping; 2265 } 2266 2267 /* Link into each base class's list of subclasses */ 2268 bases = type->tp_bases; 2269 n = PyTuple_GET_SIZE(bases); 2270 for (i = 0; i < n; i++) { 2271 PyObject *b = PyTuple_GET_ITEM(bases, i); 2272 if (PyType_Check(b) && 2273 add_subclass((PyTypeObject *)b, type) < 0) 2274 goto error; 2275 } 2276 2277 /* All done -- set the ready flag */ 2278 assert(type->tp_dict != NULL); 2279 type->tp_flags = 2280 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; 2281 return 0; 2282 2283 error: 2284 type->tp_flags &= ~Py_TPFLAGS_READYING; 2285 return -1; 2286} 2287 2288static int 2289add_subclass(PyTypeObject *base, PyTypeObject *type) 2290{ 2291 int i; 2292 PyObject *list, *ref, *new; 2293 2294 list = base->tp_subclasses; 2295 if (list == NULL) { 2296 base->tp_subclasses = list = PyList_New(0); 2297 if (list == NULL) 2298 return -1; 2299 } 2300 assert(PyList_Check(list)); 2301 new = PyWeakref_NewRef((PyObject *)type, NULL); 2302 i = PyList_GET_SIZE(list); 2303 while (--i >= 0) { 2304 ref = PyList_GET_ITEM(list, i); 2305 assert(PyWeakref_CheckRef(ref)); 2306 if (PyWeakref_GET_OBJECT(ref) == Py_None) 2307 return PyList_SetItem(list, i, new); 2308 } 2309 i = PyList_Append(list, new); 2310 Py_DECREF(new); 2311 return i; 2312} 2313 2314 2315/* Generic wrappers for overloadable 'operators' such as __getitem__ */ 2316 2317/* There's a wrapper *function* for each distinct function typedef used 2318 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a 2319 wrapper *table* for each distinct operation (e.g. __len__, __add__). 2320 Most tables have only one entry; the tables for binary operators have two 2321 entries, one regular and one with reversed arguments. */ 2322 2323static PyObject * 2324wrap_inquiry(PyObject *self, PyObject *args, void *wrapped) 2325{ 2326 inquiry func = (inquiry)wrapped; 2327 int res; 2328 2329 if (!PyArg_ParseTuple(args, "")) 2330 return NULL; 2331 res = (*func)(self); 2332 if (res == -1 && PyErr_Occurred()) 2333 return NULL; 2334 return PyInt_FromLong((long)res); 2335} 2336 2337static PyObject * 2338wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped) 2339{ 2340 binaryfunc func = (binaryfunc)wrapped; 2341 PyObject *other; 2342 2343 if (!PyArg_ParseTuple(args, "O", &other)) 2344 return NULL; 2345 return (*func)(self, other); 2346} 2347 2348static PyObject * 2349wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped) 2350{ 2351 binaryfunc func = (binaryfunc)wrapped; 2352 PyObject *other; 2353 2354 if (!PyArg_ParseTuple(args, "O", &other)) 2355 return NULL; 2356 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) && 2357 !PyType_IsSubtype(other->ob_type, self->ob_type)) { 2358 Py_INCREF(Py_NotImplemented); 2359 return Py_NotImplemented; 2360 } 2361 return (*func)(self, other); 2362} 2363 2364static PyObject * 2365wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped) 2366{ 2367 binaryfunc func = (binaryfunc)wrapped; 2368 PyObject *other; 2369 2370 if (!PyArg_ParseTuple(args, "O", &other)) 2371 return NULL; 2372 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) && 2373 !PyType_IsSubtype(other->ob_type, self->ob_type)) { 2374 Py_INCREF(Py_NotImplemented); 2375 return Py_NotImplemented; 2376 } 2377 return (*func)(other, self); 2378} 2379 2380static PyObject * 2381wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped) 2382{ 2383 coercion func = (coercion)wrapped; 2384 PyObject *other, *res; 2385 int ok; 2386 2387 if (!PyArg_ParseTuple(args, "O", &other)) 2388 return NULL; 2389 ok = func(&self, &other); 2390 if (ok < 0) 2391 return NULL; 2392 if (ok > 0) { 2393 Py_INCREF(Py_NotImplemented); 2394 return Py_NotImplemented; 2395 } 2396 res = PyTuple_New(2); 2397 if (res == NULL) { 2398 Py_DECREF(self); 2399 Py_DECREF(other); 2400 return NULL; 2401 } 2402 PyTuple_SET_ITEM(res, 0, self); 2403 PyTuple_SET_ITEM(res, 1, other); 2404 return res; 2405} 2406 2407static PyObject * 2408wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped) 2409{ 2410 ternaryfunc func = (ternaryfunc)wrapped; 2411 PyObject *other; 2412 PyObject *third = Py_None; 2413 2414 /* Note: This wrapper only works for __pow__() */ 2415 2416 if (!PyArg_ParseTuple(args, "O|O", &other, &third)) 2417 return NULL; 2418 return (*func)(self, other, third); 2419} 2420 2421static PyObject * 2422wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped) 2423{ 2424 ternaryfunc func = (ternaryfunc)wrapped; 2425 PyObject *other; 2426 PyObject *third = Py_None; 2427 2428 /* Note: This wrapper only works for __pow__() */ 2429 2430 if (!PyArg_ParseTuple(args, "O|O", &other, &third)) 2431 return NULL; 2432 return (*func)(other, self, third); 2433} 2434 2435static PyObject * 2436wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped) 2437{ 2438 unaryfunc func = (unaryfunc)wrapped; 2439 2440 if (!PyArg_ParseTuple(args, "")) 2441 return NULL; 2442 return (*func)(self); 2443} 2444 2445static PyObject * 2446wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped) 2447{ 2448 intargfunc func = (intargfunc)wrapped; 2449 int i; 2450 2451 if (!PyArg_ParseTuple(args, "i", &i)) 2452 return NULL; 2453 return (*func)(self, i); 2454} 2455 2456static int 2457getindex(PyObject *self, PyObject *arg) 2458{ 2459 int i; 2460 2461 i = PyInt_AsLong(arg); 2462 if (i == -1 && PyErr_Occurred()) 2463 return -1; 2464 if (i < 0) { 2465 PySequenceMethods *sq = self->ob_type->tp_as_sequence; 2466 if (sq && sq->sq_length) { 2467 int n = (*sq->sq_length)(self); 2468 if (n < 0) 2469 return -1; 2470 i += n; 2471 } 2472 } 2473 return i; 2474} 2475 2476static PyObject * 2477wrap_sq_item(PyObject *self, PyObject *args, void *wrapped) 2478{ 2479 intargfunc func = (intargfunc)wrapped; 2480 PyObject *arg; 2481 int i; 2482 2483 if (PyTuple_GET_SIZE(args) == 1) { 2484 arg = PyTuple_GET_ITEM(args, 0); 2485 i = getindex(self, arg); 2486 if (i == -1 && PyErr_Occurred()) 2487 return NULL; 2488 return (*func)(self, i); 2489 } 2490 PyArg_ParseTuple(args, "O", &arg); 2491 assert(PyErr_Occurred()); 2492 return NULL; 2493} 2494 2495static PyObject * 2496wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped) 2497{ 2498 intintargfunc func = (intintargfunc)wrapped; 2499 int i, j; 2500 2501 if (!PyArg_ParseTuple(args, "ii", &i, &j)) 2502 return NULL; 2503 return (*func)(self, i, j); 2504} 2505 2506static PyObject * 2507wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped) 2508{ 2509 intobjargproc func = (intobjargproc)wrapped; 2510 int i, res; 2511 PyObject *arg, *value; 2512 2513 if (!PyArg_ParseTuple(args, "OO", &arg, &value)) 2514 return NULL; 2515 i = getindex(self, arg); 2516 if (i == -1 && PyErr_Occurred()) 2517 return NULL; 2518 res = (*func)(self, i, value); 2519 if (res == -1 && PyErr_Occurred()) 2520 return NULL; 2521 Py_INCREF(Py_None); 2522 return Py_None; 2523} 2524 2525static PyObject * 2526wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped) 2527{ 2528 intobjargproc func = (intobjargproc)wrapped; 2529 int i, res; 2530 PyObject *arg; 2531 2532 if (!PyArg_ParseTuple(args, "O", &arg)) 2533 return NULL; 2534 i = getindex(self, arg); 2535 if (i == -1 && PyErr_Occurred()) 2536 return NULL; 2537 res = (*func)(self, i, NULL); 2538 if (res == -1 && PyErr_Occurred()) 2539 return NULL; 2540 Py_INCREF(Py_None); 2541 return Py_None; 2542} 2543 2544static PyObject * 2545wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped) 2546{ 2547 intintobjargproc func = (intintobjargproc)wrapped; 2548 int i, j, res; 2549 PyObject *value; 2550 2551 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value)) 2552 return NULL; 2553 res = (*func)(self, i, j, value); 2554 if (res == -1 && PyErr_Occurred()) 2555 return NULL; 2556 Py_INCREF(Py_None); 2557 return Py_None; 2558} 2559 2560static PyObject * 2561wrap_delslice(PyObject *self, PyObject *args, void *wrapped) 2562{ 2563 intintobjargproc func = (intintobjargproc)wrapped; 2564 int i, j, res; 2565 2566 if (!PyArg_ParseTuple(args, "ii", &i, &j)) 2567 return NULL; 2568 res = (*func)(self, i, j, NULL); 2569 if (res == -1 && PyErr_Occurred()) 2570 return NULL; 2571 Py_INCREF(Py_None); 2572 return Py_None; 2573} 2574 2575/* XXX objobjproc is a misnomer; should be objargpred */ 2576static PyObject * 2577wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped) 2578{ 2579 objobjproc func = (objobjproc)wrapped; 2580 int res; 2581 PyObject *value; 2582 2583 if (!PyArg_ParseTuple(args, "O", &value)) 2584 return NULL; 2585 res = (*func)(self, value); 2586 if (res == -1 && PyErr_Occurred()) 2587 return NULL; 2588 return PyInt_FromLong((long)res); 2589} 2590 2591static PyObject * 2592wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped) 2593{ 2594 objobjargproc func = (objobjargproc)wrapped; 2595 int res; 2596 PyObject *key, *value; 2597 2598 if (!PyArg_ParseTuple(args, "OO", &key, &value)) 2599 return NULL; 2600 res = (*func)(self, key, value); 2601 if (res == -1 && PyErr_Occurred()) 2602 return NULL; 2603 Py_INCREF(Py_None); 2604 return Py_None; 2605} 2606 2607static PyObject * 2608wrap_delitem(PyObject *self, PyObject *args, void *wrapped) 2609{ 2610 objobjargproc func = (objobjargproc)wrapped; 2611 int res; 2612 PyObject *key; 2613 2614 if (!PyArg_ParseTuple(args, "O", &key)) 2615 return NULL; 2616 res = (*func)(self, key, NULL); 2617 if (res == -1 && PyErr_Occurred()) 2618 return NULL; 2619 Py_INCREF(Py_None); 2620 return Py_None; 2621} 2622 2623static PyObject * 2624wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped) 2625{ 2626 cmpfunc func = (cmpfunc)wrapped; 2627 int res; 2628 PyObject *other; 2629 2630 if (!PyArg_ParseTuple(args, "O", &other)) 2631 return NULL; 2632 if (other->ob_type->tp_compare != func && 2633 !PyType_IsSubtype(other->ob_type, self->ob_type)) { 2634 PyErr_Format( 2635 PyExc_TypeError, 2636 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'", 2637 self->ob_type->tp_name, 2638 self->ob_type->tp_name, 2639 other->ob_type->tp_name); 2640 return NULL; 2641 } 2642 res = (*func)(self, other); 2643 if (PyErr_Occurred()) 2644 return NULL; 2645 return PyInt_FromLong((long)res); 2646} 2647 2648static PyObject * 2649wrap_setattr(PyObject *self, PyObject *args, void *wrapped) 2650{ 2651 setattrofunc func = (setattrofunc)wrapped; 2652 int res; 2653 PyObject *name, *value; 2654 2655 if (!PyArg_ParseTuple(args, "OO", &name, &value)) 2656 return NULL; 2657 res = (*func)(self, name, value); 2658 if (res < 0) 2659 return NULL; 2660 Py_INCREF(Py_None); 2661 return Py_None; 2662} 2663 2664static PyObject * 2665wrap_delattr(PyObject *self, PyObject *args, void *wrapped) 2666{ 2667 setattrofunc func = (setattrofunc)wrapped; 2668 int res; 2669 PyObject *name; 2670 2671 if (!PyArg_ParseTuple(args, "O", &name)) 2672 return NULL; 2673 res = (*func)(self, name, NULL); 2674 if (res < 0) 2675 return NULL; 2676 Py_INCREF(Py_None); 2677 return Py_None; 2678} 2679 2680static PyObject * 2681wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped) 2682{ 2683 hashfunc func = (hashfunc)wrapped; 2684 long res; 2685 2686 if (!PyArg_ParseTuple(args, "")) 2687 return NULL; 2688 res = (*func)(self); 2689 if (res == -1 && PyErr_Occurred()) 2690 return NULL; 2691 return PyInt_FromLong(res); 2692} 2693 2694static PyObject * 2695wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) 2696{ 2697 ternaryfunc func = (ternaryfunc)wrapped; 2698 2699 return (*func)(self, args, kwds); 2700} 2701 2702static PyObject * 2703wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op) 2704{ 2705 richcmpfunc func = (richcmpfunc)wrapped; 2706 PyObject *other; 2707 2708 if (!PyArg_ParseTuple(args, "O", &other)) 2709 return NULL; 2710 return (*func)(self, other, op); 2711} 2712 2713#undef RICHCMP_WRAPPER 2714#define RICHCMP_WRAPPER(NAME, OP) \ 2715static PyObject * \ 2716richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \ 2717{ \ 2718 return wrap_richcmpfunc(self, args, wrapped, OP); \ 2719} 2720 2721RICHCMP_WRAPPER(lt, Py_LT) 2722RICHCMP_WRAPPER(le, Py_LE) 2723RICHCMP_WRAPPER(eq, Py_EQ) 2724RICHCMP_WRAPPER(ne, Py_NE) 2725RICHCMP_WRAPPER(gt, Py_GT) 2726RICHCMP_WRAPPER(ge, Py_GE) 2727 2728static PyObject * 2729wrap_next(PyObject *self, PyObject *args, void *wrapped) 2730{ 2731 unaryfunc func = (unaryfunc)wrapped; 2732 PyObject *res; 2733 2734 if (!PyArg_ParseTuple(args, "")) 2735 return NULL; 2736 res = (*func)(self); 2737 if (res == NULL && !PyErr_Occurred()) 2738 PyErr_SetNone(PyExc_StopIteration); 2739 return res; 2740} 2741 2742static PyObject * 2743wrap_descr_get(PyObject *self, PyObject *args, void *wrapped) 2744{ 2745 descrgetfunc func = (descrgetfunc)wrapped; 2746 PyObject *obj; 2747 PyObject *type = NULL; 2748 2749 if (!PyArg_ParseTuple(args, "O|O", &obj, &type)) 2750 return NULL; 2751 return (*func)(self, obj, type); 2752} 2753 2754static PyObject * 2755wrap_descr_set(PyObject *self, PyObject *args, void *wrapped) 2756{ 2757 descrsetfunc func = (descrsetfunc)wrapped; 2758 PyObject *obj, *value; 2759 int ret; 2760 2761 if (!PyArg_ParseTuple(args, "OO", &obj, &value)) 2762 return NULL; 2763 ret = (*func)(self, obj, value); 2764 if (ret < 0) 2765 return NULL; 2766 Py_INCREF(Py_None); 2767 return Py_None; 2768} 2769 2770static PyObject * 2771wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) 2772{ 2773 initproc func = (initproc)wrapped; 2774 2775 if (func(self, args, kwds) < 0) 2776 return NULL; 2777 Py_INCREF(Py_None); 2778 return Py_None; 2779} 2780 2781static PyObject * 2782tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds) 2783{ 2784 PyTypeObject *type, *subtype, *staticbase; 2785 PyObject *arg0, *res; 2786 2787 if (self == NULL || !PyType_Check(self)) 2788 Py_FatalError("__new__() called with non-type 'self'"); 2789 type = (PyTypeObject *)self; 2790 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) { 2791 PyErr_Format(PyExc_TypeError, 2792 "%s.__new__(): not enough arguments", 2793 type->tp_name); 2794 return NULL; 2795 } 2796 arg0 = PyTuple_GET_ITEM(args, 0); 2797 if (!PyType_Check(arg0)) { 2798 PyErr_Format(PyExc_TypeError, 2799 "%s.__new__(X): X is not a type object (%s)", 2800 type->tp_name, 2801 arg0->ob_type->tp_name); 2802 return NULL; 2803 } 2804 subtype = (PyTypeObject *)arg0; 2805 if (!PyType_IsSubtype(subtype, type)) { 2806 PyErr_Format(PyExc_TypeError, 2807 "%s.__new__(%s): %s is not a subtype of %s", 2808 type->tp_name, 2809 subtype->tp_name, 2810 subtype->tp_name, 2811 type->tp_name); 2812 return NULL; 2813 } 2814 2815 /* Check that the use doesn't do something silly and unsafe like 2816 object.__new__(dict). To do this, we check that the 2817 most derived base that's not a heap type is this type. */ 2818 staticbase = subtype; 2819 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE)) 2820 staticbase = staticbase->tp_base; 2821 if (staticbase->tp_new != type->tp_new) { 2822 PyErr_Format(PyExc_TypeError, 2823 "%s.__new__(%s) is not safe, use %s.__new__()", 2824 type->tp_name, 2825 subtype->tp_name, 2826 staticbase == NULL ? "?" : staticbase->tp_name); 2827 return NULL; 2828 } 2829 2830 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); 2831 if (args == NULL) 2832 return NULL; 2833 res = type->tp_new(subtype, args, kwds); 2834 Py_DECREF(args); 2835 return res; 2836} 2837 2838static struct PyMethodDef tp_new_methoddef[] = { 2839 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS, 2840 "T.__new__(S, ...) -> a new object with type S, a subtype of T"}, 2841 {0} 2842}; 2843 2844static int 2845add_tp_new_wrapper(PyTypeObject *type) 2846{ 2847 PyObject *func; 2848 2849 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL) 2850 return 0; 2851 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type); 2852 if (func == NULL) 2853 return -1; 2854 return PyDict_SetItemString(type->tp_dict, "__new__", func); 2855} 2856 2857/* Slot wrappers that call the corresponding __foo__ slot. See comments 2858 below at override_slots() for more explanation. */ 2859 2860#define SLOT0(FUNCNAME, OPSTR) \ 2861static PyObject * \ 2862FUNCNAME(PyObject *self) \ 2863{ \ 2864 static PyObject *cache_str; \ 2865 return call_method(self, OPSTR, &cache_str, "()"); \ 2866} 2867 2868#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \ 2869static PyObject * \ 2870FUNCNAME(PyObject *self, ARG1TYPE arg1) \ 2871{ \ 2872 static PyObject *cache_str; \ 2873 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \ 2874} 2875 2876 2877#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \ 2878static PyObject * \ 2879FUNCNAME(PyObject *self, PyObject *other) \ 2880{ \ 2881 static PyObject *cache_str, *rcache_str; \ 2882 int do_other = self->ob_type != other->ob_type && \ 2883 other->ob_type->tp_as_number != NULL && \ 2884 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \ 2885 if (self->ob_type->tp_as_number != NULL && \ 2886 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \ 2887 PyObject *r; \ 2888 if (do_other && \ 2889 PyType_IsSubtype(other->ob_type, self->ob_type)) { \ 2890 r = call_maybe( \ 2891 other, ROPSTR, &rcache_str, "(O)", self); \ 2892 if (r != Py_NotImplemented) \ 2893 return r; \ 2894 Py_DECREF(r); \ 2895 do_other = 0; \ 2896 } \ 2897 r = call_maybe( \ 2898 self, OPSTR, &cache_str, "(O)", other); \ 2899 if (r != Py_NotImplemented || \ 2900 other->ob_type == self->ob_type) \ 2901 return r; \ 2902 Py_DECREF(r); \ 2903 } \ 2904 if (do_other) { \ 2905 return call_maybe( \ 2906 other, ROPSTR, &rcache_str, "(O)", self); \ 2907 } \ 2908 Py_INCREF(Py_NotImplemented); \ 2909 return Py_NotImplemented; \ 2910} 2911 2912#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \ 2913 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) 2914 2915#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \ 2916static PyObject * \ 2917FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \ 2918{ \ 2919 static PyObject *cache_str; \ 2920 return call_method(self, OPSTR, &cache_str, \ 2921 "(" ARGCODES ")", arg1, arg2); \ 2922} 2923 2924static int 2925slot_sq_length(PyObject *self) 2926{ 2927 static PyObject *len_str; 2928 PyObject *res = call_method(self, "__len__", &len_str, "()"); 2929 int len; 2930 2931 if (res == NULL) 2932 return -1; 2933 len = (int)PyInt_AsLong(res); 2934 Py_DECREF(res); 2935 return len; 2936} 2937 2938SLOT1(slot_sq_concat, "__add__", PyObject *, "O") 2939SLOT1(slot_sq_repeat, "__mul__", int, "i") 2940 2941/* Super-optimized version of slot_sq_item. 2942 Other slots could do the same... */ 2943static PyObject * 2944slot_sq_item(PyObject *self, int i) 2945{ 2946 static PyObject *getitem_str; 2947 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL; 2948 descrgetfunc f; 2949 2950 if (getitem_str == NULL) { 2951 getitem_str = PyString_InternFromString("__getitem__"); 2952 if (getitem_str == NULL) 2953 return NULL; 2954 } 2955 func = _PyType_Lookup(self->ob_type, getitem_str); 2956 if (func != NULL) { 2957 if ((f = func->ob_type->tp_descr_get) == NULL) 2958 Py_INCREF(func); 2959 else 2960 func = f(func, self, (PyObject *)(self->ob_type)); 2961 ival = PyInt_FromLong(i); 2962 if (ival != NULL) { 2963 args = PyTuple_New(1); 2964 if (args != NULL) { 2965 PyTuple_SET_ITEM(args, 0, ival); 2966 retval = PyObject_Call(func, args, NULL); 2967 Py_XDECREF(args); 2968 Py_XDECREF(func); 2969 return retval; 2970 } 2971 } 2972 } 2973 else { 2974 PyErr_SetObject(PyExc_AttributeError, getitem_str); 2975 } 2976 Py_XDECREF(args); 2977 Py_XDECREF(ival); 2978 Py_XDECREF(func); 2979 return NULL; 2980} 2981 2982SLOT2(slot_sq_slice, "__getslice__", int, int, "ii") 2983 2984static int 2985slot_sq_ass_item(PyObject *self, int index, PyObject *value) 2986{ 2987 PyObject *res; 2988 static PyObject *delitem_str, *setitem_str; 2989 2990 if (value == NULL) 2991 res = call_method(self, "__delitem__", &delitem_str, 2992 "(i)", index); 2993 else 2994 res = call_method(self, "__setitem__", &setitem_str, 2995 "(iO)", index, value); 2996 if (res == NULL) 2997 return -1; 2998 Py_DECREF(res); 2999 return 0; 3000} 3001 3002static int 3003slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value) 3004{ 3005 PyObject *res; 3006 static PyObject *delslice_str, *setslice_str; 3007 3008 if (value == NULL) 3009 res = call_method(self, "__delslice__", &delslice_str, 3010 "(ii)", i, j); 3011 else 3012 res = call_method(self, "__setslice__", &setslice_str, 3013 "(iiO)", i, j, value); 3014 if (res == NULL) 3015 return -1; 3016 Py_DECREF(res); 3017 return 0; 3018} 3019 3020static int 3021slot_sq_contains(PyObject *self, PyObject *value) 3022{ 3023 PyObject *func, *res, *args; 3024 static PyObject *contains_str; 3025 3026 func = lookup_maybe(self, "__contains__", &contains_str); 3027 3028 if (func != NULL) { 3029 args = Py_BuildValue("(O)", value); 3030 if (args == NULL) 3031 res = NULL; 3032 else { 3033 res = PyObject_Call(func, args, NULL); 3034 Py_DECREF(args); 3035 } 3036 Py_DECREF(func); 3037 if (res == NULL) 3038 return -1; 3039 return PyObject_IsTrue(res); 3040 } 3041 else if (PyErr_Occurred()) 3042 return -1; 3043 else { 3044 return _PySequence_IterSearch(self, value, 3045 PY_ITERSEARCH_CONTAINS); 3046 } 3047} 3048 3049SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O") 3050SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i") 3051 3052#define slot_mp_length slot_sq_length 3053 3054SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O") 3055 3056static int 3057slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value) 3058{ 3059 PyObject *res; 3060 static PyObject *delitem_str, *setitem_str; 3061 3062 if (value == NULL) 3063 res = call_method(self, "__delitem__", &delitem_str, 3064 "(O)", key); 3065 else 3066 res = call_method(self, "__setitem__", &setitem_str, 3067 "(OO)", key, value); 3068 if (res == NULL) 3069 return -1; 3070 Py_DECREF(res); 3071 return 0; 3072} 3073 3074SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__") 3075SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__") 3076SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__") 3077SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__") 3078SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__") 3079SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__") 3080 3081staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *); 3082 3083SLOT1BINFULL(slot_nb_power_binary, slot_nb_power, 3084 nb_power, "__pow__", "__rpow__") 3085 3086static PyObject * 3087slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus) 3088{ 3089 static PyObject *pow_str; 3090 3091 if (modulus == Py_None) 3092 return slot_nb_power_binary(self, other); 3093 /* Three-arg power doesn't use __rpow__. But ternary_op 3094 can call this when the second argument's type uses 3095 slot_nb_power, so check before calling self.__pow__. */ 3096 if (self->ob_type->tp_as_number != NULL && 3097 self->ob_type->tp_as_number->nb_power == slot_nb_power) { 3098 return call_method(self, "__pow__", &pow_str, 3099 "(OO)", other, modulus); 3100 } 3101 Py_INCREF(Py_NotImplemented); 3102 return Py_NotImplemented; 3103} 3104 3105SLOT0(slot_nb_negative, "__neg__") 3106SLOT0(slot_nb_positive, "__pos__") 3107SLOT0(slot_nb_absolute, "__abs__") 3108 3109static int 3110slot_nb_nonzero(PyObject *self) 3111{ 3112 PyObject *func, *res; 3113 static PyObject *nonzero_str, *len_str; 3114 3115 func = lookup_maybe(self, "__nonzero__", &nonzero_str); 3116 if (func == NULL) { 3117 if (PyErr_Occurred()) 3118 return -1; 3119 func = lookup_maybe(self, "__len__", &len_str); 3120 if (func == NULL) { 3121 if (PyErr_Occurred()) 3122 return -1; 3123 else 3124 return 1; 3125 } 3126 } 3127 res = PyObject_CallObject(func, NULL); 3128 Py_DECREF(func); 3129 if (res == NULL) 3130 return -1; 3131 return PyObject_IsTrue(res); 3132} 3133 3134SLOT0(slot_nb_invert, "__invert__") 3135SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__") 3136SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__") 3137SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__") 3138SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__") 3139SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__") 3140 3141static int 3142slot_nb_coerce(PyObject **a, PyObject **b) 3143{ 3144 static PyObject *coerce_str; 3145 PyObject *self = *a, *other = *b; 3146 3147 if (self->ob_type->tp_as_number != NULL && 3148 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) { 3149 PyObject *r; 3150 r = call_maybe( 3151 self, "__coerce__", &coerce_str, "(O)", other); 3152 if (r == NULL) 3153 return -1; 3154 if (r == Py_NotImplemented) { 3155 Py_DECREF(r); 3156 } 3157 else { 3158 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) { 3159 PyErr_SetString(PyExc_TypeError, 3160 "__coerce__ didn't return a 2-tuple"); 3161 Py_DECREF(r); 3162 return -1; 3163 } 3164 *a = PyTuple_GET_ITEM(r, 0); 3165 Py_INCREF(*a); 3166 *b = PyTuple_GET_ITEM(r, 1); 3167 Py_INCREF(*b); 3168 Py_DECREF(r); 3169 return 0; 3170 } 3171 } 3172 if (other->ob_type->tp_as_number != NULL && 3173 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) { 3174 PyObject *r; 3175 r = call_maybe( 3176 other, "__coerce__", &coerce_str, "(O)", self); 3177 if (r == NULL) 3178 return -1; 3179 if (r == Py_NotImplemented) { 3180 Py_DECREF(r); 3181 return 1; 3182 } 3183 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) { 3184 PyErr_SetString(PyExc_TypeError, 3185 "__coerce__ didn't return a 2-tuple"); 3186 Py_DECREF(r); 3187 return -1; 3188 } 3189 *a = PyTuple_GET_ITEM(r, 1); 3190 Py_INCREF(*a); 3191 *b = PyTuple_GET_ITEM(r, 0); 3192 Py_INCREF(*b); 3193 Py_DECREF(r); 3194 return 0; 3195 } 3196 return 1; 3197} 3198 3199SLOT0(slot_nb_int, "__int__") 3200SLOT0(slot_nb_long, "__long__") 3201SLOT0(slot_nb_float, "__float__") 3202SLOT0(slot_nb_oct, "__oct__") 3203SLOT0(slot_nb_hex, "__hex__") 3204SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O") 3205SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O") 3206SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") 3207SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O") 3208SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") 3209SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO") 3210SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") 3211SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") 3212SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O") 3213SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O") 3214SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O") 3215SLOT1BIN(slot_nb_floor_divide, nb_floor_divide, 3216 "__floordiv__", "__rfloordiv__") 3217SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__") 3218SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O") 3219SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O") 3220 3221static int 3222half_compare(PyObject *self, PyObject *other) 3223{ 3224 PyObject *func, *args, *res; 3225 static PyObject *cmp_str; 3226 int c; 3227 3228 func = lookup_method(self, "__cmp__", &cmp_str); 3229 if (func == NULL) { 3230 PyErr_Clear(); 3231 } 3232 else { 3233 args = Py_BuildValue("(O)", other); 3234 if (args == NULL) 3235 res = NULL; 3236 else { 3237 res = PyObject_Call(func, args, NULL); 3238 Py_DECREF(args); 3239 } 3240 if (res != Py_NotImplemented) { 3241 if (res == NULL) 3242 return -2; 3243 c = PyInt_AsLong(res); 3244 Py_DECREF(res); 3245 if (c == -1 && PyErr_Occurred()) 3246 return -2; 3247 return (c < 0) ? -1 : (c > 0) ? 1 : 0; 3248 } 3249 Py_DECREF(res); 3250 } 3251 return 2; 3252} 3253 3254/* This slot is published for the benefit of try_3way_compare in object.c */ 3255int 3256_PyObject_SlotCompare(PyObject *self, PyObject *other) 3257{ 3258 int c; 3259 3260 if (self->ob_type->tp_compare == _PyObject_SlotCompare) { 3261 c = half_compare(self, other); 3262 if (c <= 1) 3263 return c; 3264 } 3265 if (other->ob_type->tp_compare == _PyObject_SlotCompare) { 3266 c = half_compare(other, self); 3267 if (c < -1) 3268 return -2; 3269 if (c <= 1) 3270 return -c; 3271 } 3272 return (void *)self < (void *)other ? -1 : 3273 (void *)self > (void *)other ? 1 : 0; 3274} 3275 3276static PyObject * 3277slot_tp_repr(PyObject *self) 3278{ 3279 PyObject *func, *res; 3280 static PyObject *repr_str; 3281 3282 func = lookup_method(self, "__repr__", &repr_str); 3283 if (func != NULL) { 3284 res = PyEval_CallObject(func, NULL); 3285 Py_DECREF(func); 3286 return res; 3287 } 3288 PyErr_Clear(); 3289 return PyString_FromFormat("<%s object at %p>", 3290 self->ob_type->tp_name, self); 3291} 3292 3293static PyObject * 3294slot_tp_str(PyObject *self) 3295{ 3296 PyObject *func, *res; 3297 static PyObject *str_str; 3298 3299 func = lookup_method(self, "__str__", &str_str); 3300 if (func != NULL) { 3301 res = PyEval_CallObject(func, NULL); 3302 Py_DECREF(func); 3303 return res; 3304 } 3305 else { 3306 PyErr_Clear(); 3307 return slot_tp_repr(self); 3308 } 3309} 3310 3311static long 3312slot_tp_hash(PyObject *self) 3313{ 3314 PyObject *func, *res; 3315 static PyObject *hash_str, *eq_str, *cmp_str; 3316 3317 long h; 3318 3319 func = lookup_method(self, "__hash__", &hash_str); 3320 3321 if (func != NULL) { 3322 res = PyEval_CallObject(func, NULL); 3323 Py_DECREF(func); 3324 if (res == NULL) 3325 return -1; 3326 h = PyInt_AsLong(res); 3327 } 3328 else { 3329 PyErr_Clear(); 3330 func = lookup_method(self, "__eq__", &eq_str); 3331 if (func == NULL) { 3332 PyErr_Clear(); 3333 func = lookup_method(self, "__cmp__", &cmp_str); 3334 } 3335 if (func != NULL) { 3336 Py_DECREF(func); 3337 PyErr_SetString(PyExc_TypeError, "unhashable type"); 3338 return -1; 3339 } 3340 PyErr_Clear(); 3341 h = _Py_HashPointer((void *)self); 3342 } 3343 if (h == -1 && !PyErr_Occurred()) 3344 h = -2; 3345 return h; 3346} 3347 3348static PyObject * 3349slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds) 3350{ 3351 static PyObject *call_str; 3352 PyObject *meth = lookup_method(self, "__call__", &call_str); 3353 PyObject *res; 3354 3355 if (meth == NULL) 3356 return NULL; 3357 res = PyObject_Call(meth, args, kwds); 3358 Py_DECREF(meth); 3359 return res; 3360} 3361 3362/* There are two slot dispatch functions for tp_getattro. 3363 3364 - slot_tp_getattro() is used when __getattribute__ is overridden 3365 but no __getattr__ hook is present; 3366 3367 - slot_tp_getattr_hook() is used when a __getattr__ hook is present. 3368 3369 The code in update_one_slot() always installs slot_tp_getattr_hook(); this 3370 detects the absence of __getattr__ and then installs the simpler slot if 3371 necessary. */ 3372 3373static PyObject * 3374slot_tp_getattro(PyObject *self, PyObject *name) 3375{ 3376 static PyObject *getattribute_str = NULL; 3377 return call_method(self, "__getattribute__", &getattribute_str, 3378 "(O)", name); 3379} 3380 3381static PyObject * 3382slot_tp_getattr_hook(PyObject *self, PyObject *name) 3383{ 3384 PyTypeObject *tp = self->ob_type; 3385 PyObject *getattr, *getattribute, *res; 3386 static PyObject *getattribute_str = NULL; 3387 static PyObject *getattr_str = NULL; 3388 3389 if (getattr_str == NULL) { 3390 getattr_str = PyString_InternFromString("__getattr__"); 3391 if (getattr_str == NULL) 3392 return NULL; 3393 } 3394 if (getattribute_str == NULL) { 3395 getattribute_str = 3396 PyString_InternFromString("__getattribute__"); 3397 if (getattribute_str == NULL) 3398 return NULL; 3399 } 3400 getattr = _PyType_Lookup(tp, getattr_str); 3401 if (getattr == NULL) { 3402 /* No __getattr__ hook: use a simpler dispatcher */ 3403 tp->tp_getattro = slot_tp_getattro; 3404 return slot_tp_getattro(self, name); 3405 } 3406 getattribute = _PyType_Lookup(tp, getattribute_str); 3407 if (getattribute == NULL || 3408 (getattribute->ob_type == &PyWrapperDescr_Type && 3409 ((PyWrapperDescrObject *)getattribute)->d_wrapped == 3410 (void *)PyObject_GenericGetAttr)) 3411 res = PyObject_GenericGetAttr(self, name); 3412 else 3413 res = PyObject_CallFunction(getattribute, "OO", self, name); 3414 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { 3415 PyErr_Clear(); 3416 res = PyObject_CallFunction(getattr, "OO", self, name); 3417 } 3418 return res; 3419} 3420 3421static int 3422slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value) 3423{ 3424 PyObject *res; 3425 static PyObject *delattr_str, *setattr_str; 3426 3427 if (value == NULL) 3428 res = call_method(self, "__delattr__", &delattr_str, 3429 "(O)", name); 3430 else 3431 res = call_method(self, "__setattr__", &setattr_str, 3432 "(OO)", name, value); 3433 if (res == NULL) 3434 return -1; 3435 Py_DECREF(res); 3436 return 0; 3437} 3438 3439/* Map rich comparison operators to their __xx__ namesakes */ 3440static char *name_op[] = { 3441 "__lt__", 3442 "__le__", 3443 "__eq__", 3444 "__ne__", 3445 "__gt__", 3446 "__ge__", 3447}; 3448 3449static PyObject * 3450half_richcompare(PyObject *self, PyObject *other, int op) 3451{ 3452 PyObject *func, *args, *res; 3453 static PyObject *op_str[6]; 3454 3455 func = lookup_method(self, name_op[op], &op_str[op]); 3456 if (func == NULL) { 3457 PyErr_Clear(); 3458 Py_INCREF(Py_NotImplemented); 3459 return Py_NotImplemented; 3460 } 3461 args = Py_BuildValue("(O)", other); 3462 if (args == NULL) 3463 res = NULL; 3464 else { 3465 res = PyObject_Call(func, args, NULL); 3466 Py_DECREF(args); 3467 } 3468 Py_DECREF(func); 3469 return res; 3470} 3471 3472/* Map rich comparison operators to their swapped version, e.g. LT --> GT */ 3473static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE}; 3474 3475static PyObject * 3476slot_tp_richcompare(PyObject *self, PyObject *other, int op) 3477{ 3478 PyObject *res; 3479 3480 if (self->ob_type->tp_richcompare == slot_tp_richcompare) { 3481 res = half_richcompare(self, other, op); 3482 if (res != Py_NotImplemented) 3483 return res; 3484 Py_DECREF(res); 3485 } 3486 if (other->ob_type->tp_richcompare == slot_tp_richcompare) { 3487 res = half_richcompare(other, self, swapped_op[op]); 3488 if (res != Py_NotImplemented) { 3489 return res; 3490 } 3491 Py_DECREF(res); 3492 } 3493 Py_INCREF(Py_NotImplemented); 3494 return Py_NotImplemented; 3495} 3496 3497static PyObject * 3498slot_tp_iter(PyObject *self) 3499{ 3500 PyObject *func, *res; 3501 static PyObject *iter_str, *getitem_str; 3502 3503 func = lookup_method(self, "__iter__", &iter_str); 3504 if (func != NULL) { 3505 res = PyObject_CallObject(func, NULL); 3506 Py_DECREF(func); 3507 return res; 3508 } 3509 PyErr_Clear(); 3510 func = lookup_method(self, "__getitem__", &getitem_str); 3511 if (func == NULL) { 3512 PyErr_SetString(PyExc_TypeError, 3513 "iteration over non-sequence"); 3514 return NULL; 3515 } 3516 Py_DECREF(func); 3517 return PySeqIter_New(self); 3518} 3519 3520static PyObject * 3521slot_tp_iternext(PyObject *self) 3522{ 3523 static PyObject *next_str; 3524 return call_method(self, "next", &next_str, "()"); 3525} 3526 3527static PyObject * 3528slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type) 3529{ 3530 PyTypeObject *tp = self->ob_type; 3531 PyObject *get; 3532 static PyObject *get_str = NULL; 3533 3534 if (get_str == NULL) { 3535 get_str = PyString_InternFromString("__get__"); 3536 if (get_str == NULL) 3537 return NULL; 3538 } 3539 get = _PyType_Lookup(tp, get_str); 3540 if (get == NULL) { 3541 /* Avoid further slowdowns */ 3542 if (tp->tp_descr_get == slot_tp_descr_get) 3543 tp->tp_descr_get = NULL; 3544 Py_INCREF(self); 3545 return self; 3546 } 3547 if (obj == NULL) 3548 obj = Py_None; 3549 if (type == NULL) 3550 type = Py_None; 3551 return PyObject_CallFunction(get, "OOO", self, obj, type); 3552} 3553 3554static int 3555slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value) 3556{ 3557 PyObject *res; 3558 static PyObject *del_str, *set_str; 3559 3560 if (value == NULL) 3561 res = call_method(self, "__delete__", &del_str, 3562 "(O)", target); 3563 else 3564 res = call_method(self, "__set__", &set_str, 3565 "(OO)", target, value); 3566 if (res == NULL) 3567 return -1; 3568 Py_DECREF(res); 3569 return 0; 3570} 3571 3572static int 3573slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds) 3574{ 3575 static PyObject *init_str; 3576 PyObject *meth = lookup_method(self, "__init__", &init_str); 3577 PyObject *res; 3578 3579 if (meth == NULL) 3580 return -1; 3581 res = PyObject_Call(meth, args, kwds); 3582 Py_DECREF(meth); 3583 if (res == NULL) 3584 return -1; 3585 Py_DECREF(res); 3586 return 0; 3587} 3588 3589static PyObject * 3590slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 3591{ 3592 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__"); 3593 PyObject *newargs, *x; 3594 int i, n; 3595 3596 if (func == NULL) 3597 return NULL; 3598 assert(PyTuple_Check(args)); 3599 n = PyTuple_GET_SIZE(args); 3600 newargs = PyTuple_New(n+1); 3601 if (newargs == NULL) 3602 return NULL; 3603 Py_INCREF(type); 3604 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type); 3605 for (i = 0; i < n; i++) { 3606 x = PyTuple_GET_ITEM(args, i); 3607 Py_INCREF(x); 3608 PyTuple_SET_ITEM(newargs, i+1, x); 3609 } 3610 x = PyObject_Call(func, newargs, kwds); 3611 Py_DECREF(newargs); 3612 Py_DECREF(func); 3613 return x; 3614} 3615 3616 3617/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper 3618 functions. The offsets here are relative to the 'etype' structure, which 3619 incorporates the additional structures used for numbers, sequences and 3620 mappings. Note that multiple names may map to the same slot (e.g. __eq__, 3621 __ne__ etc. all map to tp_richcompare) and one name may map to multiple 3622 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is 3623 terminated with an all-zero entry. (This table is further initialized and 3624 sorted in init_slotdefs() below.) */ 3625 3626typedef struct wrapperbase slotdef; 3627 3628#undef TPSLOT 3629#undef FLSLOT 3630#undef ETSLOT 3631#undef SQSLOT 3632#undef MPSLOT 3633#undef NBSLOT 3634#undef UNSLOT 3635#undef IBSLOT 3636#undef BINSLOT 3637#undef RBINSLOT 3638 3639#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 3640 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC} 3641#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \ 3642 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ 3643 DOC, FLAGS} 3644#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 3645 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC} 3646#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 3647 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) 3648#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 3649 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) 3650#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 3651 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) 3652#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 3653 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ 3654 "x." NAME "() <==> " DOC) 3655#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ 3656 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ 3657 "x." NAME "(y) <==> x" DOC "y") 3658#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \ 3659 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ 3660 "x." NAME "(y) <==> x" DOC "y") 3661#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \ 3662 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ 3663 "x." NAME "(y) <==> y" DOC "x") 3664 3665static slotdef slotdefs[] = { 3666 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry, 3667 "x.__len__() <==> len(x)"), 3668 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc, 3669 "x.__add__(y) <==> x+y"), 3670 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc, 3671 "x.__mul__(n) <==> x*n"), 3672 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc, 3673 "x.__rmul__(n) <==> n*x"), 3674 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, 3675 "x.__getitem__(y) <==> x[y]"), 3676 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc, 3677 "x.__getslice__(i, j) <==> x[i:j]"), 3678 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, 3679 "x.__setitem__(i, y) <==> x[i]=y"), 3680 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, 3681 "x.__delitem__(y) <==> del x[y]"), 3682 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice, 3683 wrap_intintobjargproc, 3684 "x.__setslice__(i, j, y) <==> x[i:j]=y"), 3685 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice, 3686 "x.__delslice__(i, j) <==> del x[i:j]"), 3687 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, 3688 "x.__contains__(y) <==> y in x"), 3689 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat, 3690 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), 3691 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat, 3692 wrap_intargfunc, "x.__imul__(y) <==> x*=y"), 3693 3694 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry, 3695 "x.__len__() <==> len(x)"), 3696 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, 3697 wrap_binaryfunc, 3698 "x.__getitem__(y) <==> x[y]"), 3699 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, 3700 wrap_objobjargproc, 3701 "x.__setitem__(i, y) <==> x[i]=y"), 3702 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, 3703 wrap_delitem, 3704 "x.__delitem__(y) <==> del x[y]"), 3705 3706 BINSLOT("__add__", nb_add, slot_nb_add, 3707 "+"), 3708 RBINSLOT("__radd__", nb_add, slot_nb_add, 3709 "+"), 3710 BINSLOT("__sub__", nb_subtract, slot_nb_subtract, 3711 "-"), 3712 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, 3713 "-"), 3714 BINSLOT("__mul__", nb_multiply, slot_nb_multiply, 3715 "*"), 3716 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, 3717 "*"), 3718 BINSLOT("__div__", nb_divide, slot_nb_divide, 3719 "/"), 3720 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide, 3721 "/"), 3722 BINSLOT("__mod__", nb_remainder, slot_nb_remainder, 3723 "%"), 3724 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, 3725 "%"), 3726 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod, 3727 "divmod(x, y)"), 3728 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod, 3729 "divmod(y, x)"), 3730 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, 3731 "x.__pow__(y[, z]) <==> pow(x, y[, z])"), 3732 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, 3733 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"), 3734 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"), 3735 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), 3736 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, 3737 "abs(x)"), 3738 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry, 3739 "x != 0"), 3740 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), 3741 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), 3742 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), 3743 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), 3744 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), 3745 BINSLOT("__and__", nb_and, slot_nb_and, "&"), 3746 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), 3747 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), 3748 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), 3749 BINSLOT("__or__", nb_or, slot_nb_or, "|"), 3750 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), 3751 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc, 3752 "x.__coerce__(y) <==> coerce(x, y)"), 3753 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, 3754 "int(x)"), 3755 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc, 3756 "long(x)"), 3757 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, 3758 "float(x)"), 3759 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc, 3760 "oct(x)"), 3761 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc, 3762 "hex(x)"), 3763 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, 3764 wrap_binaryfunc, "+"), 3765 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, 3766 wrap_binaryfunc, "-"), 3767 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, 3768 wrap_binaryfunc, "*"), 3769 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide, 3770 wrap_binaryfunc, "/"), 3771 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, 3772 wrap_binaryfunc, "%"), 3773 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, 3774 wrap_ternaryfunc, "**"), 3775 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, 3776 wrap_binaryfunc, "<<"), 3777 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, 3778 wrap_binaryfunc, ">>"), 3779 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, 3780 wrap_binaryfunc, "&"), 3781 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, 3782 wrap_binaryfunc, "^"), 3783 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, 3784 wrap_binaryfunc, "|"), 3785 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), 3786 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), 3787 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), 3788 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), 3789 IBSLOT("__ifloordiv__", nb_inplace_floor_divide, 3790 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"), 3791 IBSLOT("__itruediv__", nb_inplace_true_divide, 3792 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), 3793 3794 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, 3795 "x.__str__() <==> str(x)"), 3796 TPSLOT("__str__", tp_print, NULL, NULL, ""), 3797 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, 3798 "x.__repr__() <==> repr(x)"), 3799 TPSLOT("__repr__", tp_print, NULL, NULL, ""), 3800 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc, 3801 "x.__cmp__(y) <==> cmp(x,y)"), 3802 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, 3803 "x.__hash__() <==> hash(x)"), 3804 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, 3805 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS), 3806 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, 3807 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"), 3808 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), 3809 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), 3810 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), 3811 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, 3812 "x.__setattr__('name', value) <==> x.name = value"), 3813 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), 3814 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, 3815 "x.__delattr__('name') <==> del x.name"), 3816 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), 3817 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, 3818 "x.__lt__(y) <==> x<y"), 3819 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le, 3820 "x.__le__(y) <==> x<=y"), 3821 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, 3822 "x.__eq__(y) <==> x==y"), 3823 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, 3824 "x.__ne__(y) <==> x!=y"), 3825 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, 3826 "x.__gt__(y) <==> x>y"), 3827 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, 3828 "x.__ge__(y) <==> x>=y"), 3829 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, 3830 "x.__iter__() <==> iter(x)"), 3831 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next, 3832 "x.next() -> the next value, or raise StopIteration"), 3833 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, 3834 "descr.__get__(obj[, type]) -> value"), 3835 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set, 3836 "descr.__set__(obj, value)"), 3837 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, 3838 "x.__init__(...) initializes x; " 3839 "see x.__class__.__doc__ for signature", 3840 PyWrapperFlag_KEYWORDS), 3841 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""), 3842 {NULL} 3843}; 3844 3845/* Given a type pointer and an offset gotten from a slotdef entry, return a 3846 pointer to the actual slot. This is not quite the same as simply adding 3847 the offset to the type pointer, since it takes care to indirect through the 3848 proper indirection pointer (as_buffer, etc.); it returns NULL if the 3849 indirection pointer is NULL. */ 3850static void ** 3851slotptr(PyTypeObject *type, int offset) 3852{ 3853 char *ptr; 3854 3855 assert(offset >= 0); 3856 assert(offset < offsetof(etype, as_buffer)); 3857 if (offset >= offsetof(etype, as_mapping)) { 3858 ptr = (void *)type->tp_as_mapping; 3859 offset -= offsetof(etype, as_mapping); 3860 } 3861 else if (offset >= offsetof(etype, as_sequence)) { 3862 ptr = (void *)type->tp_as_sequence; 3863 offset -= offsetof(etype, as_sequence); 3864 } 3865 else if (offset >= offsetof(etype, as_number)) { 3866 ptr = (void *)type->tp_as_number; 3867 offset -= offsetof(etype, as_number); 3868 } 3869 else { 3870 ptr = (void *)type; 3871 } 3872 if (ptr != NULL) 3873 ptr += offset; 3874 return (void **)ptr; 3875} 3876 3877/* Length of array of slotdef pointers used to store slots with the 3878 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with 3879 the same __name__, for any __name__. Since that's a static property, it is 3880 appropriate to declare fixed-size arrays for this. */ 3881#define MAX_EQUIV 10 3882 3883/* Return a slot pointer for a given name, but ONLY if the attribute has 3884 exactly one slot function. The name must be an interned string. */ 3885static void ** 3886resolve_slotdups(PyTypeObject *type, PyObject *name) 3887{ 3888 /* XXX Maybe this could be optimized more -- but is it worth it? */ 3889 3890 /* pname and ptrs act as a little cache */ 3891 static PyObject *pname; 3892 static slotdef *ptrs[MAX_EQUIV]; 3893 slotdef *p, **pp; 3894 void **res, **ptr; 3895 3896 if (pname != name) { 3897 /* Collect all slotdefs that match name into ptrs. */ 3898 pname = name; 3899 pp = ptrs; 3900 for (p = slotdefs; p->name_strobj; p++) { 3901 if (p->name_strobj == name) 3902 *pp++ = p; 3903 } 3904 *pp = NULL; 3905 } 3906 3907 /* Look in all matching slots of the type; if exactly one of these has 3908 a filled-in slot, return its value. Otherwise return NULL. */ 3909 res = NULL; 3910 for (pp = ptrs; *pp; pp++) { 3911 ptr = slotptr(type, (*pp)->offset); 3912 if (ptr == NULL || *ptr == NULL) 3913 continue; 3914 if (res != NULL) 3915 return NULL; 3916 res = ptr; 3917 } 3918 return res; 3919} 3920 3921/* Common code for update_these_slots() and fixup_slot_dispatchers(). This 3922 does some incredibly complex thinking and then sticks something into the 3923 slot. (It sees if the adjacent slotdefs for the same slot have conflicting 3924 interests, and then stores a generic wrapper or a specific function into 3925 the slot.) Return a pointer to the next slotdef with a different offset, 3926 because that's convenient for fixup_slot_dispatchers(). */ 3927static slotdef * 3928update_one_slot(PyTypeObject *type, slotdef *p) 3929{ 3930 PyObject *descr; 3931 PyWrapperDescrObject *d; 3932 void *generic = NULL, *specific = NULL; 3933 int use_generic = 0; 3934 int offset = p->offset; 3935 void **ptr = slotptr(type, offset); 3936 3937 if (ptr == NULL) { 3938 do { 3939 ++p; 3940 } while (p->offset == offset); 3941 return p; 3942 } 3943 do { 3944 descr = _PyType_Lookup(type, p->name_strobj); 3945 if (descr == NULL) 3946 continue; 3947 if (descr->ob_type == &PyWrapperDescr_Type) { 3948 void **tptr = resolve_slotdups(type, p->name_strobj); 3949 if (tptr == NULL || tptr == ptr) 3950 generic = p->function; 3951 d = (PyWrapperDescrObject *)descr; 3952 if (d->d_base->wrapper == p->wrapper && 3953 PyType_IsSubtype(type, d->d_type)) 3954 { 3955 if (specific == NULL || 3956 specific == d->d_wrapped) 3957 specific = d->d_wrapped; 3958 else 3959 use_generic = 1; 3960 } 3961 } 3962 else { 3963 use_generic = 1; 3964 generic = p->function; 3965 } 3966 } while ((++p)->offset == offset); 3967 if (specific && !use_generic) 3968 *ptr = specific; 3969 else 3970 *ptr = generic; 3971 return p; 3972} 3973 3974staticforward int recurse_down_subclasses(PyTypeObject *type, 3975 slotdef **pp, PyObject *name); 3976 3977/* In the type, update the slots whose slotdefs are gathered in the pp0 array, 3978 and then do the same for all this type's subtypes. */ 3979static int 3980update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name) 3981{ 3982 slotdef **pp; 3983 3984 for (pp = pp0; *pp; pp++) 3985 update_one_slot(type, *pp); 3986 return recurse_down_subclasses(type, pp0, name); 3987} 3988 3989/* Update the slots whose slotdefs are gathered in the pp array in all (direct 3990 or indirect) subclasses of type. */ 3991static int 3992recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name) 3993{ 3994 PyTypeObject *subclass; 3995 PyObject *ref, *subclasses, *dict; 3996 int i, n; 3997 3998 subclasses = type->tp_subclasses; 3999 if (subclasses == NULL) 4000 return 0; 4001 assert(PyList_Check(subclasses)); 4002 n = PyList_GET_SIZE(subclasses); 4003 for (i = 0; i < n; i++) { 4004 ref = PyList_GET_ITEM(subclasses, i); 4005 assert(PyWeakref_CheckRef(ref)); 4006 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); 4007 if (subclass == NULL) 4008 continue; 4009 assert(PyType_Check(subclass)); 4010 /* Avoid recursing down into unaffected classes */ 4011 dict = subclass->tp_dict; 4012 if (dict != NULL && PyDict_Check(dict) && 4013 PyDict_GetItem(dict, name) != NULL) 4014 continue; 4015 if (update_these_slots(subclass, pp, name) < 0) 4016 return -1; 4017 } 4018 return 0; 4019} 4020 4021/* Comparison function for qsort() to compare slotdefs by their offset, and 4022 for equal offset by their address (to force a stable sort). */ 4023static int 4024slotdef_cmp(const void *aa, const void *bb) 4025{ 4026 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb; 4027 int c = a->offset - b->offset; 4028 if (c != 0) 4029 return c; 4030 else 4031 return a - b; 4032} 4033 4034/* Initialize the slotdefs table by adding interned string objects for the 4035 names and sorting the entries. */ 4036static void 4037init_slotdefs(void) 4038{ 4039 slotdef *p; 4040 static int initialized = 0; 4041 4042 if (initialized) 4043 return; 4044 for (p = slotdefs; p->name; p++) { 4045 p->name_strobj = PyString_InternFromString(p->name); 4046 if (!p->name_strobj) 4047 Py_FatalError("Out of memory interning slotdef names"); 4048 } 4049 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), 4050 slotdef_cmp); 4051 initialized = 1; 4052} 4053 4054/* Update the slots after assignment to a class (type) attribute. */ 4055static int 4056update_slot(PyTypeObject *type, PyObject *name) 4057{ 4058 slotdef *ptrs[MAX_EQUIV]; 4059 slotdef *p; 4060 slotdef **pp; 4061 int offset; 4062 4063 init_slotdefs(); 4064 pp = ptrs; 4065 for (p = slotdefs; p->name; p++) { 4066 /* XXX assume name is interned! */ 4067 if (p->name_strobj == name) 4068 *pp++ = p; 4069 } 4070 *pp = NULL; 4071 for (pp = ptrs; *pp; pp++) { 4072 p = *pp; 4073 offset = p->offset; 4074 while (p > slotdefs && (p-1)->offset == offset) 4075 --p; 4076 *pp = p; 4077 } 4078 if (ptrs[0] == NULL) 4079 return 0; /* Not an attribute that affects any slots */ 4080 return update_these_slots(type, ptrs, name); 4081} 4082 4083/* Store the proper functions in the slot dispatches at class (type) 4084 definition time, based upon which operations the class overrides in its 4085 dict. */ 4086static void 4087fixup_slot_dispatchers(PyTypeObject *type) 4088{ 4089 slotdef *p; 4090 4091 init_slotdefs(); 4092 for (p = slotdefs; p->name; ) 4093 p = update_one_slot(type, p); 4094} 4095 4096/* This function is called by PyType_Ready() to populate the type's 4097 dictionary with method descriptors for function slots. For each 4098 function slot (like tp_repr) that's defined in the type, one or 4099 more corresponding descriptors are added in the type's tp_dict 4100 dictionary under the appropriate name (like __repr__). Some 4101 function slots cause more than one descriptor to be added (for 4102 example, the nb_add slot adds both __add__ and __radd__ 4103 descriptors) and some function slots compete for the same 4104 descriptor (for example both sq_item and mp_subscript generate a 4105 __getitem__ descriptor). This only adds new descriptors and 4106 doesn't overwrite entries in tp_dict that were previously 4107 defined. The descriptors contain a reference to the C function 4108 they must call, so that it's safe if they are copied into a 4109 subtype's __dict__ and the subtype has a different C function in 4110 its slot -- calling the method defined by the descriptor will call 4111 the C function that was used to create it, rather than the C 4112 function present in the slot when it is called. (This is important 4113 because a subtype may have a C function in the slot that calls the 4114 method from the dictionary, and we want to avoid infinite recursion 4115 here.) */ 4116 4117static int 4118add_operators(PyTypeObject *type) 4119{ 4120 PyObject *dict = type->tp_dict; 4121 slotdef *p; 4122 PyObject *descr; 4123 void **ptr; 4124 4125 init_slotdefs(); 4126 for (p = slotdefs; p->name; p++) { 4127 if (p->wrapper == NULL) 4128 continue; 4129 ptr = slotptr(type, p->offset); 4130 if (!ptr || !*ptr) 4131 continue; 4132 if (PyDict_GetItem(dict, p->name_strobj)) 4133 continue; 4134 descr = PyDescr_NewWrapper(type, p, *ptr); 4135 if (descr == NULL) 4136 return -1; 4137 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) 4138 return -1; 4139 Py_DECREF(descr); 4140 } 4141 if (type->tp_new != NULL) { 4142 if (add_tp_new_wrapper(type) < 0) 4143 return -1; 4144 } 4145 return 0; 4146} 4147 4148 4149/* Cooperative 'super' */ 4150 4151typedef struct { 4152 PyObject_HEAD 4153 PyTypeObject *type; 4154 PyObject *obj; 4155} superobject; 4156 4157static PyMemberDef super_members[] = { 4158 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY, 4159 "the class invoking super()"}, 4160 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, 4161 "the instance invoking super(); may be None"}, 4162 {0} 4163}; 4164 4165static void 4166super_dealloc(PyObject *self) 4167{ 4168 superobject *su = (superobject *)self; 4169 4170 _PyObject_GC_UNTRACK(self); 4171 Py_XDECREF(su->obj); 4172 Py_XDECREF(su->type); 4173 self->ob_type->tp_free(self); 4174} 4175 4176static PyObject * 4177super_repr(PyObject *self) 4178{ 4179 superobject *su = (superobject *)self; 4180 4181 if (su->obj) 4182 return PyString_FromFormat( 4183 "<super: <class '%s'>, <%s object>>", 4184 su->type ? su->type->tp_name : "NULL", 4185 su->obj->ob_type->tp_name); 4186 else 4187 return PyString_FromFormat( 4188 "<super: <class '%s'>, NULL>", 4189 su->type ? su->type->tp_name : "NULL"); 4190} 4191 4192static PyObject * 4193super_getattro(PyObject *self, PyObject *name) 4194{ 4195 superobject *su = (superobject *)self; 4196 4197 if (su->obj != NULL) { 4198 PyObject *mro, *res, *tmp, *dict; 4199 PyTypeObject *starttype; 4200 descrgetfunc f; 4201 int i, n; 4202 4203 starttype = su->obj->ob_type; 4204 mro = starttype->tp_mro; 4205 4206 if (mro == NULL) 4207 n = 0; 4208 else { 4209 assert(PyTuple_Check(mro)); 4210 n = PyTuple_GET_SIZE(mro); 4211 } 4212 for (i = 0; i < n; i++) { 4213 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i)) 4214 break; 4215 } 4216 if (i >= n && PyType_Check(su->obj)) { 4217 starttype = (PyTypeObject *)(su->obj); 4218 mro = starttype->tp_mro; 4219 if (mro == NULL) 4220 n = 0; 4221 else { 4222 assert(PyTuple_Check(mro)); 4223 n = PyTuple_GET_SIZE(mro); 4224 } 4225 for (i = 0; i < n; i++) { 4226 if ((PyObject *)(su->type) == 4227 PyTuple_GET_ITEM(mro, i)) 4228 break; 4229 } 4230 } 4231 i++; 4232 res = NULL; 4233 for (; i < n; i++) { 4234 tmp = PyTuple_GET_ITEM(mro, i); 4235 if (PyType_Check(tmp)) 4236 dict = ((PyTypeObject *)tmp)->tp_dict; 4237 else if (PyClass_Check(tmp)) 4238 dict = ((PyClassObject *)tmp)->cl_dict; 4239 else 4240 continue; 4241 res = PyDict_GetItem(dict, name); 4242 if (res != NULL && !PyDescr_IsData(res)) { 4243 Py_INCREF(res); 4244 f = res->ob_type->tp_descr_get; 4245 if (f != NULL) { 4246 tmp = f(res, su->obj, 4247 (PyObject *)starttype); 4248 Py_DECREF(res); 4249 res = tmp; 4250 } 4251 return res; 4252 } 4253 } 4254 } 4255 return PyObject_GenericGetAttr(self, name); 4256} 4257 4258static int 4259supercheck(PyTypeObject *type, PyObject *obj) 4260{ 4261 if (!PyType_IsSubtype(obj->ob_type, type) && 4262 !(PyType_Check(obj) && 4263 PyType_IsSubtype((PyTypeObject *)obj, type))) { 4264 PyErr_SetString(PyExc_TypeError, 4265 "super(type, obj): " 4266 "obj must be an instance or subtype of type"); 4267 return -1; 4268 } 4269 else 4270 return 0; 4271} 4272 4273static PyObject * 4274super_descr_get(PyObject *self, PyObject *obj, PyObject *type) 4275{ 4276 superobject *su = (superobject *)self; 4277 superobject *new; 4278 4279 if (obj == NULL || obj == Py_None || su->obj != NULL) { 4280 /* Not binding to an object, or already bound */ 4281 Py_INCREF(self); 4282 return self; 4283 } 4284 if (su->ob_type != &PySuper_Type) 4285 /* If su is an instance of a subclass of super, 4286 call its type */ 4287 return PyObject_CallFunction((PyObject *)su->ob_type, 4288 "OO", su->type, obj); 4289 else { 4290 /* Inline the common case */ 4291 if (supercheck(su->type, obj) < 0) 4292 return NULL; 4293 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, 4294 NULL, NULL); 4295 if (new == NULL) 4296 return NULL; 4297 Py_INCREF(su->type); 4298 Py_INCREF(obj); 4299 new->type = su->type; 4300 new->obj = obj; 4301 return (PyObject *)new; 4302 } 4303} 4304 4305static int 4306super_init(PyObject *self, PyObject *args, PyObject *kwds) 4307{ 4308 superobject *su = (superobject *)self; 4309 PyTypeObject *type; 4310 PyObject *obj = NULL; 4311 4312 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj)) 4313 return -1; 4314 if (obj == Py_None) 4315 obj = NULL; 4316 if (obj != NULL && supercheck(type, obj) < 0) 4317 return -1; 4318 Py_INCREF(type); 4319 Py_XINCREF(obj); 4320 su->type = type; 4321 su->obj = obj; 4322 return 0; 4323} 4324 4325static char super_doc[] = 4326"super(type) -> unbound super object\n" 4327"super(type, obj) -> bound super object; requires isinstance(obj, type)\n" 4328"super(type, type2) -> bound super object; requires issubclass(type2, type)\n" 4329"Typical use to call a cooperative superclass method:\n" 4330"class C(B):\n" 4331" def meth(self, arg):\n" 4332" super(C, self).meth(arg)"; 4333 4334static int 4335super_traverse(PyObject *self, visitproc visit, void *arg) 4336{ 4337 superobject *su = (superobject *)self; 4338 int err; 4339 4340#define VISIT(SLOT) \ 4341 if (SLOT) { \ 4342 err = visit((PyObject *)(SLOT), arg); \ 4343 if (err) \ 4344 return err; \ 4345 } 4346 4347 VISIT(su->obj); 4348 VISIT(su->type); 4349 4350#undef VISIT 4351 4352 return 0; 4353} 4354 4355PyTypeObject PySuper_Type = { 4356 PyObject_HEAD_INIT(&PyType_Type) 4357 0, /* ob_size */ 4358 "super", /* tp_name */ 4359 sizeof(superobject), /* tp_basicsize */ 4360 0, /* tp_itemsize */ 4361 /* methods */ 4362 super_dealloc, /* tp_dealloc */ 4363 0, /* tp_print */ 4364 0, /* tp_getattr */ 4365 0, /* tp_setattr */ 4366 0, /* tp_compare */ 4367 super_repr, /* tp_repr */ 4368 0, /* tp_as_number */ 4369 0, /* tp_as_sequence */ 4370 0, /* tp_as_mapping */ 4371 0, /* tp_hash */ 4372 0, /* tp_call */ 4373 0, /* tp_str */ 4374 super_getattro, /* tp_getattro */ 4375 0, /* tp_setattro */ 4376 0, /* tp_as_buffer */ 4377 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | 4378 Py_TPFLAGS_BASETYPE, /* tp_flags */ 4379 super_doc, /* tp_doc */ 4380 super_traverse, /* tp_traverse */ 4381 0, /* tp_clear */ 4382 0, /* tp_richcompare */ 4383 0, /* tp_weaklistoffset */ 4384 0, /* tp_iter */ 4385 0, /* tp_iternext */ 4386 0, /* tp_methods */ 4387 super_members, /* tp_members */ 4388 0, /* tp_getset */ 4389 0, /* tp_base */ 4390 0, /* tp_dict */ 4391 super_descr_get, /* tp_descr_get */ 4392 0, /* tp_descr_set */ 4393 0, /* tp_dictoffset */ 4394 super_init, /* tp_init */ 4395 PyType_GenericAlloc, /* tp_alloc */ 4396 PyType_GenericNew, /* tp_new */ 4397 PyObject_GC_Del, /* tp_free */ 4398}; 4399