PageRenderTime 59ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/classobject.c

http://unladen-swallow.googlecode.com/
C | 2689 lines | 2347 code | 215 blank | 127 comment | 730 complexity | 60d08320b03f22639ec127f56863a7cf MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /* Class object implementation */
  2. #include "Python.h"
  3. #include "structmember.h"
  4. /* Free list for method objects to safe malloc/free overhead
  5. * The im_self element is used to chain the elements.
  6. */
  7. static PyMethodObject *free_list;
  8. static int numfree = 0;
  9. #ifndef PyMethod_MAXFREELIST
  10. #define PyMethod_MAXFREELIST 256
  11. #endif
  12. #define TP_DESCR_GET(t) \
  13. (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
  14. /* Forward */
  15. static PyObject *class_lookup(PyClassObject *, PyObject *,
  16. PyClassObject **);
  17. static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
  18. static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
  19. static PyObject *getattrstr, *setattrstr, *delattrstr;
  20. PyObject *
  21. PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
  22. /* bases is NULL or tuple of classobjects! */
  23. {
  24. PyClassObject *op, *dummy;
  25. static PyObject *docstr, *modstr, *namestr;
  26. if (docstr == NULL) {
  27. docstr= PyString_InternFromString("__doc__");
  28. if (docstr == NULL)
  29. return NULL;
  30. }
  31. if (modstr == NULL) {
  32. modstr= PyString_InternFromString("__module__");
  33. if (modstr == NULL)
  34. return NULL;
  35. }
  36. if (namestr == NULL) {
  37. namestr= PyString_InternFromString("__name__");
  38. if (namestr == NULL)
  39. return NULL;
  40. }
  41. if (name == NULL || !PyString_Check(name)) {
  42. PyErr_SetString(PyExc_TypeError,
  43. "PyClass_New: name must be a string");
  44. return NULL;
  45. }
  46. if (dict == NULL || !PyDict_Check(dict)) {
  47. PyErr_SetString(PyExc_TypeError,
  48. "PyClass_New: dict must be a dictionary");
  49. return NULL;
  50. }
  51. if (PyDict_GetItem(dict, docstr) == NULL) {
  52. if (PyDict_SetItem(dict, docstr, Py_None) < 0)
  53. return NULL;
  54. }
  55. if (PyDict_GetItem(dict, modstr) == NULL) {
  56. PyObject *globals = PyEval_GetGlobals();
  57. if (globals != NULL) {
  58. PyObject *modname = PyDict_GetItem(globals, namestr);
  59. if (modname != NULL) {
  60. if (PyDict_SetItem(dict, modstr, modname) < 0)
  61. return NULL;
  62. }
  63. }
  64. }
  65. if (bases == NULL) {
  66. bases = PyTuple_New(0);
  67. if (bases == NULL)
  68. return NULL;
  69. }
  70. else {
  71. Py_ssize_t i, n;
  72. PyObject *base;
  73. if (!PyTuple_Check(bases)) {
  74. PyErr_SetString(PyExc_TypeError,
  75. "PyClass_New: bases must be a tuple");
  76. return NULL;
  77. }
  78. n = PyTuple_Size(bases);
  79. for (i = 0; i < n; i++) {
  80. base = PyTuple_GET_ITEM(bases, i);
  81. if (!PyClass_Check(base)) {
  82. if (PyCallable_Check(
  83. (PyObject *) base->ob_type))
  84. return PyObject_CallFunctionObjArgs(
  85. (PyObject *) base->ob_type,
  86. name, bases, dict, NULL);
  87. PyErr_SetString(PyExc_TypeError,
  88. "PyClass_New: base must be a class");
  89. return NULL;
  90. }
  91. }
  92. Py_INCREF(bases);
  93. }
  94. if (getattrstr == NULL) {
  95. getattrstr = PyString_InternFromString("__getattr__");
  96. if (getattrstr == NULL)
  97. goto alloc_error;
  98. setattrstr = PyString_InternFromString("__setattr__");
  99. if (setattrstr == NULL)
  100. goto alloc_error;
  101. delattrstr = PyString_InternFromString("__delattr__");
  102. if (delattrstr == NULL)
  103. goto alloc_error;
  104. }
  105. op = PyObject_GC_New(PyClassObject, &PyClass_Type);
  106. if (op == NULL) {
  107. alloc_error:
  108. Py_DECREF(bases);
  109. return NULL;
  110. }
  111. op->cl_bases = bases;
  112. Py_INCREF(dict);
  113. op->cl_dict = dict;
  114. Py_XINCREF(name);
  115. op->cl_name = name;
  116. op->cl_getattr = class_lookup(op, getattrstr, &dummy);
  117. op->cl_setattr = class_lookup(op, setattrstr, &dummy);
  118. op->cl_delattr = class_lookup(op, delattrstr, &dummy);
  119. Py_XINCREF(op->cl_getattr);
  120. Py_XINCREF(op->cl_setattr);
  121. Py_XINCREF(op->cl_delattr);
  122. _PyObject_GC_TRACK(op);
  123. return (PyObject *) op;
  124. }
  125. PyObject *
  126. PyMethod_Function(PyObject *im)
  127. {
  128. if (!PyMethod_Check(im)) {
  129. PyErr_BadInternalCall();
  130. return NULL;
  131. }
  132. return ((PyMethodObject *)im)->im_func;
  133. }
  134. PyObject *
  135. PyMethod_Self(PyObject *im)
  136. {
  137. if (!PyMethod_Check(im)) {
  138. PyErr_BadInternalCall();
  139. return NULL;
  140. }
  141. return ((PyMethodObject *)im)->im_self;
  142. }
  143. PyObject *
  144. PyMethod_Class(PyObject *im)
  145. {
  146. if (!PyMethod_Check(im)) {
  147. PyErr_BadInternalCall();
  148. return NULL;
  149. }
  150. return ((PyMethodObject *)im)->im_class;
  151. }
  152. PyDoc_STRVAR(class_doc,
  153. "classobj(name, bases, dict)\n\
  154. \n\
  155. Create a class object. The name must be a string; the second argument\n\
  156. a tuple of classes, and the third a dictionary.");
  157. static PyObject *
  158. class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  159. {
  160. PyObject *name, *bases, *dict;
  161. static char *kwlist[] = {"name", "bases", "dict", 0};
  162. if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
  163. &name, &bases, &dict))
  164. return NULL;
  165. return PyClass_New(bases, dict, name);
  166. }
  167. /* Class methods */
  168. static void
  169. class_dealloc(PyClassObject *op)
  170. {
  171. _PyObject_GC_UNTRACK(op);
  172. Py_DECREF(op->cl_bases);
  173. Py_DECREF(op->cl_dict);
  174. Py_XDECREF(op->cl_name);
  175. Py_XDECREF(op->cl_getattr);
  176. Py_XDECREF(op->cl_setattr);
  177. Py_XDECREF(op->cl_delattr);
  178. PyObject_GC_Del(op);
  179. }
  180. static PyObject *
  181. class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
  182. {
  183. Py_ssize_t i, n;
  184. PyObject *value = PyDict_GetItem(cp->cl_dict, name);
  185. if (value != NULL) {
  186. *pclass = cp;
  187. return value;
  188. }
  189. n = PyTuple_Size(cp->cl_bases);
  190. for (i = 0; i < n; i++) {
  191. /* XXX What if one of the bases is not a class? */
  192. PyObject *v = class_lookup(
  193. (PyClassObject *)
  194. PyTuple_GetItem(cp->cl_bases, i), name, pclass);
  195. if (v != NULL)
  196. return v;
  197. }
  198. return NULL;
  199. }
  200. static PyObject *
  201. class_getattr(register PyClassObject *op, PyObject *name)
  202. {
  203. register PyObject *v;
  204. register char *sname = PyString_AsString(name);
  205. PyClassObject *klass;
  206. descrgetfunc f;
  207. if (sname[0] == '_' && sname[1] == '_') {
  208. if (strcmp(sname, "__dict__") == 0) {
  209. if (PyEval_GetRestricted()) {
  210. PyErr_SetString(PyExc_RuntimeError,
  211. "class.__dict__ not accessible in restricted mode");
  212. return NULL;
  213. }
  214. Py_INCREF(op->cl_dict);
  215. return op->cl_dict;
  216. }
  217. if (strcmp(sname, "__bases__") == 0) {
  218. Py_INCREF(op->cl_bases);
  219. return op->cl_bases;
  220. }
  221. if (strcmp(sname, "__name__") == 0) {
  222. if (op->cl_name == NULL)
  223. v = Py_None;
  224. else
  225. v = op->cl_name;
  226. Py_INCREF(v);
  227. return v;
  228. }
  229. }
  230. v = class_lookup(op, name, &klass);
  231. if (v == NULL) {
  232. PyErr_Format(PyExc_AttributeError,
  233. "class %.50s has no attribute '%.400s'",
  234. PyString_AS_STRING(op->cl_name), sname);
  235. return NULL;
  236. }
  237. f = TP_DESCR_GET(v->ob_type);
  238. if (f == NULL)
  239. Py_INCREF(v);
  240. else
  241. v = f(v, (PyObject *)NULL, (PyObject *)op);
  242. return v;
  243. }
  244. static void
  245. set_slot(PyObject **slot, PyObject *v)
  246. {
  247. PyObject *temp = *slot;
  248. Py_XINCREF(v);
  249. *slot = v;
  250. Py_XDECREF(temp);
  251. }
  252. static void
  253. set_attr_slots(PyClassObject *c)
  254. {
  255. PyClassObject *dummy;
  256. set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
  257. set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
  258. set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
  259. }
  260. static char *
  261. set_dict(PyClassObject *c, PyObject *v)
  262. {
  263. if (v == NULL || !PyDict_Check(v))
  264. return "__dict__ must be a dictionary object";
  265. set_slot(&c->cl_dict, v);
  266. set_attr_slots(c);
  267. return "";
  268. }
  269. static char *
  270. set_bases(PyClassObject *c, PyObject *v)
  271. {
  272. Py_ssize_t i, n;
  273. if (v == NULL || !PyTuple_Check(v))
  274. return "__bases__ must be a tuple object";
  275. n = PyTuple_Size(v);
  276. for (i = 0; i < n; i++) {
  277. PyObject *x = PyTuple_GET_ITEM(v, i);
  278. if (!PyClass_Check(x))
  279. return "__bases__ items must be classes";
  280. if (PyClass_IsSubclass(x, (PyObject *)c))
  281. return "a __bases__ item causes an inheritance cycle";
  282. }
  283. set_slot(&c->cl_bases, v);
  284. set_attr_slots(c);
  285. return "";
  286. }
  287. static char *
  288. set_name(PyClassObject *c, PyObject *v)
  289. {
  290. if (v == NULL || !PyString_Check(v))
  291. return "__name__ must be a string object";
  292. if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
  293. return "__name__ must not contain null bytes";
  294. set_slot(&c->cl_name, v);
  295. return "";
  296. }
  297. static int
  298. class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
  299. {
  300. char *sname;
  301. if (PyEval_GetRestricted()) {
  302. PyErr_SetString(PyExc_RuntimeError,
  303. "classes are read-only in restricted mode");
  304. return -1;
  305. }
  306. sname = PyString_AsString(name);
  307. if (sname[0] == '_' && sname[1] == '_') {
  308. Py_ssize_t n = PyString_Size(name);
  309. if (sname[n-1] == '_' && sname[n-2] == '_') {
  310. char *err = NULL;
  311. if (strcmp(sname, "__dict__") == 0)
  312. err = set_dict(op, v);
  313. else if (strcmp(sname, "__bases__") == 0)
  314. err = set_bases(op, v);
  315. else if (strcmp(sname, "__name__") == 0)
  316. err = set_name(op, v);
  317. else if (strcmp(sname, "__getattr__") == 0)
  318. set_slot(&op->cl_getattr, v);
  319. else if (strcmp(sname, "__setattr__") == 0)
  320. set_slot(&op->cl_setattr, v);
  321. else if (strcmp(sname, "__delattr__") == 0)
  322. set_slot(&op->cl_delattr, v);
  323. /* For the last three, we fall through to update the
  324. dictionary as well. */
  325. if (err != NULL) {
  326. if (*err == '\0')
  327. return 0;
  328. PyErr_SetString(PyExc_TypeError, err);
  329. return -1;
  330. }
  331. }
  332. }
  333. if (v == NULL) {
  334. int rv = PyDict_DelItem(op->cl_dict, name);
  335. if (rv < 0)
  336. PyErr_Format(PyExc_AttributeError,
  337. "class %.50s has no attribute '%.400s'",
  338. PyString_AS_STRING(op->cl_name), sname);
  339. return rv;
  340. }
  341. else
  342. return PyDict_SetItem(op->cl_dict, name, v);
  343. }
  344. static PyObject *
  345. class_repr(PyClassObject *op)
  346. {
  347. PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
  348. char *name;
  349. if (op->cl_name == NULL || !PyString_Check(op->cl_name))
  350. name = "?";
  351. else
  352. name = PyString_AsString(op->cl_name);
  353. if (mod == NULL || !PyString_Check(mod))
  354. return PyString_FromFormat("<class ?.%s at %p>", name, op);
  355. else
  356. return PyString_FromFormat("<class %s.%s at %p>",
  357. PyString_AsString(mod),
  358. name, op);
  359. }
  360. static PyObject *
  361. class_str(PyClassObject *op)
  362. {
  363. PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
  364. PyObject *name = op->cl_name;
  365. PyObject *res;
  366. Py_ssize_t m, n;
  367. if (name == NULL || !PyString_Check(name))
  368. return class_repr(op);
  369. if (mod == NULL || !PyString_Check(mod)) {
  370. Py_INCREF(name);
  371. return name;
  372. }
  373. m = PyString_GET_SIZE(mod);
  374. n = PyString_GET_SIZE(name);
  375. res = PyString_FromStringAndSize((char *)NULL, m+1+n);
  376. if (res != NULL) {
  377. char *s = PyString_AS_STRING(res);
  378. memcpy(s, PyString_AS_STRING(mod), m);
  379. s += m;
  380. *s++ = '.';
  381. memcpy(s, PyString_AS_STRING(name), n);
  382. }
  383. return res;
  384. }
  385. static int
  386. class_traverse(PyClassObject *o, visitproc visit, void *arg)
  387. {
  388. Py_VISIT(o->cl_bases);
  389. Py_VISIT(o->cl_dict);
  390. Py_VISIT(o->cl_name);
  391. Py_VISIT(o->cl_getattr);
  392. Py_VISIT(o->cl_setattr);
  393. Py_VISIT(o->cl_delattr);
  394. return 0;
  395. }
  396. PyTypeObject PyClass_Type = {
  397. PyObject_HEAD_INIT(&PyType_Type)
  398. 0,
  399. "classobj",
  400. sizeof(PyClassObject),
  401. 0,
  402. (destructor)class_dealloc, /* tp_dealloc */
  403. 0, /* tp_print */
  404. 0, /* tp_getattr */
  405. 0, /* tp_setattr */
  406. 0, /* tp_compare */
  407. (reprfunc)class_repr, /* tp_repr */
  408. 0, /* tp_as_number */
  409. 0, /* tp_as_sequence */
  410. 0, /* tp_as_mapping */
  411. 0, /* tp_hash */
  412. PyInstance_New, /* tp_call */
  413. (reprfunc)class_str, /* tp_str */
  414. (getattrofunc)class_getattr, /* tp_getattro */
  415. (setattrofunc)class_setattr, /* tp_setattro */
  416. 0, /* tp_as_buffer */
  417. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  418. class_doc, /* tp_doc */
  419. (traverseproc)class_traverse, /* tp_traverse */
  420. 0, /* tp_clear */
  421. 0, /* tp_richcompare */
  422. 0, /* tp_weaklistoffset */
  423. 0, /* tp_iter */
  424. 0, /* tp_iternext */
  425. 0, /* tp_methods */
  426. 0, /* tp_members */
  427. 0, /* tp_getset */
  428. 0, /* tp_base */
  429. 0, /* tp_dict */
  430. 0, /* tp_descr_get */
  431. 0, /* tp_descr_set */
  432. 0, /* tp_dictoffset */
  433. 0, /* tp_init */
  434. 0, /* tp_alloc */
  435. class_new, /* tp_new */
  436. };
  437. int
  438. PyClass_IsSubclass(PyObject *klass, PyObject *base)
  439. {
  440. Py_ssize_t i, n;
  441. PyClassObject *cp;
  442. if (klass == base)
  443. return 1;
  444. if (PyTuple_Check(base)) {
  445. n = PyTuple_GET_SIZE(base);
  446. for (i = 0; i < n; i++) {
  447. if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
  448. return 1;
  449. }
  450. return 0;
  451. }
  452. if (klass == NULL || !PyClass_Check(klass))
  453. return 0;
  454. cp = (PyClassObject *)klass;
  455. n = PyTuple_Size(cp->cl_bases);
  456. for (i = 0; i < n; i++) {
  457. if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
  458. return 1;
  459. }
  460. return 0;
  461. }
  462. /* Instance objects */
  463. PyObject *
  464. PyInstance_NewRaw(PyObject *klass, PyObject *dict)
  465. {
  466. PyInstanceObject *inst;
  467. if (!PyClass_Check(klass)) {
  468. PyErr_BadInternalCall();
  469. return NULL;
  470. }
  471. if (dict == NULL) {
  472. dict = PyDict_New();
  473. if (dict == NULL)
  474. return NULL;
  475. }
  476. else {
  477. if (!PyDict_Check(dict)) {
  478. PyErr_BadInternalCall();
  479. return NULL;
  480. }
  481. Py_INCREF(dict);
  482. }
  483. inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
  484. if (inst == NULL) {
  485. Py_DECREF(dict);
  486. return NULL;
  487. }
  488. inst->in_weakreflist = NULL;
  489. Py_INCREF(klass);
  490. inst->in_class = (PyClassObject *)klass;
  491. inst->in_dict = dict;
  492. _PyObject_GC_TRACK(inst);
  493. return (PyObject *)inst;
  494. }
  495. PyObject *
  496. PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
  497. {
  498. register PyInstanceObject *inst;
  499. PyObject *init;
  500. static PyObject *initstr;
  501. if (initstr == NULL) {
  502. initstr = PyString_InternFromString("__init__");
  503. if (initstr == NULL)
  504. return NULL;
  505. }
  506. inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
  507. if (inst == NULL)
  508. return NULL;
  509. init = instance_getattr2(inst, initstr);
  510. if (init == NULL) {
  511. if (PyErr_Occurred()) {
  512. Py_DECREF(inst);
  513. return NULL;
  514. }
  515. if ((arg != NULL && (!PyTuple_Check(arg) ||
  516. PyTuple_Size(arg) != 0))
  517. || (kw != NULL && (!PyDict_Check(kw) ||
  518. PyDict_Size(kw) != 0))) {
  519. PyErr_SetString(PyExc_TypeError,
  520. "this constructor takes no arguments");
  521. Py_DECREF(inst);
  522. inst = NULL;
  523. }
  524. }
  525. else {
  526. PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
  527. Py_DECREF(init);
  528. if (res == NULL) {
  529. Py_DECREF(inst);
  530. inst = NULL;
  531. }
  532. else {
  533. if (res != Py_None) {
  534. PyErr_SetString(PyExc_TypeError,
  535. "__init__() should return None");
  536. Py_DECREF(inst);
  537. inst = NULL;
  538. }
  539. Py_DECREF(res);
  540. }
  541. }
  542. return (PyObject *)inst;
  543. }
  544. /* Instance methods */
  545. PyDoc_STRVAR(instance_doc,
  546. "instance(class[, dict])\n\
  547. \n\
  548. Create an instance without calling its __init__() method.\n\
  549. The class must be a classic class.\n\
  550. If present, dict must be a dictionary or None.");
  551. static PyObject *
  552. instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
  553. {
  554. PyObject *klass;
  555. PyObject *dict = Py_None;
  556. if (!PyArg_ParseTuple(args, "O!|O:instance",
  557. &PyClass_Type, &klass, &dict))
  558. return NULL;
  559. if (dict == Py_None)
  560. dict = NULL;
  561. else if (!PyDict_Check(dict)) {
  562. PyErr_SetString(PyExc_TypeError,
  563. "instance() second arg must be dictionary or None");
  564. return NULL;
  565. }
  566. return PyInstance_NewRaw(klass, dict);
  567. }
  568. static void
  569. instance_dealloc(register PyInstanceObject *inst)
  570. {
  571. PyObject *error_type, *error_value, *error_traceback;
  572. PyObject *del;
  573. static PyObject *delstr;
  574. _PyObject_GC_UNTRACK(inst);
  575. if (inst->in_weakreflist != NULL)
  576. PyObject_ClearWeakRefs((PyObject *) inst);
  577. /* Temporarily resurrect the object. */
  578. assert(inst->ob_type == &PyInstance_Type);
  579. assert(inst->ob_refcnt == 0);
  580. inst->ob_refcnt = 1;
  581. /* Save the current exception, if any. */
  582. PyErr_Fetch(&error_type, &error_value, &error_traceback);
  583. /* Execute __del__ method, if any. */
  584. if (delstr == NULL) {
  585. delstr = PyString_InternFromString("__del__");
  586. if (delstr == NULL)
  587. PyErr_WriteUnraisable((PyObject*)inst);
  588. }
  589. if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
  590. PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
  591. if (res == NULL)
  592. PyErr_WriteUnraisable(del);
  593. else
  594. Py_DECREF(res);
  595. Py_DECREF(del);
  596. }
  597. /* Restore the saved exception. */
  598. PyErr_Restore(error_type, error_value, error_traceback);
  599. /* Undo the temporary resurrection; can't use DECREF here, it would
  600. * cause a recursive call.
  601. */
  602. assert(inst->ob_refcnt > 0);
  603. if (--inst->ob_refcnt == 0) {
  604. /* New weakrefs could be created during the finalizer call.
  605. If this occurs, clear them out without calling their
  606. finalizers since they might rely on part of the object
  607. being finalized that has already been destroyed. */
  608. while (inst->in_weakreflist != NULL) {
  609. _PyWeakref_ClearRef((PyWeakReference *)
  610. (inst->in_weakreflist));
  611. }
  612. Py_DECREF(inst->in_class);
  613. Py_XDECREF(inst->in_dict);
  614. PyObject_GC_Del(inst);
  615. }
  616. else {
  617. Py_ssize_t refcnt = inst->ob_refcnt;
  618. /* __del__ resurrected it! Make it look like the original
  619. * Py_DECREF never happened.
  620. */
  621. _Py_NewReference((PyObject *)inst);
  622. inst->ob_refcnt = refcnt;
  623. _PyObject_GC_TRACK(inst);
  624. /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
  625. * we need to undo that. */
  626. _Py_DEC_REFTOTAL;
  627. /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
  628. * object chain, so no more to do there.
  629. * If COUNT_ALLOCS, the original decref bumped tp_frees, and
  630. * _Py_NewReference bumped tp_allocs: both of those need to be
  631. * undone.
  632. */
  633. #ifdef COUNT_ALLOCS
  634. --inst->ob_type->tp_frees;
  635. --inst->ob_type->tp_allocs;
  636. #endif
  637. }
  638. }
  639. static PyObject *
  640. instance_getattr1(register PyInstanceObject *inst, PyObject *name)
  641. {
  642. register PyObject *v;
  643. register char *sname = PyString_AsString(name);
  644. if (sname[0] == '_' && sname[1] == '_') {
  645. if (strcmp(sname, "__dict__") == 0) {
  646. if (PyEval_GetRestricted()) {
  647. PyErr_SetString(PyExc_RuntimeError,
  648. "instance.__dict__ not accessible in restricted mode");
  649. return NULL;
  650. }
  651. Py_INCREF(inst->in_dict);
  652. return inst->in_dict;
  653. }
  654. if (strcmp(sname, "__class__") == 0) {
  655. Py_INCREF(inst->in_class);
  656. return (PyObject *)inst->in_class;
  657. }
  658. }
  659. v = instance_getattr2(inst, name);
  660. if (v == NULL && !PyErr_Occurred()) {
  661. PyErr_Format(PyExc_AttributeError,
  662. "%.50s instance has no attribute '%.400s'",
  663. PyString_AS_STRING(inst->in_class->cl_name), sname);
  664. }
  665. return v;
  666. }
  667. static PyObject *
  668. instance_getattr2(register PyInstanceObject *inst, PyObject *name)
  669. {
  670. register PyObject *v;
  671. PyClassObject *klass;
  672. descrgetfunc f;
  673. v = PyDict_GetItem(inst->in_dict, name);
  674. if (v != NULL) {
  675. Py_INCREF(v);
  676. return v;
  677. }
  678. v = class_lookup(inst->in_class, name, &klass);
  679. if (v != NULL) {
  680. Py_INCREF(v);
  681. f = TP_DESCR_GET(v->ob_type);
  682. if (f != NULL) {
  683. PyObject *w = f(v, (PyObject *)inst,
  684. (PyObject *)(inst->in_class));
  685. Py_DECREF(v);
  686. v = w;
  687. }
  688. }
  689. return v;
  690. }
  691. static PyObject *
  692. instance_getattr(register PyInstanceObject *inst, PyObject *name)
  693. {
  694. register PyObject *func, *res;
  695. res = instance_getattr1(inst, name);
  696. if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
  697. PyObject *args;
  698. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  699. return NULL;
  700. PyErr_Clear();
  701. args = PyTuple_Pack(2, inst, name);
  702. if (args == NULL)
  703. return NULL;
  704. res = PyEval_CallObject(func, args);
  705. Py_DECREF(args);
  706. }
  707. return res;
  708. }
  709. /* See classobject.h comments: this only does dict lookups, and is always
  710. * safe to call.
  711. */
  712. PyObject *
  713. _PyInstance_Lookup(PyObject *pinst, PyObject *name)
  714. {
  715. PyObject *v;
  716. PyClassObject *klass;
  717. PyInstanceObject *inst; /* pinst cast to the right type */
  718. assert(PyInstance_Check(pinst));
  719. inst = (PyInstanceObject *)pinst;
  720. assert(PyString_Check(name));
  721. v = PyDict_GetItem(inst->in_dict, name);
  722. if (v == NULL)
  723. v = class_lookup(inst->in_class, name, &klass);
  724. return v;
  725. }
  726. static int
  727. instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
  728. {
  729. if (v == NULL) {
  730. int rv = PyDict_DelItem(inst->in_dict, name);
  731. if (rv < 0)
  732. PyErr_Format(PyExc_AttributeError,
  733. "%.50s instance has no attribute '%.400s'",
  734. PyString_AS_STRING(inst->in_class->cl_name),
  735. PyString_AS_STRING(name));
  736. return rv;
  737. }
  738. else
  739. return PyDict_SetItem(inst->in_dict, name, v);
  740. }
  741. static int
  742. instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
  743. {
  744. PyObject *func, *args, *res, *tmp;
  745. char *sname = PyString_AsString(name);
  746. if (sname[0] == '_' && sname[1] == '_') {
  747. Py_ssize_t n = PyString_Size(name);
  748. if (sname[n-1] == '_' && sname[n-2] == '_') {
  749. if (strcmp(sname, "__dict__") == 0) {
  750. if (PyEval_GetRestricted()) {
  751. PyErr_SetString(PyExc_RuntimeError,
  752. "__dict__ not accessible in restricted mode");
  753. return -1;
  754. }
  755. if (v == NULL || !PyDict_Check(v)) {
  756. PyErr_SetString(PyExc_TypeError,
  757. "__dict__ must be set to a dictionary");
  758. return -1;
  759. }
  760. tmp = inst->in_dict;
  761. Py_INCREF(v);
  762. inst->in_dict = v;
  763. Py_DECREF(tmp);
  764. return 0;
  765. }
  766. if (strcmp(sname, "__class__") == 0) {
  767. if (PyEval_GetRestricted()) {
  768. PyErr_SetString(PyExc_RuntimeError,
  769. "__class__ not accessible in restricted mode");
  770. return -1;
  771. }
  772. if (v == NULL || !PyClass_Check(v)) {
  773. PyErr_SetString(PyExc_TypeError,
  774. "__class__ must be set to a class");
  775. return -1;
  776. }
  777. tmp = (PyObject *)(inst->in_class);
  778. Py_INCREF(v);
  779. inst->in_class = (PyClassObject *)v;
  780. Py_DECREF(tmp);
  781. return 0;
  782. }
  783. }
  784. }
  785. if (v == NULL)
  786. func = inst->in_class->cl_delattr;
  787. else
  788. func = inst->in_class->cl_setattr;
  789. if (func == NULL)
  790. return instance_setattr1(inst, name, v);
  791. if (v == NULL)
  792. args = PyTuple_Pack(2, inst, name);
  793. else
  794. args = PyTuple_Pack(3, inst, name, v);
  795. if (args == NULL)
  796. return -1;
  797. res = PyEval_CallObject(func, args);
  798. Py_DECREF(args);
  799. if (res == NULL)
  800. return -1;
  801. Py_DECREF(res);
  802. return 0;
  803. }
  804. static PyObject *
  805. instance_repr(PyInstanceObject *inst)
  806. {
  807. PyObject *func;
  808. PyObject *res;
  809. static PyObject *reprstr;
  810. if (reprstr == NULL) {
  811. reprstr = PyString_InternFromString("__repr__");
  812. if (reprstr == NULL)
  813. return NULL;
  814. }
  815. func = instance_getattr(inst, reprstr);
  816. if (func == NULL) {
  817. PyObject *classname, *mod;
  818. char *cname;
  819. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  820. return NULL;
  821. PyErr_Clear();
  822. classname = inst->in_class->cl_name;
  823. mod = PyDict_GetItemString(inst->in_class->cl_dict,
  824. "__module__");
  825. if (classname != NULL && PyString_Check(classname))
  826. cname = PyString_AsString(classname);
  827. else
  828. cname = "?";
  829. if (mod == NULL || !PyString_Check(mod))
  830. return PyString_FromFormat("<?.%s instance at %p>",
  831. cname, inst);
  832. else
  833. return PyString_FromFormat("<%s.%s instance at %p>",
  834. PyString_AsString(mod),
  835. cname, inst);
  836. }
  837. res = PyEval_CallObject(func, (PyObject *)NULL);
  838. Py_DECREF(func);
  839. return res;
  840. }
  841. static PyObject *
  842. instance_str(PyInstanceObject *inst)
  843. {
  844. PyObject *func;
  845. PyObject *res;
  846. static PyObject *strstr;
  847. if (strstr == NULL) {
  848. strstr = PyString_InternFromString("__str__");
  849. if (strstr == NULL)
  850. return NULL;
  851. }
  852. func = instance_getattr(inst, strstr);
  853. if (func == NULL) {
  854. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  855. return NULL;
  856. PyErr_Clear();
  857. return instance_repr(inst);
  858. }
  859. res = PyEval_CallObject(func, (PyObject *)NULL);
  860. Py_DECREF(func);
  861. return res;
  862. }
  863. static long
  864. instance_hash(PyInstanceObject *inst)
  865. {
  866. PyObject *func;
  867. PyObject *res;
  868. long outcome;
  869. static PyObject *hashstr, *eqstr, *cmpstr;
  870. if (hashstr == NULL) {
  871. hashstr = PyString_InternFromString("__hash__");
  872. if (hashstr == NULL)
  873. return -1;
  874. }
  875. func = instance_getattr(inst, hashstr);
  876. if (func == NULL) {
  877. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  878. return -1;
  879. PyErr_Clear();
  880. /* If there is no __eq__ and no __cmp__ method, we hash on the
  881. address. If an __eq__ or __cmp__ method exists, there must
  882. be a __hash__. */
  883. if (eqstr == NULL) {
  884. eqstr = PyString_InternFromString("__eq__");
  885. if (eqstr == NULL)
  886. return -1;
  887. }
  888. func = instance_getattr(inst, eqstr);
  889. if (func == NULL) {
  890. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  891. return -1;
  892. PyErr_Clear();
  893. if (cmpstr == NULL) {
  894. cmpstr = PyString_InternFromString("__cmp__");
  895. if (cmpstr == NULL)
  896. return -1;
  897. }
  898. func = instance_getattr(inst, cmpstr);
  899. if (func == NULL) {
  900. if (!PyErr_ExceptionMatches(
  901. PyExc_AttributeError))
  902. return -1;
  903. PyErr_Clear();
  904. return _Py_HashPointer(inst);
  905. }
  906. }
  907. Py_XDECREF(func);
  908. PyErr_SetString(PyExc_TypeError, "unhashable instance");
  909. return -1;
  910. }
  911. res = PyEval_CallObject(func, (PyObject *)NULL);
  912. Py_DECREF(func);
  913. if (res == NULL)
  914. return -1;
  915. if (PyInt_Check(res) || PyLong_Check(res))
  916. /* This already converts a -1 result to -2. */
  917. outcome = res->ob_type->tp_hash(res);
  918. else {
  919. PyErr_SetString(PyExc_TypeError,
  920. "__hash__() should return an int");
  921. outcome = -1;
  922. }
  923. Py_DECREF(res);
  924. return outcome;
  925. }
  926. static int
  927. instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
  928. {
  929. Py_VISIT(o->in_class);
  930. Py_VISIT(o->in_dict);
  931. return 0;
  932. }
  933. static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
  934. static PyObject *iterstr, *nextstr;
  935. static Py_ssize_t
  936. instance_length(PyInstanceObject *inst)
  937. {
  938. PyObject *func;
  939. PyObject *res;
  940. Py_ssize_t outcome;
  941. if (lenstr == NULL) {
  942. lenstr = PyString_InternFromString("__len__");
  943. if (lenstr == NULL)
  944. return -1;
  945. }
  946. func = instance_getattr(inst, lenstr);
  947. if (func == NULL)
  948. return -1;
  949. res = PyEval_CallObject(func, (PyObject *)NULL);
  950. Py_DECREF(func);
  951. if (res == NULL)
  952. return -1;
  953. if (PyInt_Check(res)) {
  954. outcome = PyInt_AsSsize_t(res);
  955. if (outcome == -1 && PyErr_Occurred()) {
  956. Py_DECREF(res);
  957. return -1;
  958. }
  959. #if SIZEOF_SIZE_T < SIZEOF_INT
  960. /* Overflow check -- range of PyInt is more than C int */
  961. if (outcome != (int)outcome) {
  962. PyErr_SetString(PyExc_OverflowError,
  963. "__len__() should return 0 <= outcome < 2**31");
  964. outcome = -1;
  965. }
  966. else
  967. #endif
  968. if (outcome < 0) {
  969. PyErr_SetString(PyExc_ValueError,
  970. "__len__() should return >= 0");
  971. outcome = -1;
  972. }
  973. }
  974. else {
  975. PyErr_SetString(PyExc_TypeError,
  976. "__len__() should return an int");
  977. outcome = -1;
  978. }
  979. Py_DECREF(res);
  980. return outcome;
  981. }
  982. static PyObject *
  983. instance_subscript(PyInstanceObject *inst, PyObject *key)
  984. {
  985. PyObject *func;
  986. PyObject *arg;
  987. PyObject *res;
  988. if (getitemstr == NULL) {
  989. getitemstr = PyString_InternFromString("__getitem__");
  990. if (getitemstr == NULL)
  991. return NULL;
  992. }
  993. func = instance_getattr(inst, getitemstr);
  994. if (func == NULL)
  995. return NULL;
  996. arg = PyTuple_Pack(1, key);
  997. if (arg == NULL) {
  998. Py_DECREF(func);
  999. return NULL;
  1000. }
  1001. res = PyEval_CallObject(func, arg);
  1002. Py_DECREF(func);
  1003. Py_DECREF(arg);
  1004. return res;
  1005. }
  1006. static int
  1007. instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
  1008. {
  1009. PyObject *func;
  1010. PyObject *arg;
  1011. PyObject *res;
  1012. if (value == NULL) {
  1013. if (delitemstr == NULL) {
  1014. delitemstr = PyString_InternFromString("__delitem__");
  1015. if (delitemstr == NULL)
  1016. return -1;
  1017. }
  1018. func = instance_getattr(inst, delitemstr);
  1019. }
  1020. else {
  1021. if (setitemstr == NULL) {
  1022. setitemstr = PyString_InternFromString("__setitem__");
  1023. if (setitemstr == NULL)
  1024. return -1;
  1025. }
  1026. func = instance_getattr(inst, setitemstr);
  1027. }
  1028. if (func == NULL)
  1029. return -1;
  1030. if (value == NULL)
  1031. arg = PyTuple_Pack(1, key);
  1032. else
  1033. arg = PyTuple_Pack(2, key, value);
  1034. if (arg == NULL) {
  1035. Py_DECREF(func);
  1036. return -1;
  1037. }
  1038. res = PyEval_CallObject(func, arg);
  1039. Py_DECREF(func);
  1040. Py_DECREF(arg);
  1041. if (res == NULL)
  1042. return -1;
  1043. Py_DECREF(res);
  1044. return 0;
  1045. }
  1046. static PyMappingMethods instance_as_mapping = {
  1047. (lenfunc)instance_length, /* mp_length */
  1048. (binaryfunc)instance_subscript, /* mp_subscript */
  1049. (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
  1050. };
  1051. static PyObject *
  1052. instance_item(PyInstanceObject *inst, Py_ssize_t i)
  1053. {
  1054. PyObject *func, *res;
  1055. if (getitemstr == NULL) {
  1056. getitemstr = PyString_InternFromString("__getitem__");
  1057. if (getitemstr == NULL)
  1058. return NULL;
  1059. }
  1060. func = instance_getattr(inst, getitemstr);
  1061. if (func == NULL)
  1062. return NULL;
  1063. res = PyObject_CallFunction(func, "n", i);
  1064. Py_DECREF(func);
  1065. return res;
  1066. }
  1067. static PyObject *
  1068. instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
  1069. {
  1070. PyObject *func, *arg, *res;
  1071. static PyObject *getslicestr;
  1072. if (getslicestr == NULL) {
  1073. getslicestr = PyString_InternFromString("__getslice__");
  1074. if (getslicestr == NULL)
  1075. return NULL;
  1076. }
  1077. func = instance_getattr(inst, getslicestr);
  1078. if (func == NULL) {
  1079. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1080. return NULL;
  1081. PyErr_Clear();
  1082. if (getitemstr == NULL) {
  1083. getitemstr = PyString_InternFromString("__getitem__");
  1084. if (getitemstr == NULL)
  1085. return NULL;
  1086. }
  1087. func = instance_getattr(inst, getitemstr);
  1088. if (func == NULL)
  1089. return NULL;
  1090. arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
  1091. }
  1092. else {
  1093. if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
  1094. "use __getitem__", 1) < 0) {
  1095. Py_DECREF(func);
  1096. return NULL;
  1097. }
  1098. arg = Py_BuildValue("(nn)", i, j);
  1099. }
  1100. if (arg == NULL) {
  1101. Py_DECREF(func);
  1102. return NULL;
  1103. }
  1104. res = PyEval_CallObject(func, arg);
  1105. Py_DECREF(func);
  1106. Py_DECREF(arg);
  1107. return res;
  1108. }
  1109. static int
  1110. instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
  1111. {
  1112. PyObject *func, *arg, *res;
  1113. if (item == NULL) {
  1114. if (delitemstr == NULL) {
  1115. delitemstr = PyString_InternFromString("__delitem__");
  1116. if (delitemstr == NULL)
  1117. return -1;
  1118. }
  1119. func = instance_getattr(inst, delitemstr);
  1120. }
  1121. else {
  1122. if (setitemstr == NULL) {
  1123. setitemstr = PyString_InternFromString("__setitem__");
  1124. if (setitemstr == NULL)
  1125. return -1;
  1126. }
  1127. func = instance_getattr(inst, setitemstr);
  1128. }
  1129. if (func == NULL)
  1130. return -1;
  1131. if (item == NULL)
  1132. arg = PyInt_FromSsize_t(i);
  1133. else
  1134. arg = Py_BuildValue("(nO)", i, item);
  1135. if (arg == NULL) {
  1136. Py_DECREF(func);
  1137. return -1;
  1138. }
  1139. res = PyEval_CallObject(func, arg);
  1140. Py_DECREF(func);
  1141. Py_DECREF(arg);
  1142. if (res == NULL)
  1143. return -1;
  1144. Py_DECREF(res);
  1145. return 0;
  1146. }
  1147. static int
  1148. instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
  1149. {
  1150. PyObject *func, *arg, *res;
  1151. static PyObject *setslicestr, *delslicestr;
  1152. if (value == NULL) {
  1153. if (delslicestr == NULL) {
  1154. delslicestr =
  1155. PyString_InternFromString("__delslice__");
  1156. if (delslicestr == NULL)
  1157. return -1;
  1158. }
  1159. func = instance_getattr(inst, delslicestr);
  1160. if (func == NULL) {
  1161. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1162. return -1;
  1163. PyErr_Clear();
  1164. if (delitemstr == NULL) {
  1165. delitemstr =
  1166. PyString_InternFromString("__delitem__");
  1167. if (delitemstr == NULL)
  1168. return -1;
  1169. }
  1170. func = instance_getattr(inst, delitemstr);
  1171. if (func == NULL)
  1172. return -1;
  1173. arg = Py_BuildValue("(N)",
  1174. _PySlice_FromIndices(i, j));
  1175. }
  1176. else {
  1177. if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
  1178. "removed; use __delitem__", 1) < 0) {
  1179. Py_DECREF(func);
  1180. return -1;
  1181. }
  1182. arg = Py_BuildValue("(nn)", i, j);
  1183. }
  1184. }
  1185. else {
  1186. if (setslicestr == NULL) {
  1187. setslicestr =
  1188. PyString_InternFromString("__setslice__");
  1189. if (setslicestr == NULL)
  1190. return -1;
  1191. }
  1192. func = instance_getattr(inst, setslicestr);
  1193. if (func == NULL) {
  1194. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1195. return -1;
  1196. PyErr_Clear();
  1197. if (setitemstr == NULL) {
  1198. setitemstr =
  1199. PyString_InternFromString("__setitem__");
  1200. if (setitemstr == NULL)
  1201. return -1;
  1202. }
  1203. func = instance_getattr(inst, setitemstr);
  1204. if (func == NULL)
  1205. return -1;
  1206. arg = Py_BuildValue("(NO)",
  1207. _PySlice_FromIndices(i, j), value);
  1208. }
  1209. else {
  1210. if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
  1211. "removed; use __setitem__", 1) < 0) {
  1212. Py_DECREF(func);
  1213. return -1;
  1214. }
  1215. arg = Py_BuildValue("(nnO)", i, j, value);
  1216. }
  1217. }
  1218. if (arg == NULL) {
  1219. Py_DECREF(func);
  1220. return -1;
  1221. }
  1222. res = PyEval_CallObject(func, arg);
  1223. Py_DECREF(func);
  1224. Py_DECREF(arg);
  1225. if (res == NULL)
  1226. return -1;
  1227. Py_DECREF(res);
  1228. return 0;
  1229. }
  1230. static int
  1231. instance_contains(PyInstanceObject *inst, PyObject *member)
  1232. {
  1233. static PyObject *__contains__;
  1234. PyObject *func;
  1235. /* Try __contains__ first.
  1236. * If that can't be done, try iterator-based searching.
  1237. */
  1238. if(__contains__ == NULL) {
  1239. __contains__ = PyString_InternFromString("__contains__");
  1240. if(__contains__ == NULL)
  1241. return -1;
  1242. }
  1243. func = instance_getattr(inst, __contains__);
  1244. if (func) {
  1245. PyObject *res;
  1246. int ret;
  1247. PyObject *arg = PyTuple_Pack(1, member);
  1248. if(arg == NULL) {
  1249. Py_DECREF(func);
  1250. return -1;
  1251. }
  1252. res = PyEval_CallObject(func, arg);
  1253. Py_DECREF(func);
  1254. Py_DECREF(arg);
  1255. if(res == NULL)
  1256. return -1;
  1257. ret = PyObject_IsTrue(res);
  1258. Py_DECREF(res);
  1259. return ret;
  1260. }
  1261. /* Couldn't find __contains__. */
  1262. if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
  1263. Py_ssize_t rc;
  1264. /* Assume the failure was simply due to that there is no
  1265. * __contains__ attribute, and try iterating instead.
  1266. */
  1267. PyErr_Clear();
  1268. rc = _PySequence_IterSearch((PyObject *)inst, member,
  1269. PY_ITERSEARCH_CONTAINS);
  1270. if (rc >= 0)
  1271. return rc > 0;
  1272. }
  1273. return -1;
  1274. }
  1275. static PySequenceMethods
  1276. instance_as_sequence = {
  1277. (lenfunc)instance_length, /* sq_length */
  1278. 0, /* sq_concat */
  1279. 0, /* sq_repeat */
  1280. (ssizeargfunc)instance_item, /* sq_item */
  1281. (ssizessizeargfunc)instance_slice, /* sq_slice */
  1282. (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
  1283. (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
  1284. (objobjproc)instance_contains, /* sq_contains */
  1285. };
  1286. static PyObject *
  1287. generic_unary_op(PyInstanceObject *self, PyObject *methodname)
  1288. {
  1289. PyObject *func, *res;
  1290. if ((func = instance_getattr(self, methodname)) == NULL)
  1291. return NULL;
  1292. res = PyEval_CallObject(func, (PyObject *)NULL);
  1293. Py_DECREF(func);
  1294. return res;
  1295. }
  1296. static PyObject *
  1297. generic_binary_op(PyObject *v, PyObject *w, char *opname)
  1298. {
  1299. PyObject *result;
  1300. PyObject *args;
  1301. PyObject *func = PyObject_GetAttrString(v, opname);
  1302. if (func == NULL) {
  1303. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1304. return NULL;
  1305. PyErr_Clear();
  1306. Py_INCREF(Py_NotImplemented);
  1307. return Py_NotImplemented;
  1308. }
  1309. args = PyTuple_Pack(1, w);
  1310. if (args == NULL) {
  1311. Py_DECREF(func);
  1312. return NULL;
  1313. }
  1314. result = PyEval_CallObject(func, args);
  1315. Py_DECREF(args);
  1316. Py_DECREF(func);
  1317. return result;
  1318. }
  1319. static PyObject *coerce_obj;
  1320. /* Try one half of a binary operator involving a class instance. */
  1321. static PyObject *
  1322. half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
  1323. int swapped)
  1324. {
  1325. PyObject *args;
  1326. PyObject *coercefunc;
  1327. PyObject *coerced = NULL;
  1328. PyObject *v1;
  1329. PyObject *result;
  1330. if (!PyInstance_Check(v)) {
  1331. Py_INCREF(Py_NotImplemented);
  1332. return Py_NotImplemented;
  1333. }
  1334. if (coerce_obj == NULL) {
  1335. coerce_obj = PyString_InternFromString("__coerce__");
  1336. if (coerce_obj == NULL)
  1337. return NULL;
  1338. }
  1339. coercefunc = PyObject_GetAttr(v, coerce_obj);
  1340. if (coercefunc == NULL) {
  1341. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1342. return NULL;
  1343. PyErr_Clear();
  1344. return generic_binary_op(v, w, opname);
  1345. }
  1346. args = PyTuple_Pack(1, w);
  1347. if (args == NULL) {
  1348. Py_DECREF(coercefunc);
  1349. return NULL;
  1350. }
  1351. coerced = PyEval_CallObject(coercefunc, args);
  1352. Py_DECREF(args);
  1353. Py_DECREF(coercefunc);
  1354. if (coerced == NULL) {
  1355. return NULL;
  1356. }
  1357. if (coerced == Py_None || coerced == Py_NotImplemented) {
  1358. Py_DECREF(coerced);
  1359. return generic_binary_op(v, w, opname);
  1360. }
  1361. if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
  1362. Py_DECREF(coerced);
  1363. PyErr_SetString(PyExc_TypeError,
  1364. "coercion should return None or 2-tuple");
  1365. return NULL;
  1366. }
  1367. v1 = PyTuple_GetItem(coerced, 0);
  1368. w = PyTuple_GetItem(coerced, 1);
  1369. if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
  1370. /* prevent recursion if __coerce__ returns self as the first
  1371. * argument */
  1372. result = generic_binary_op(v1, w, opname);
  1373. } else {
  1374. if (Py_EnterRecursiveCall(" after coercion"))
  1375. return NULL;
  1376. if (swapped)
  1377. result = (thisfunc)(w, v1);
  1378. else
  1379. result = (thisfunc)(v1, w);
  1380. Py_LeaveRecursiveCall();
  1381. }
  1382. Py_DECREF(coerced);
  1383. return result;
  1384. }
  1385. /* Implement a binary operator involving at least one class instance. */
  1386. static PyObject *
  1387. do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
  1388. binaryfunc thisfunc)
  1389. {
  1390. PyObject *result = half_binop(v, w, opname, thisfunc, 0);
  1391. if (result == Py_NotImplemented) {
  1392. Py_DECREF(result);
  1393. result = half_binop(w, v, ropname, thisfunc, 1);
  1394. }
  1395. return result;
  1396. }
  1397. static PyObject *
  1398. do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
  1399. char *ropname, binaryfunc thisfunc)
  1400. {
  1401. PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
  1402. if (result == Py_NotImplemented) {
  1403. Py_DECREF(result);
  1404. result = do_binop(v, w, opname, ropname, thisfunc);
  1405. }
  1406. return result;
  1407. }
  1408. static int
  1409. instance_coerce(PyObject **pv, PyObject **pw)
  1410. {
  1411. PyObject *v = *pv;
  1412. PyObject *w = *pw;
  1413. PyObject *coercefunc;
  1414. PyObject *args;
  1415. PyObject *coerced;
  1416. if (coerce_obj == NULL) {
  1417. coerce_obj = PyString_InternFromString("__coerce__");
  1418. if (coerce_obj == NULL)
  1419. return -1;
  1420. }
  1421. coercefunc = PyObject_GetAttr(v, coerce_obj);
  1422. if (coercefunc == NULL) {
  1423. /* No __coerce__ method */
  1424. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1425. return -1;
  1426. PyErr_Clear();
  1427. return 1;
  1428. }
  1429. /* Has __coerce__ method: call it */
  1430. args = PyTuple_Pack(1, w);
  1431. if (args == NULL) {
  1432. return -1;
  1433. }
  1434. coerced = PyEval_CallObject(coercefunc, args);
  1435. Py_DECREF(args);
  1436. Py_DECREF(coercefunc);
  1437. if (coerced == NULL) {
  1438. /* __coerce__ call raised an exception */
  1439. return -1;
  1440. }
  1441. if (coerced == Py_None || coerced == Py_NotImplemented) {
  1442. /* __coerce__ says "I can't do it" */
  1443. Py_DECREF(coerced);
  1444. return 1;
  1445. }
  1446. if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
  1447. /* __coerce__ return value is malformed */
  1448. Py_DECREF(coerced);
  1449. PyErr_SetString(PyExc_TypeError,
  1450. "coercion should return None or 2-tuple");
  1451. return -1;
  1452. }
  1453. /* __coerce__ returned two new values */
  1454. *pv = PyTuple_GetItem(coerced, 0);
  1455. *pw = PyTuple_GetItem(coerced, 1);
  1456. Py_INCREF(*pv);
  1457. Py_INCREF(*pw);
  1458. Py_DECREF(coerced);
  1459. return 0;
  1460. }
  1461. #define UNARY(funcname, methodname) \
  1462. static PyObject *funcname(PyInstanceObject *self) { \
  1463. static PyObject *o; \
  1464. if (o == NULL) { o = PyString_InternFromString(methodname); \
  1465. if (o == NULL) return NULL; } \
  1466. return generic_unary_op(self, o); \
  1467. }
  1468. /* unary function with a fallback */
  1469. #define UNARY_FB(funcname, methodname, funcname_fb) \
  1470. static PyObject *funcname(PyInstanceObject *self) { \
  1471. static PyObject *o; \
  1472. if (o == NULL) { o = PyString_InternFromString(methodname); \
  1473. if (o == NULL) return NULL; } \
  1474. if (PyObject_HasAttr((PyObject*)self, o)) \
  1475. return generic_unary_op(self, o); \
  1476. else \
  1477. return funcname_fb(self); \
  1478. }
  1479. #define BINARY(f, m, n) \
  1480. static PyObject *f(PyObject *v, PyObject *w) { \
  1481. return do_binop(v, w, "__" m "__", "__r" m "__", n); \
  1482. }
  1483. #define BINARY_INPLACE(f, m, n) \
  1484. static PyObject *f(PyObject *v, PyObject *w) { \
  1485. return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
  1486. "__r" m "__", n); \
  1487. }
  1488. UNARY(instance_neg, "__neg__")
  1489. UNARY(instance_pos, "__pos__")
  1490. UNARY(instance_abs, "__abs__")
  1491. BINARY(instance_or, "or", PyNumber_Or)
  1492. BINARY(instance_and, "and", PyNumber_And)
  1493. BINARY(instance_xor, "xor", PyNumber_Xor)
  1494. BINARY(instance_lshift, "lshift", PyNumber_Lshift)
  1495. BINARY(instance_rshift, "rshift", PyNumber_Rshift)
  1496. BINARY(instance_add, "add", PyNumber_Add)
  1497. BINARY(instance_sub, "sub", PyNumber_Subtract)
  1498. BINARY(instance_mul, "mul", PyNumber_Multiply)
  1499. BINARY(instance_div, "div", PyNumber_Divide)
  1500. BINARY(instance_mod, "mod", PyNumber_Remainder)
  1501. BINARY(instance_divmod, "divmod", PyNumber_Divmod)
  1502. BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
  1503. BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
  1504. BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
  1505. BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
  1506. BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
  1507. BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
  1508. BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
  1509. BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
  1510. BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
  1511. BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
  1512. BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
  1513. BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
  1514. BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
  1515. BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
  1516. /* Try a 3-way comparison, returning an int; v is an instance. Return:
  1517. -2 for an exception;
  1518. -1 if v < w;
  1519. 0 if v == w;
  1520. 1 if v > w;
  1521. 2 if this particular 3-way comparison is not implemented or undefined.
  1522. */
  1523. static int
  1524. half_cmp(PyObject *v, PyObject *w)
  1525. {
  1526. static PyObject *cmp_obj;
  1527. PyObject *args;
  1528. PyObject *cmp_func;
  1529. PyObject *result;
  1530. long l;
  1531. assert(PyInstance_Check(v));
  1532. if (cmp_obj == NULL) {
  1533. cmp_obj = PyString_InternFromString("__cmp__");
  1534. if (cmp_obj == NULL)
  1535. return -2;
  1536. }
  1537. cmp_func = PyObject_GetAttr(v, cmp_obj);
  1538. if (cmp_func == NULL) {
  1539. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1540. return -2;
  1541. PyErr_Clear();
  1542. return 2;
  1543. }
  1544. args = PyTuple_Pack(1, w);
  1545. if (args == NULL) {
  1546. Py_DECREF(cmp_func);
  1547. return -2;
  1548. }
  1549. result = PyEval_CallObject(cmp_func, args);
  1550. Py_DECREF(args);
  1551. Py_DECREF(cmp_func);
  1552. if (result == NULL)
  1553. return -2;
  1554. if (result == Py_NotImplemented) {
  1555. Py_DECREF(result);
  1556. return 2;
  1557. }
  1558. l = PyInt_AsLong(result);
  1559. Py_DECREF(result);
  1560. if (l == -1 && PyErr_Occurred()) {
  1561. PyErr_SetString(PyExc_TypeError,
  1562. "comparison did not return an int");
  1563. return -2;
  1564. }
  1565. return l < 0 ? -1 : l > 0 ? 1 : 0;
  1566. }
  1567. /* Try a 3-way comparison, returning an int; either v or w is an instance.
  1568. We first try a coercion. Return:
  1569. -2 for an exception;
  1570. -1 if v < w;
  1571. 0 if v == w;
  1572. 1 if v > w;
  1573. 2 if this particular 3-way comparison is not implemented or undefined.
  1574. THIS IS ONLY CALLED FROM object.c!
  1575. */
  1576. static int
  1577. instance_compare(PyObject *v, PyObject *w)
  1578. {
  1579. int c;
  1580. c = PyNumber_CoerceEx(&v, &w);
  1581. if (c < 0)
  1582. return -2;
  1583. if (c == 0) {
  1584. /* If neither is now an instance, use regular comparison */
  1585. if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
  1586. c = PyObject_Compare(v, w);
  1587. Py_DECREF(v);
  1588. Py_DECREF(w);
  1589. if (PyErr_Occurred())
  1590. return -2;
  1591. return c < 0 ? -1 : c > 0 ? 1 : 0;
  1592. }
  1593. }
  1594. else {
  1595. /* The coercion didn't do anything.
  1596. Treat this the same as returning v and w unchanged. */
  1597. Py_INCREF(v);
  1598. Py_INCREF(w);
  1599. }
  1600. if (PyInstance_Check(v)) {
  1601. c = half_cmp(v, w);
  1602. if (c <= 1) {
  1603. Py_DECREF(v);
  1604. Py_DECREF(w);
  1605. return c;
  1606. }
  1607. }
  1608. if (PyInstance_Check(w)) {
  1609. c = half_cmp(w, v);
  1610. if (c <= 1) {
  1611. Py_DECREF(v);
  1612. Py_DECREF(w);
  1613. if (c >= -1)
  1614. c = -c;
  1615. return c;
  1616. }
  1617. }
  1618. Py_DECREF(v);
  1619. Py_DECREF(w);
  1620. return 2;
  1621. }
  1622. static int
  1623. instance_nonzero(PyInstanceObject *self)
  1624. {
  1625. PyObject *func, *res;
  1626. long outcome;
  1627. static PyObject *nonzerostr;
  1628. if (nonzerostr == NULL) {
  1629. nonzerostr = PyString_InternFromString("__nonzero__");
  1630. if (nonzerostr == NULL)
  1631. return -1;
  1632. }
  1633. if ((func = instance_getattr(self, nonzerostr)) == NULL) {
  1634. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1635. return -1;
  1636. PyErr_Clear();
  1637. if (lenstr == NULL) {
  1638. lenstr = PyString_InternFromString("__len__");
  1639. if (lenstr == NULL)
  1640. return -1;
  1641. }
  1642. if ((func = instance_getattr(self, lenstr)) == NULL) {
  1643. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1644. return -1;
  1645. PyErr_Clear();
  1646. /* Fall back to the default behavior:
  1647. all instances are nonzero */
  1648. return 1;
  1649. }
  1650. }
  1651. res = PyEval_CallObject(func, (PyObject *)NULL);
  1652. Py_DECREF(func);
  1653. if (res == NULL)
  1654. return -1;
  1655. if (!PyInt_Check(res)) {
  1656. Py_DECREF(res);
  1657. PyErr_SetString(PyExc_TypeError,
  1658. "__nonzero__ should return an int");
  1659. return -1;
  1660. }
  1661. outcome = PyInt_AsLong(res);
  1662. Py_DECREF(res);
  1663. if (outcome < 0) {
  1664. PyErr_SetString(PyExc_ValueError,
  1665. "__nonzero__ should return >= 0");
  1666. return -1;
  1667. }
  1668. return outcome > 0;
  1669. }
  1670. static PyObject *
  1671. instance_index(PyInstanceObject *self)
  1672. {
  1673. PyObject *func, *res;
  1674. static PyObject *indexstr = NULL;
  1675. if (indexstr == NULL) {
  1676. indexstr = PyString_InternFromString("__index__");
  1677. if (indexstr == NULL)
  1678. return NULL;
  1679. }
  1680. if ((func = instance_getattr(self, indexstr)) == NULL) {
  1681. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1682. return NULL;
  1683. PyErr_Clear();
  1684. PyErr_SetString(PyExc_TypeError,
  1685. "object cannot be interpreted as an index");
  1686. return NULL;
  1687. }
  1688. res = PyEval_CallObject(func, (PyObject *)NULL);
  1689. Py_DECREF(func);
  1690. return res;
  1691. }
  1692. UNARY(instance_invert, "__invert__")
  1693. UNARY(_instance_trunc, "__trunc__")
  1694. static PyObject *
  1695. instance_int(PyInstanceObject *self)
  1696. {
  1697. PyObject *truncated;
  1698. static PyObject *int_name;
  1699. if (int_name == NULL) {
  1700. int_name = PyString_InternFromString("__int__");
  1701. if (int_name == NULL)
  1702. return NULL;
  1703. }
  1704. if (PyObject_HasAttr((PyObject*)self, int_name))
  1705. return generic_unary_op(self, int_name);
  1706. truncated = _instance_trunc(self);
  1707. /* __trunc__ is specified to return an Integral type, but
  1708. int() needs to return an int. */
  1709. return _PyNumber_ConvertIntegralToInt(
  1710. truncated,
  1711. "__trunc__ returned non-Integral (type %.200s)");
  1712. }
  1713. UNARY_FB(instance_long, "__long__", instance_int)
  1714. UNARY(instance_float, "__float__")
  1715. UNARY(instance_oct, "__oct__")
  1716. UNARY(instance_hex, "__hex__")
  1717. static PyObject *
  1718. bin_power(PyObject *v, PyObject *w)
  1719. {
  1720. return PyNumber_Power(v, w, Py_None);
  1721. }
  1722. /* This version is for ternary calls only (z != None) */
  1723. static PyObject *
  1724. instance_pow(PyObject *v, PyObject *w, PyObject *z)
  1725. {
  1726. if (z == Py_None) {
  1727. return do_binop(v, w, "__pow__", "__rpow__", bin_power);
  1728. }
  1729. else {
  1730. PyObject *func;
  1731. PyObject *args;
  1732. PyObject *result;
  1733. /* XXX Doesn't do coercions... */
  1734. func = PyObject_GetAttrString(v, "__pow__");
  1735. if (func == NULL)
  1736. return NULL;
  1737. args = PyTuple_Pack(2, w, z);
  1738. if (args == NULL) {
  1739. Py_DECREF(func);
  1740. return NULL;
  1741. }
  1742. result = PyEval_CallObject(func, args);
  1743. Py_DECREF(func);
  1744. Py_DECREF(args);
  1745. return result;
  1746. }
  1747. }
  1748. static PyObject *
  1749. bin_inplace_power(PyObject *v, PyObject *w)
  1750. {
  1751. return PyNumber_InPlacePower(v, w, Py_None);
  1752. }
  1753. static PyObject *
  1754. instance_ipow(PyObject *v, PyObject *w, PyObject *z)
  1755. {
  1756. if (z == Py_None) {
  1757. return do_binop_inplace(v, w, "__ipow__", "__pow__",
  1758. "__rpow__", bin_inplace_power);
  1759. }
  1760. else {
  1761. /* XXX Doesn't do coercions... */
  1762. PyObject *func;
  1763. PyObject *args;
  1764. PyObject *result;
  1765. func = PyObject_GetAttrString(v, "__ipow__");
  1766. if (func == NULL) {
  1767. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1768. return NULL;
  1769. PyErr_Clear();
  1770. return instance_pow(v, w, z);
  1771. }
  1772. args = PyTuple_Pack(2, w, z);
  1773. if (args == NULL) {
  1774. Py_DECREF(func);
  1775. return NULL;
  1776. }
  1777. result = PyEval_CallObject(func, args);
  1778. Py_DECREF(func);
  1779. Py_DECREF(args);
  1780. return result;
  1781. }
  1782. }
  1783. /* Map rich comparison operators to their __xx__ namesakes */
  1784. #define NAME_OPS 6
  1785. static PyObject **name_op = NULL;
  1786. static int
  1787. init_name_op(void)
  1788. {
  1789. int i;
  1790. char *_name_op[] = {
  1791. "__lt__",
  1792. "__le__",
  1793. "__eq__",
  1794. "__ne__",
  1795. "__gt__",
  1796. "__ge__",
  1797. };
  1798. name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
  1799. if (name_op == NULL)
  1800. return -1;
  1801. for (i = 0; i < NAME_OPS; ++i) {
  1802. name_op[i] = PyString_InternFromString(_name_op[i]);
  1803. if (name_op[i] == NULL)
  1804. return -1;
  1805. }
  1806. return 0;
  1807. }
  1808. static PyObject *
  1809. half_richcompare(PyObject *v, PyObject *w, int op)
  1810. {
  1811. PyObject *method;
  1812. PyObject *args;
  1813. PyObject *res;
  1814. assert(PyInstance_Check(v));
  1815. if (name_op == NULL) {
  1816. if (init_name_op() < 0)
  1817. return NULL;
  1818. }
  1819. /* If the instance doesn't define an __getattr__ method, use
  1820. instance_getattr2 directly because it will not set an
  1821. exception on failure. */
  1822. if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
  1823. method = instance_getattr2((PyInstanceObject *)v,
  1824. name_op[op]);
  1825. else
  1826. method = PyObject_GetAttr(v, name_op[op]);
  1827. if (method == NULL) {
  1828. if (PyErr_Occurred()) {
  1829. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1830. return NULL;
  1831. PyErr_Clear();
  1832. }
  1833. res = Py_NotImplemented;
  1834. Py_INCREF(res);
  1835. return res;
  1836. }
  1837. args = PyTuple_Pack(1, w);
  1838. if (args == NULL) {
  1839. Py_DECREF(method);
  1840. return NULL;
  1841. }
  1842. res = PyEval_CallObject(method, args);
  1843. Py_DECREF(args);
  1844. Py_DECREF(method);
  1845. return res;
  1846. }
  1847. static PyObject *
  1848. instance_richcompare(PyObject *v, PyObject *w, int op)
  1849. {
  1850. PyObject *res;
  1851. if (PyInstance_Check(v)) {
  1852. res = half_richcompare(v, w, op);
  1853. if (res != Py_NotImplemented)
  1854. return res;
  1855. Py_DECREF(res);
  1856. }
  1857. if (PyInstance_Check(w)) {
  1858. res = half_richcompare(w, v, _Py_SwappedOp[op]);
  1859. if (res != Py_NotImplemented)
  1860. return res;
  1861. Py_DECREF(res);
  1862. }
  1863. Py_INCREF(Py_NotImplemented);
  1864. return Py_NotImplemented;
  1865. }
  1866. /* Get the iterator */
  1867. static PyObject *
  1868. instance_getiter(PyInstanceObject *self)
  1869. {
  1870. PyObject *func;
  1871. if (iterstr == NULL) {
  1872. iterstr = PyString_InternFromString("__iter__");
  1873. if (iterstr == NULL)
  1874. return NULL;
  1875. }
  1876. if (getitemstr == NULL) {
  1877. getitemstr = PyString_InternFromString("__getitem__");
  1878. if (getitemstr == NULL)
  1879. return NULL;
  1880. }
  1881. if ((func = instance_getattr(self, iterstr)) != NULL) {
  1882. PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
  1883. Py_DECREF(func);
  1884. if (res != NULL && !PyIter_Check(res)) {
  1885. PyErr_Format(PyExc_TypeError,
  1886. "__iter__ returned non-iterator "
  1887. "of type '%.100s'",
  1888. res->ob_type->tp_name);
  1889. Py_DECREF(res);
  1890. res = NULL;
  1891. }
  1892. return res;
  1893. }
  1894. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1895. return NULL;
  1896. PyErr_Clear();
  1897. if ((func = instance_getattr(self, getitemstr)) == NULL) {
  1898. PyErr_SetString(PyExc_TypeError,
  1899. "iteration over non-sequence");
  1900. return NULL;
  1901. }
  1902. Py_DECREF(func);
  1903. return PySeqIter_New((PyObject *)self);
  1904. }
  1905. /* Call the iterator's next */
  1906. static PyObject *
  1907. instance_iternext(PyInstanceObject *self)
  1908. {
  1909. PyObject *func;
  1910. if (nextstr == NULL) {
  1911. nextstr = PyString_InternFromString("next");
  1912. if (nextstr == NULL)
  1913. return NULL;
  1914. }
  1915. if ((func = instance_getattr(self, nextstr)) != NULL) {
  1916. PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
  1917. Py_DECREF(func);
  1918. if (res != NULL) {
  1919. return res;
  1920. }
  1921. if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
  1922. PyErr_Clear();
  1923. return NULL;
  1924. }
  1925. return NULL;
  1926. }
  1927. PyErr_SetString(PyExc_TypeError, "instance has no next() method");
  1928. return NULL;
  1929. }
  1930. static PyObject *
  1931. instance_call(PyObject *func, PyObject *arg, PyObject *kw)
  1932. {
  1933. PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
  1934. if (call == NULL) {
  1935. PyInstanceObject *inst = (PyInstanceObject*) func;
  1936. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  1937. return NULL;
  1938. PyErr_Clear();
  1939. PyErr_Format(PyExc_AttributeError,
  1940. "%.200s instance has no __call__ method",
  1941. PyString_AsString(inst->in_class->cl_name));
  1942. return NULL;
  1943. }
  1944. /* We must check and increment the recursion depth here. Scenario:
  1945. class A:
  1946. pass
  1947. A.__call__ = A() # that's right
  1948. a = A() # ok
  1949. a() # infinite recursion
  1950. This bounces between instance_call() and PyObject_Call() without
  1951. ever hitting eval_frame() (which has the main recursion check). */
  1952. if (Py_EnterRecursiveCall(" in __call__")) {
  1953. res = NULL;
  1954. }
  1955. else {
  1956. res = PyObject_Call(call, arg, kw);
  1957. Py_LeaveRecursiveCall();
  1958. }
  1959. Py_DECREF(call);
  1960. return res;
  1961. }
  1962. static PyNumberMethods instance_as_number = {
  1963. instance_add, /* nb_add */
  1964. instance_sub, /* nb_subtract */
  1965. instance_mul, /* nb_multiply */
  1966. instance_div, /* nb_divide */
  1967. instance_mod, /* nb_remainder */
  1968. instance_divmod, /* nb_divmod */
  1969. instance_pow, /* nb_power */
  1970. (unaryfunc)instance_neg, /* nb_negative */
  1971. (unaryfunc)instance_pos, /* nb_positive */
  1972. (unaryfunc)instance_abs, /* nb_absolute */
  1973. (inquiry)instance_nonzero, /* nb_nonzero */
  1974. (unaryfunc)instance_invert, /* nb_invert */
  1975. instance_lshift, /* nb_lshift */
  1976. instance_rshift, /* nb_rshift */
  1977. instance_and, /* nb_and */
  1978. instance_xor, /* nb_xor */
  1979. instance_or, /* nb_or */
  1980. instance_coerce, /* nb_coerce */
  1981. (unaryfunc)instance_int, /* nb_int */
  1982. (unaryfunc)instance_long, /* nb_long */
  1983. (unaryfunc)instance_float, /* nb_float */
  1984. (unaryfunc)instance_oct, /* nb_oct */
  1985. (unaryfunc)instance_hex, /* nb_hex */
  1986. instance_iadd, /* nb_inplace_add */
  1987. instance_isub, /* nb_inplace_subtract */
  1988. instance_imul, /* nb_inplace_multiply */
  1989. instance_idiv, /* nb_inplace_divide */
  1990. instance_imod, /* nb_inplace_remainder */
  1991. instance_ipow, /* nb_inplace_power */
  1992. instance_ilshift, /* nb_inplace_lshift */
  1993. instance_irshift, /* nb_inplace_rshift */
  1994. instance_iand, /* nb_inplace_and */
  1995. instance_ixor, /* nb_inplace_xor */
  1996. instance_ior, /* nb_inplace_or */
  1997. instance_floordiv, /* nb_floor_divide */
  1998. instance_truediv, /* nb_true_divide */
  1999. instance_ifloordiv, /* nb_inplace_floor_divide */
  2000. instance_itruediv, /* nb_inplace_true_divide */
  2001. (unaryfunc)instance_index, /* nb_index */
  2002. };
  2003. PyTypeObject PyInstance_Type = {
  2004. PyObject_HEAD_INIT(&PyType_Type)
  2005. 0,
  2006. "instance",
  2007. sizeof(PyInstanceObject),
  2008. 0,
  2009. (destructor)instance_dealloc, /* tp_dealloc */
  2010. 0, /* tp_print */
  2011. 0, /* tp_getattr */
  2012. 0, /* tp_setattr */
  2013. instance_compare, /* tp_compare */
  2014. (reprfunc)instance_repr, /* tp_repr */
  2015. &instance_as_number, /* tp_as_number */
  2016. &instance_as_sequence, /* tp_as_sequence */
  2017. &instance_as_mapping, /* tp_as_mapping */
  2018. (hashfunc)instance_hash, /* tp_hash */
  2019. instance_call, /* tp_call */
  2020. (reprfunc)instance_str, /* tp_str */
  2021. (getattrofunc)instance_getattr, /* tp_getattro */
  2022. (setattrofunc)instance_setattr, /* tp_setattro */
  2023. 0, /* tp_as_buffer */
  2024. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
  2025. instance_doc, /* tp_doc */
  2026. (traverseproc)instance_traverse, /* tp_traverse */
  2027. 0, /* tp_clear */
  2028. instance_richcompare, /* tp_richcompare */
  2029. offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
  2030. (getiterfunc)instance_getiter, /* tp_iter */
  2031. (iternextfunc)instance_iternext, /* tp_iternext */
  2032. 0, /* tp_methods */
  2033. 0, /* tp_members */
  2034. 0, /* tp_getset */
  2035. 0, /* tp_base */
  2036. 0, /* tp_dict */
  2037. 0, /* tp_descr_get */
  2038. 0, /* tp_descr_set */
  2039. 0, /* tp_dictoffset */
  2040. 0, /* tp_init */
  2041. 0, /* tp_alloc */
  2042. instance_new, /* tp_new */
  2043. };
  2044. /* Instance method objects are used for two purposes:
  2045. (a) as bound instance methods (returned by instancename.methodname)
  2046. (b) as unbound methods (returned by ClassName.methodname)
  2047. In case (b), im_self is NULL
  2048. */
  2049. PyObject *
  2050. PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
  2051. {
  2052. register PyMethodObject *im;
  2053. if (!PyCallable_Check(func)) {
  2054. PyErr_BadInternalCall();
  2055. return NULL;
  2056. }
  2057. im = free_list;
  2058. if (im != NULL) {
  2059. free_list = (PyMethodObject *)(im->im_self);
  2060. PyObject_INIT(im, &PyMethod_Type);
  2061. numfree--;
  2062. }
  2063. else {
  2064. im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
  2065. if (im == NULL)
  2066. return NULL;
  2067. }
  2068. im->im_weakreflist = NULL;
  2069. Py_INCREF(func);
  2070. im->im_func = func;
  2071. Py_XINCREF(self);
  2072. im->im_self = self;
  2073. Py_XINCREF(klass);
  2074. im->im_class = klass;
  2075. _PyObject_GC_TRACK(im);
  2076. return (PyObject *)im;
  2077. }
  2078. /* Descriptors for PyMethod attributes */
  2079. /* im_class, im_func and im_self are stored in the PyMethod object */
  2080. #define OFF(x) offsetof(PyMethodObject, x)
  2081. static PyMemberDef instancemethod_memberlist[] = {
  2082. {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
  2083. "the class associated with a method"},
  2084. {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
  2085. "the function (or other callable) implementing a method"},
  2086. {"__func__", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
  2087. "the function (or other callable) implementing a method"},
  2088. {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
  2089. "the instance to which a method is bound; None for unbound methods"},
  2090. {"__self__", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
  2091. "the instance to which a method is bound; None for unbound methods"},
  2092. {NULL} /* Sentinel */
  2093. };
  2094. /* Christian Tismer argued convincingly that method attributes should
  2095. (nearly) always override function attributes.
  2096. The one exception is __doc__; there's a default __doc__ which
  2097. should only be used for the class, not for instances */
  2098. static PyObject *
  2099. instancemethod_get_doc(PyMethodObject *im, void *context)
  2100. {
  2101. static PyObject *docstr;
  2102. if (docstr == NULL) {
  2103. docstr= PyString_InternFromString("__doc__");
  2104. if (docstr == NULL)
  2105. return NULL;
  2106. }
  2107. return PyObject_GetAttr(im->im_func, docstr);
  2108. }
  2109. static PyGetSetDef instancemethod_getset[] = {
  2110. {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
  2111. {0}
  2112. };
  2113. static PyObject *
  2114. instancemethod_getattro(PyObject *obj, PyObject *name)
  2115. {
  2116. PyMethodObject *im = (PyMethodObject *)obj;
  2117. PyTypeObject *tp = obj->ob_type;
  2118. PyObject *descr = NULL;
  2119. if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
  2120. if (tp->tp_dict == NULL) {
  2121. if (PyType_Ready(tp) < 0)
  2122. return NULL;
  2123. }
  2124. descr = _PyType_Lookup(tp, name);
  2125. }
  2126. if (descr != NULL) {
  2127. descrgetfunc f = TP_DESCR_GET(descr->ob_type);
  2128. if (f != NULL)
  2129. return f(descr, obj, (PyObject *)obj->ob_type);
  2130. else {
  2131. Py_INCREF(descr);
  2132. return descr;
  2133. }
  2134. }
  2135. return PyObject_GetAttr(im->im_func, name);
  2136. }
  2137. PyDoc_STRVAR(instancemethod_doc,
  2138. "instancemethod(function, instance, class)\n\
  2139. \n\
  2140. Create an instance method object.");
  2141. static PyObject *
  2142. instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
  2143. {
  2144. PyObject *func;
  2145. PyObject *self;
  2146. PyObject *classObj = NULL;
  2147. if (!_PyArg_NoKeywords("instancemethod", kw))
  2148. return NULL;
  2149. if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
  2150. &func, &self, &classObj))
  2151. return NULL;
  2152. if (!PyCallable_Check(func)) {
  2153. PyErr_SetString(PyExc_TypeError,
  2154. "first argument must be callable");
  2155. return NULL;
  2156. }
  2157. if (self == Py_None)
  2158. self = NULL;
  2159. if (self == NULL && classObj == NULL) {
  2160. PyErr_SetString(PyExc_TypeError,
  2161. "unbound methods must have non-NULL im_class");
  2162. return NULL;
  2163. }
  2164. return PyMethod_New(func, self, classObj);
  2165. }
  2166. static void
  2167. instancemethod_dealloc(register PyMethodObject *im)
  2168. {
  2169. _PyObject_GC_UNTRACK(im);
  2170. if (im->im_weakreflist != NULL)
  2171. PyObject_ClearWeakRefs((PyObject *)im);
  2172. Py_DECREF(im->im_func);
  2173. Py_XDECREF(im->im_self);
  2174. Py_XDECREF(im->im_class);
  2175. if (numfree < PyMethod_MAXFREELIST) {
  2176. im->im_self = (PyObject *)free_list;
  2177. free_list = im;
  2178. numfree++;
  2179. }
  2180. else {
  2181. PyObject_GC_Del(im);
  2182. }
  2183. }
  2184. static int
  2185. instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
  2186. {
  2187. int cmp;
  2188. cmp = PyObject_Compare(a->im_func, b->im_func);
  2189. if (cmp)
  2190. return cmp;
  2191. if (a->im_self == b->im_self)
  2192. return 0;
  2193. if (a->im_self == NULL || b->im_self == NULL)
  2194. return (a->im_self < b->im_self) ? -1 : 1;
  2195. else
  2196. return PyObject_Compare(a->im_self, b->im_self);
  2197. }
  2198. static PyObject *
  2199. instancemethod_repr(PyMethodObject *a)
  2200. {
  2201. PyObject *self = a->im_self;
  2202. PyObject *func = a->im_func;
  2203. PyObject *klass = a->im_class;
  2204. PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
  2205. char *sfuncname = "?", *sklassname = "?";
  2206. funcname = PyObject_GetAttrString(func, "__name__");
  2207. if (funcname == NULL) {
  2208. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  2209. return NULL;
  2210. PyErr_Clear();
  2211. }
  2212. else if (!PyString_Check(funcname)) {
  2213. Py_DECREF(funcname);
  2214. funcname = NULL;
  2215. }
  2216. else
  2217. sfuncname = PyString_AS_STRING(funcname);
  2218. if (klass == NULL)
  2219. klassname = NULL;
  2220. else {
  2221. klassname = PyObject_GetAttrString(klass, "__name__");
  2222. if (klassname == NULL) {
  2223. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  2224. return NULL;
  2225. PyErr_Clear();
  2226. }
  2227. else if (!PyString_Check(klassname)) {
  2228. Py_DECREF(klassname);
  2229. klassname = NULL;
  2230. }
  2231. else
  2232. sklassname = PyString_AS_STRING(klassname);
  2233. }
  2234. if (self == NULL)
  2235. result = PyString_FromFormat("<unbound method %s.%s>",
  2236. sklassname, sfuncname);
  2237. else {
  2238. /* XXX Shouldn't use repr() here! */
  2239. PyObject *selfrepr = PyObject_Repr(self);
  2240. if (selfrepr == NULL)
  2241. goto fail;
  2242. if (!PyString_Check(selfrepr)) {
  2243. Py_DECREF(selfrepr);
  2244. goto fail;
  2245. }
  2246. result = PyString_FromFormat("<bound method %s.%s of %s>",
  2247. sklassname, sfuncname,
  2248. PyString_AS_STRING(selfrepr));
  2249. Py_DECREF(selfrepr);
  2250. }
  2251. fail:
  2252. Py_XDECREF(funcname);
  2253. Py_XDECREF(klassname);
  2254. return result;
  2255. }
  2256. static long
  2257. instancemethod_hash(PyMethodObject *a)
  2258. {
  2259. long x, y;
  2260. if (a->im_self == NULL)
  2261. x = PyObject_Hash(Py_None);
  2262. else
  2263. x = PyObject_Hash(a->im_self);
  2264. if (x == -1)
  2265. return -1;
  2266. y = PyObject_Hash(a->im_func);
  2267. if (y == -1)
  2268. return -1;
  2269. x = x ^ y;
  2270. if (x == -1)
  2271. x = -2;
  2272. return x;
  2273. }
  2274. static int
  2275. instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
  2276. {
  2277. Py_VISIT(im->im_func);
  2278. Py_VISIT(im->im_self);
  2279. Py_VISIT(im->im_class);
  2280. return 0;
  2281. }
  2282. static void
  2283. getclassname(PyObject *klass, char *buf, int bufsize)
  2284. {
  2285. PyObject *name;
  2286. assert(bufsize > 1);
  2287. strcpy(buf, "?"); /* Default outcome */
  2288. if (klass == NULL)
  2289. return;
  2290. name = PyObject_GetAttrString(klass, "__name__");
  2291. if (name == NULL) {
  2292. /* This function cannot return an exception */
  2293. PyErr_Clear();
  2294. return;
  2295. }
  2296. if (PyString_Check(name)) {
  2297. strncpy(buf, PyString_AS_STRING(name), bufsize);
  2298. buf[bufsize-1] = '\0';
  2299. }
  2300. Py_DECREF(name);
  2301. }
  2302. static void
  2303. getinstclassname(PyObject *inst, char *buf, int bufsize)
  2304. {
  2305. PyObject *klass;
  2306. if (inst == NULL) {
  2307. assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
  2308. strcpy(buf, "nothing");
  2309. return;
  2310. }
  2311. klass = PyObject_GetAttrString(inst, "__class__");
  2312. if (klass == NULL) {
  2313. /* This function cannot return an exception */
  2314. PyErr_Clear();
  2315. klass = (PyObject *)(inst->ob_type);
  2316. Py_INCREF(klass);
  2317. }
  2318. getclassname(klass, buf, bufsize);
  2319. Py_XDECREF(klass);
  2320. }
  2321. static PyObject *
  2322. instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
  2323. {
  2324. PyObject *self = PyMethod_GET_SELF(func);
  2325. PyObject *klass = PyMethod_GET_CLASS(func);
  2326. PyObject *result;
  2327. func = PyMethod_GET_FUNCTION(func);
  2328. if (self == NULL) {
  2329. /* Unbound methods must be called with an instance of
  2330. the class (or a derived class) as first argument */
  2331. int ok;
  2332. if (PyTuple_Size(arg) >= 1)
  2333. self = PyTuple_GET_ITEM(arg, 0);
  2334. if (self == NULL)
  2335. ok = 0;
  2336. else {
  2337. ok = PyObject_IsInstance(self, klass);
  2338. if (ok < 0)
  2339. return NULL;
  2340. }
  2341. if (!ok) {
  2342. char clsbuf[256];
  2343. char instbuf[256];
  2344. getclassname(klass, clsbuf, sizeof(clsbuf));
  2345. getinstclassname(self, instbuf, sizeof(instbuf));
  2346. PyErr_Format(PyExc_TypeError,
  2347. "unbound method %s%s must be called with "
  2348. "%s instance as first argument "
  2349. "(got %s%s instead)",
  2350. PyEval_GetFuncName(func),
  2351. PyEval_GetFuncDesc(func),
  2352. clsbuf,
  2353. instbuf,
  2354. self == NULL ? "" : " instance");
  2355. return NULL;
  2356. }
  2357. Py_INCREF(arg);
  2358. }
  2359. else {
  2360. Py_ssize_t argcount = PyTuple_Size(arg);
  2361. PyObject *newarg = PyTuple_New(argcount + 1);
  2362. int i;
  2363. if (newarg == NULL)
  2364. return NULL;
  2365. Py_INCREF(self);
  2366. PyTuple_SET_ITEM(newarg, 0, self);
  2367. for (i = 0; i < argcount; i++) {
  2368. PyObject *v = PyTuple_GET_ITEM(arg, i);
  2369. Py_XINCREF(v);
  2370. PyTuple_SET_ITEM(newarg, i+1, v);
  2371. }
  2372. arg = newarg;
  2373. }
  2374. result = PyObject_Call((PyObject *)func, arg, kw);
  2375. Py_DECREF(arg);
  2376. return result;
  2377. }
  2378. /* Return true if we should bind the method to obj when getting as an attribute
  2379. of obj. We do not rebind it if it is already bound, or if it is an unbound
  2380. method of a class that's not a base class of cls. We return -1 if there is
  2381. an error.
  2382. */
  2383. int
  2384. _PyMethod_ShouldBind(PyObject *meth, PyObject *cls)
  2385. {
  2386. if (PyMethod_GET_SELF(meth) != NULL)
  2387. return 0; /* Already bound */
  2388. /* meth is an unbound method */
  2389. if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
  2390. /* Do subclass test. If it fails, we should not bind it. */
  2391. int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
  2392. if (ok < 0)
  2393. return -1;
  2394. if (!ok)
  2395. return 0;
  2396. }
  2397. /* If either of those checks fail, we should bind the method. */
  2398. return 1;
  2399. }
  2400. static PyObject *
  2401. instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
  2402. {
  2403. int r = _PyMethod_ShouldBind(meth, cls);
  2404. if (r < 0) {
  2405. return NULL;
  2406. } else if (r > 0) {
  2407. /* Bind it to obj */
  2408. return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
  2409. } else {
  2410. /* Return meth unchanged. */
  2411. Py_INCREF(meth);
  2412. return meth;
  2413. }
  2414. }
  2415. PyTypeObject PyMethod_Type = {
  2416. PyObject_HEAD_INIT(&PyType_Type)
  2417. 0,
  2418. "instancemethod",
  2419. sizeof(PyMethodObject),
  2420. 0,
  2421. (destructor)instancemethod_dealloc, /* tp_dealloc */
  2422. 0, /* tp_print */
  2423. 0, /* tp_getattr */
  2424. 0, /* tp_setattr */
  2425. (cmpfunc)instancemethod_compare, /* tp_compare */
  2426. (reprfunc)instancemethod_repr, /* tp_repr */
  2427. 0, /* tp_as_number */
  2428. 0, /* tp_as_sequence */
  2429. 0, /* tp_as_mapping */
  2430. (hashfunc)instancemethod_hash, /* tp_hash */
  2431. instancemethod_call, /* tp_call */
  2432. 0, /* tp_str */
  2433. instancemethod_getattro, /* tp_getattro */
  2434. PyObject_GenericSetAttr, /* tp_setattro */
  2435. 0, /* tp_as_buffer */
  2436. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
  2437. instancemethod_doc, /* tp_doc */
  2438. (traverseproc)instancemethod_traverse, /* tp_traverse */
  2439. 0, /* tp_clear */
  2440. 0, /* tp_richcompare */
  2441. offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
  2442. 0, /* tp_iter */
  2443. 0, /* tp_iternext */
  2444. 0, /* tp_methods */
  2445. instancemethod_memberlist, /* tp_members */
  2446. instancemethod_getset, /* tp_getset */
  2447. 0, /* tp_base */
  2448. 0, /* tp_dict */
  2449. instancemethod_descr_get, /* tp_descr_get */
  2450. 0, /* tp_descr_set */
  2451. 0, /* tp_dictoffset */
  2452. 0, /* tp_init */
  2453. 0, /* tp_alloc */
  2454. instancemethod_new, /* tp_new */
  2455. };
  2456. /* Clear out the free list */
  2457. int
  2458. PyMethod_ClearFreeList(void)
  2459. {
  2460. int freelist_size = numfree;
  2461. while (free_list) {
  2462. PyMethodObject *im = free_list;
  2463. free_list = (PyMethodObject *)(im->im_self);
  2464. PyObject_GC_Del(im);
  2465. numfree--;
  2466. }
  2467. assert(numfree == 0);
  2468. return freelist_size;
  2469. }
  2470. void
  2471. PyMethod_Fini(void)
  2472. {
  2473. (void)PyMethod_ClearFreeList();
  2474. }