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