You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

414 lines
12 KiB

  1. /* Generator object implementation */
  2. #include "Python.h"
  3. #include "frameobject.h"
  4. #include "genobject.h"
  5. #include "ceval.h"
  6. #include "structmember.h"
  7. #include "opcode.h"
  8. static int
  9. gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
  10. {
  11. Py_VISIT((PyObject *)gen->gi_frame);
  12. Py_VISIT(gen->gi_code);
  13. return 0;
  14. }
  15. static void
  16. gen_dealloc(PyGenObject *gen)
  17. {
  18. PyObject *self = (PyObject *) gen;
  19. _PyObject_GC_UNTRACK(gen);
  20. if (gen->gi_weakreflist != NULL)
  21. PyObject_ClearWeakRefs(self);
  22. _PyObject_GC_TRACK(self);
  23. if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) {
  24. /* Generator is paused, so we need to close */
  25. Py_TYPE(gen)->tp_del(self);
  26. if (self->ob_refcnt > 0)
  27. return; /* resurrected. :( */
  28. }
  29. _PyObject_GC_UNTRACK(self);
  30. Py_CLEAR(gen->gi_frame);
  31. Py_CLEAR(gen->gi_code);
  32. PyObject_GC_Del(gen);
  33. }
  34. static PyObject *
  35. gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
  36. {
  37. PyThreadState *tstate = PyThreadState_GET();
  38. PyFrameObject *f = gen->gi_frame;
  39. PyObject *result;
  40. if (gen->gi_running) {
  41. PyErr_SetString(PyExc_ValueError,
  42. "generator already executing");
  43. return NULL;
  44. }
  45. if (f==NULL || f->f_stacktop == NULL) {
  46. /* Only set exception if called from send() */
  47. if (arg && !exc)
  48. PyErr_SetNone(PyExc_StopIteration);
  49. return NULL;
  50. }
  51. if (f->f_lasti == -1) {
  52. if (arg && arg != Py_None) {
  53. PyErr_SetString(PyExc_TypeError,
  54. "can't send non-None value to a "
  55. "just-started generator");
  56. return NULL;
  57. }
  58. } else {
  59. /* Push arg onto the frame's value stack */
  60. result = arg ? arg : Py_None;
  61. Py_INCREF(result);
  62. *(f->f_stacktop++) = result;
  63. }
  64. /* Generators always return to their most recent caller, not
  65. * necessarily their creator. */
  66. Py_XINCREF(tstate->frame);
  67. assert(f->f_back == NULL);
  68. f->f_back = tstate->frame;
  69. gen->gi_running = 1;
  70. result = PyEval_EvalFrameEx(f, exc);
  71. gen->gi_running = 0;
  72. /* Don't keep the reference to f_back any longer than necessary. It
  73. * may keep a chain of frames alive or it could create a reference
  74. * cycle. */
  75. assert(f->f_back == tstate->frame);
  76. Py_CLEAR(f->f_back);
  77. /* If the generator just returned (as opposed to yielding), signal
  78. * that the generator is exhausted. */
  79. if (result == Py_None && f->f_stacktop == NULL) {
  80. Py_DECREF(result);
  81. result = NULL;
  82. /* Set exception if not called by gen_iternext() */
  83. if (arg)
  84. PyErr_SetNone(PyExc_StopIteration);
  85. }
  86. if (!result || f->f_stacktop == NULL) {
  87. /* generator can't be rerun, so release the frame */
  88. Py_DECREF(f);
  89. gen->gi_frame = NULL;
  90. }
  91. return result;
  92. }
  93. PyDoc_STRVAR(send_doc,
  94. "send(arg) -> send 'arg' into generator,\n\
  95. return next yielded value or raise StopIteration.");
  96. static PyObject *
  97. gen_send(PyGenObject *gen, PyObject *arg)
  98. {
  99. return gen_send_ex(gen, arg, 0);
  100. }
  101. PyDoc_STRVAR(close_doc,
  102. "close(arg) -> raise GeneratorExit inside generator.");
  103. static PyObject *
  104. gen_close(PyGenObject *gen, PyObject *args)
  105. {
  106. PyObject *retval;
  107. PyErr_SetNone(PyExc_GeneratorExit);
  108. retval = gen_send_ex(gen, Py_None, 1);
  109. if (retval) {
  110. Py_DECREF(retval);
  111. PyErr_SetString(PyExc_RuntimeError,
  112. "generator ignored GeneratorExit");
  113. return NULL;
  114. }
  115. if (PyErr_ExceptionMatches(PyExc_StopIteration)
  116. || PyErr_ExceptionMatches(PyExc_GeneratorExit))
  117. {
  118. PyErr_Clear(); /* ignore these errors */
  119. Py_INCREF(Py_None);
  120. return Py_None;
  121. }
  122. return NULL;
  123. }
  124. static void
  125. gen_del(PyObject *self)
  126. {
  127. PyObject *res;
  128. PyObject *error_type, *error_value, *error_traceback;
  129. PyGenObject *gen = (PyGenObject *)self;
  130. if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
  131. /* Generator isn't paused, so no need to close */
  132. return;
  133. /* Temporarily resurrect the object. */
  134. assert(self->ob_refcnt == 0);
  135. self->ob_refcnt = 1;
  136. /* Save the current exception, if any. */
  137. PyErr_Fetch(&error_type, &error_value, &error_traceback);
  138. res = gen_close(gen, NULL);
  139. if (res == NULL)
  140. PyErr_WriteUnraisable(self);
  141. else
  142. Py_DECREF(res);
  143. /* Restore the saved exception. */
  144. PyErr_Restore(error_type, error_value, error_traceback);
  145. /* Undo the temporary resurrection; can't use DECREF here, it would
  146. * cause a recursive call.
  147. */
  148. assert(self->ob_refcnt > 0);
  149. if (--self->ob_refcnt == 0)
  150. return; /* this is the normal path out */
  151. /* close() resurrected it! Make it look like the original Py_DECREF
  152. * never happened.
  153. */
  154. {
  155. Py_ssize_t refcnt = self->ob_refcnt;
  156. _Py_NewReference(self);
  157. self->ob_refcnt = refcnt;
  158. }
  159. assert(PyType_IS_GC(self->ob_type) &&
  160. _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
  161. /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
  162. * we need to undo that. */
  163. _Py_DEC_REFTOTAL;
  164. /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
  165. * chain, so no more to do there.
  166. * If COUNT_ALLOCS, the original decref bumped tp_frees, and
  167. * _Py_NewReference bumped tp_allocs: both of those need to be
  168. * undone.
  169. */
  170. #ifdef COUNT_ALLOCS
  171. --self->ob_type->tp_frees;
  172. --self->ob_type->tp_allocs;
  173. #endif
  174. }
  175. PyDoc_STRVAR(throw_doc,
  176. "throw(typ[,val[,tb]]) -> raise exception in generator,\n\
  177. return next yielded value or raise StopIteration.");
  178. static PyObject *
  179. gen_throw(PyGenObject *gen, PyObject *args)
  180. {
  181. PyObject *typ;
  182. PyObject *tb = NULL;
  183. PyObject *val = NULL;
  184. if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
  185. return NULL;
  186. /* First, check the traceback argument, replacing None with
  187. NULL. */
  188. if (tb == Py_None)
  189. tb = NULL;
  190. else if (tb != NULL && !PyTraceBack_Check(tb)) {
  191. PyErr_SetString(PyExc_TypeError,
  192. "throw() third argument must be a traceback object");
  193. return NULL;
  194. }
  195. Py_INCREF(typ);
  196. Py_XINCREF(val);
  197. Py_XINCREF(tb);
  198. if (PyExceptionClass_Check(typ)) {
  199. PyErr_NormalizeException(&typ, &val, &tb);
  200. }
  201. else if (PyExceptionInstance_Check(typ)) {
  202. /* Raising an instance. The value should be a dummy. */
  203. if (val && val != Py_None) {
  204. PyErr_SetString(PyExc_TypeError,
  205. "instance exception may not have a separate value");
  206. goto failed_throw;
  207. }
  208. else {
  209. /* Normalize to raise <class>, <instance> */
  210. Py_XDECREF(val);
  211. val = typ;
  212. typ = PyExceptionInstance_Class(typ);
  213. Py_INCREF(typ);
  214. }
  215. }
  216. else {
  217. /* Not something you can raise. throw() fails. */
  218. PyErr_Format(PyExc_TypeError,
  219. "exceptions must be classes, or instances, not %s",
  220. typ->ob_type->tp_name);
  221. goto failed_throw;
  222. }
  223. PyErr_Restore(typ, val, tb);
  224. return gen_send_ex(gen, Py_None, 1);
  225. failed_throw:
  226. /* Didn't use our arguments, so restore their original refcounts */
  227. Py_DECREF(typ);
  228. Py_XDECREF(val);
  229. Py_XDECREF(tb);
  230. return NULL;
  231. }
  232. static PyObject *
  233. gen_iternext(PyGenObject *gen)
  234. {
  235. return gen_send_ex(gen, NULL, 0);
  236. }
  237. static PyObject *
  238. gen_repr(PyGenObject *gen)
  239. {
  240. char *code_name;
  241. code_name = PyString_AsString(((PyCodeObject *)gen->gi_code)->co_name);
  242. if (code_name == NULL)
  243. return NULL;
  244. return PyString_FromFormat("<generator object %.200s at %p>",
  245. code_name, gen);
  246. }
  247. static PyObject *
  248. gen_get_name(PyGenObject *gen)
  249. {
  250. PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name;
  251. Py_INCREF(name);
  252. return name;
  253. }
  254. PyDoc_STRVAR(gen__name__doc__,
  255. "Return the name of the generator's associated code object.");
  256. static PyGetSetDef gen_getsetlist[] = {
  257. {"__name__", (getter)gen_get_name, NULL, gen__name__doc__},
  258. {NULL}
  259. };
  260. static PyMemberDef gen_memberlist[] = {
  261. {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), RO},
  262. {"gi_running", T_INT, offsetof(PyGenObject, gi_running), RO},
  263. {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), RO},
  264. {NULL} /* Sentinel */
  265. };
  266. static PyMethodDef gen_methods[] = {
  267. {"send",(PyCFunction)gen_send, METH_O, send_doc},
  268. {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
  269. {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
  270. {NULL, NULL} /* Sentinel */
  271. };
  272. PyTypeObject PyGen_Type = {
  273. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  274. "generator", /* tp_name */
  275. sizeof(PyGenObject), /* tp_basicsize */
  276. 0, /* tp_itemsize */
  277. /* methods */
  278. (destructor)gen_dealloc, /* tp_dealloc */
  279. 0, /* tp_print */
  280. 0, /* tp_getattr */
  281. 0, /* tp_setattr */
  282. 0, /* tp_compare */
  283. (reprfunc)gen_repr, /* tp_repr */
  284. 0, /* tp_as_number */
  285. 0, /* tp_as_sequence */
  286. 0, /* tp_as_mapping */
  287. 0, /* tp_hash */
  288. 0, /* tp_call */
  289. 0, /* tp_str */
  290. PyObject_GenericGetAttr, /* tp_getattro */
  291. 0, /* tp_setattro */
  292. 0, /* tp_as_buffer */
  293. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  294. 0, /* tp_doc */
  295. (traverseproc)gen_traverse, /* tp_traverse */
  296. 0, /* tp_clear */
  297. 0, /* tp_richcompare */
  298. offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
  299. PyObject_SelfIter, /* tp_iter */
  300. (iternextfunc)gen_iternext, /* tp_iternext */
  301. gen_methods, /* tp_methods */
  302. gen_memberlist, /* tp_members */
  303. gen_getsetlist, /* tp_getset */
  304. 0, /* tp_base */
  305. 0, /* tp_dict */
  306. 0, /* tp_descr_get */
  307. 0, /* tp_descr_set */
  308. 0, /* tp_dictoffset */
  309. 0, /* tp_init */
  310. 0, /* tp_alloc */
  311. 0, /* tp_new */
  312. 0, /* tp_free */
  313. 0, /* tp_is_gc */
  314. 0, /* tp_bases */
  315. 0, /* tp_mro */
  316. 0, /* tp_cache */
  317. 0, /* tp_subclasses */
  318. 0, /* tp_weaklist */
  319. gen_del, /* tp_del */
  320. };
  321. PyObject *
  322. PyGen_New(PyFrameObject *f)
  323. {
  324. PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
  325. if (gen == NULL) {
  326. Py_DECREF(f);
  327. return NULL;
  328. }
  329. gen->gi_frame = f;
  330. Py_INCREF(f->f_code);
  331. gen->gi_code = (PyObject *)(f->f_code);
  332. gen->gi_running = 0;
  333. gen->gi_weakreflist = NULL;
  334. _PyObject_GC_TRACK(gen);
  335. return (PyObject *)gen;
  336. }
  337. int
  338. PyGen_NeedsFinalizing(PyGenObject *gen)
  339. {
  340. int i;
  341. PyFrameObject *f = gen->gi_frame;
  342. if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0)
  343. return 0; /* no frame or empty blockstack == no finalization */
  344. /* Any block type besides a loop requires cleanup. */
  345. i = f->f_iblock;
  346. while (--i >= 0) {
  347. if (f->f_blockstack[i].b_type != SETUP_LOOP)
  348. return 1;
  349. }
  350. /* No blocks except loops, it's safe to skip finalization. */
  351. return 0;
  352. }