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