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