genobject.c 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  1. /* Generator object implementation */
  2. #define _PY_INTERPRETER
  3. #include "Python.h"
  4. #include "pycore_call.h" // _PyObject_CallNoArgs()
  5. #include "pycore_ceval.h" // _PyEval_EvalFrame()
  6. #include "pycore_frame.h" // _PyInterpreterFrame
  7. #include "pycore_genobject.h" // struct _Py_async_gen_state
  8. #include "pycore_object.h" // _PyObject_GC_UNTRACK()
  9. #include "pycore_pyerrors.h" // _PyErr_ClearExcState()
  10. #include "pycore_pystate.h" // _PyThreadState_GET()
  11. #include "structmember.h" // PyMemberDef
  12. #include "opcode.h" // SEND
  13. #include "frameobject.h" // _PyInterpreterFrame_GetLine
  14. #include "pystats.h"
  15. static PyObject *gen_close(PyGenObject *, PyObject *);
  16. static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
  17. static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
  18. static const char *NON_INIT_CORO_MSG = "can't send non-None value to a "
  19. "just-started coroutine";
  20. static const char *ASYNC_GEN_IGNORED_EXIT_MSG =
  21. "async generator ignored GeneratorExit";
  22. /* Returns a borrowed reference */
  23. static inline PyCodeObject *
  24. _PyGen_GetCode(PyGenObject *gen) {
  25. _PyInterpreterFrame *frame = (_PyInterpreterFrame *)(gen->gi_iframe);
  26. return frame->f_code;
  27. }
  28. PyCodeObject *
  29. PyGen_GetCode(PyGenObject *gen) {
  30. assert(PyGen_Check(gen));
  31. PyCodeObject *res = _PyGen_GetCode(gen);
  32. Py_INCREF(res);
  33. return res;
  34. }
  35. static inline int
  36. exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
  37. {
  38. Py_VISIT(exc_state->exc_value);
  39. return 0;
  40. }
  41. static int
  42. gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
  43. {
  44. Py_VISIT(gen->gi_name);
  45. Py_VISIT(gen->gi_qualname);
  46. if (gen->gi_frame_state < FRAME_CLEARED) {
  47. _PyInterpreterFrame *frame = (_PyInterpreterFrame *)(gen->gi_iframe);
  48. assert(frame->frame_obj == NULL ||
  49. frame->frame_obj->f_frame->owner == FRAME_OWNED_BY_GENERATOR);
  50. int err = _PyFrame_Traverse(frame, visit, arg);
  51. if (err) {
  52. return err;
  53. }
  54. }
  55. /* No need to visit cr_origin, because it's just tuples/str/int, so can't
  56. participate in a reference cycle. */
  57. return exc_state_traverse(&gen->gi_exc_state, visit, arg);
  58. }
  59. void
  60. _PyGen_Finalize(PyObject *self)
  61. {
  62. PyGenObject *gen = (PyGenObject *)self;
  63. if (gen->gi_frame_state >= FRAME_COMPLETED) {
  64. /* Generator isn't paused, so no need to close */
  65. return;
  66. }
  67. if (PyAsyncGen_CheckExact(self)) {
  68. PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
  69. PyObject *finalizer = agen->ag_origin_or_finalizer;
  70. if (finalizer && !agen->ag_closed) {
  71. /* Save the current exception, if any. */
  72. PyObject *exc = PyErr_GetRaisedException();
  73. PyObject *res = PyObject_CallOneArg(finalizer, self);
  74. if (res == NULL) {
  75. PyErr_WriteUnraisable(self);
  76. } else {
  77. Py_DECREF(res);
  78. }
  79. /* Restore the saved exception. */
  80. PyErr_SetRaisedException(exc);
  81. return;
  82. }
  83. }
  84. /* Save the current exception, if any. */
  85. PyObject *exc = PyErr_GetRaisedException();
  86. /* If `gen` is a coroutine, and if it was never awaited on,
  87. issue a RuntimeWarning. */
  88. assert(_PyGen_GetCode(gen) != NULL);
  89. if (_PyGen_GetCode(gen)->co_flags & CO_COROUTINE &&
  90. gen->gi_frame_state == FRAME_CREATED)
  91. {
  92. _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
  93. }
  94. else {
  95. PyObject *res = gen_close(gen, NULL);
  96. if (res == NULL) {
  97. if (PyErr_Occurred()) {
  98. PyErr_WriteUnraisable(self);
  99. }
  100. }
  101. else {
  102. Py_DECREF(res);
  103. }
  104. }
  105. /* Restore the saved exception. */
  106. PyErr_SetRaisedException(exc);
  107. }
  108. static void
  109. gen_dealloc(PyGenObject *gen)
  110. {
  111. PyObject *self = (PyObject *) gen;
  112. _PyObject_GC_UNTRACK(gen);
  113. if (gen->gi_weakreflist != NULL)
  114. PyObject_ClearWeakRefs(self);
  115. _PyObject_GC_TRACK(self);
  116. if (PyObject_CallFinalizerFromDealloc(self))
  117. return; /* resurrected. :( */
  118. _PyObject_GC_UNTRACK(self);
  119. if (PyAsyncGen_CheckExact(gen)) {
  120. /* We have to handle this case for asynchronous generators
  121. right here, because this code has to be between UNTRACK
  122. and GC_Del. */
  123. Py_CLEAR(((PyAsyncGenObject*)gen)->ag_origin_or_finalizer);
  124. }
  125. if (gen->gi_frame_state < FRAME_CLEARED) {
  126. _PyInterpreterFrame *frame = (_PyInterpreterFrame *)gen->gi_iframe;
  127. gen->gi_frame_state = FRAME_CLEARED;
  128. frame->previous = NULL;
  129. _PyFrame_ClearExceptCode(frame);
  130. }
  131. if (_PyGen_GetCode(gen)->co_flags & CO_COROUTINE) {
  132. Py_CLEAR(((PyCoroObject *)gen)->cr_origin_or_finalizer);
  133. }
  134. Py_DECREF(_PyGen_GetCode(gen));
  135. Py_CLEAR(gen->gi_name);
  136. Py_CLEAR(gen->gi_qualname);
  137. _PyErr_ClearExcState(&gen->gi_exc_state);
  138. PyObject_GC_Del(gen);
  139. }
  140. static PySendResult
  141. gen_send_ex2(PyGenObject *gen, PyObject *arg, PyObject **presult,
  142. int exc, int closing)
  143. {
  144. PyThreadState *tstate = _PyThreadState_GET();
  145. _PyInterpreterFrame *frame = (_PyInterpreterFrame *)gen->gi_iframe;
  146. PyObject *result;
  147. *presult = NULL;
  148. if (gen->gi_frame_state == FRAME_CREATED && arg && arg != Py_None) {
  149. const char *msg = "can't send non-None value to a "
  150. "just-started generator";
  151. if (PyCoro_CheckExact(gen)) {
  152. msg = NON_INIT_CORO_MSG;
  153. }
  154. else if (PyAsyncGen_CheckExact(gen)) {
  155. msg = "can't send non-None value to a "
  156. "just-started async generator";
  157. }
  158. PyErr_SetString(PyExc_TypeError, msg);
  159. return PYGEN_ERROR;
  160. }
  161. if (gen->gi_frame_state == FRAME_EXECUTING) {
  162. const char *msg = "generator already executing";
  163. if (PyCoro_CheckExact(gen)) {
  164. msg = "coroutine already executing";
  165. }
  166. else if (PyAsyncGen_CheckExact(gen)) {
  167. msg = "async generator already executing";
  168. }
  169. PyErr_SetString(PyExc_ValueError, msg);
  170. return PYGEN_ERROR;
  171. }
  172. if (gen->gi_frame_state >= FRAME_COMPLETED) {
  173. if (PyCoro_CheckExact(gen) && !closing) {
  174. /* `gen` is an exhausted coroutine: raise an error,
  175. except when called from gen_close(), which should
  176. always be a silent method. */
  177. PyErr_SetString(
  178. PyExc_RuntimeError,
  179. "cannot reuse already awaited coroutine");
  180. }
  181. else if (arg && !exc) {
  182. /* `gen` is an exhausted generator:
  183. only return value if called from send(). */
  184. *presult = Py_NewRef(Py_None);
  185. return PYGEN_RETURN;
  186. }
  187. return PYGEN_ERROR;
  188. }
  189. assert(gen->gi_frame_state < FRAME_EXECUTING);
  190. /* Push arg onto the frame's value stack */
  191. result = arg ? arg : Py_None;
  192. _PyFrame_StackPush(frame, Py_NewRef(result));
  193. _PyErr_StackItem *prev_exc_info = tstate->exc_info;
  194. gen->gi_exc_state.previous_item = prev_exc_info;
  195. tstate->exc_info = &gen->gi_exc_state;
  196. if (exc) {
  197. assert(_PyErr_Occurred(tstate));
  198. _PyErr_ChainStackItem(NULL);
  199. }
  200. gen->gi_frame_state = FRAME_EXECUTING;
  201. EVAL_CALL_STAT_INC(EVAL_CALL_GENERATOR);
  202. result = _PyEval_EvalFrame(tstate, frame, exc);
  203. assert(tstate->exc_info == prev_exc_info);
  204. assert(gen->gi_exc_state.previous_item == NULL);
  205. assert(gen->gi_frame_state != FRAME_EXECUTING);
  206. assert(frame->previous == NULL);
  207. /* If the generator just returned (as opposed to yielding), signal
  208. * that the generator is exhausted. */
  209. if (result) {
  210. if (gen->gi_frame_state == FRAME_SUSPENDED) {
  211. *presult = result;
  212. return PYGEN_NEXT;
  213. }
  214. assert(result == Py_None || !PyAsyncGen_CheckExact(gen));
  215. if (result == Py_None && !PyAsyncGen_CheckExact(gen) && !arg) {
  216. /* Return NULL if called by gen_iternext() */
  217. Py_CLEAR(result);
  218. }
  219. }
  220. else {
  221. assert(!PyErr_ExceptionMatches(PyExc_StopIteration));
  222. assert(!PyAsyncGen_CheckExact(gen) ||
  223. !PyErr_ExceptionMatches(PyExc_StopAsyncIteration));
  224. }
  225. /* generator can't be rerun, so release the frame */
  226. /* first clean reference cycle through stored exception traceback */
  227. _PyErr_ClearExcState(&gen->gi_exc_state);
  228. assert(gen->gi_frame_state == FRAME_CLEARED);
  229. *presult = result;
  230. return result ? PYGEN_RETURN : PYGEN_ERROR;
  231. }
  232. static PySendResult
  233. PyGen_am_send(PyGenObject *gen, PyObject *arg, PyObject **result)
  234. {
  235. return gen_send_ex2(gen, arg, result, 0, 0);
  236. }
  237. static PyObject *
  238. gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
  239. {
  240. PyObject *result;
  241. if (gen_send_ex2(gen, arg, &result, exc, closing) == PYGEN_RETURN) {
  242. if (PyAsyncGen_CheckExact(gen)) {
  243. assert(result == Py_None);
  244. PyErr_SetNone(PyExc_StopAsyncIteration);
  245. }
  246. else if (result == Py_None) {
  247. PyErr_SetNone(PyExc_StopIteration);
  248. }
  249. else {
  250. _PyGen_SetStopIterationValue(result);
  251. }
  252. Py_CLEAR(result);
  253. }
  254. return result;
  255. }
  256. PyDoc_STRVAR(send_doc,
  257. "send(arg) -> send 'arg' into generator,\n\
  258. return next yielded value or raise StopIteration.");
  259. static PyObject *
  260. gen_send(PyGenObject *gen, PyObject *arg)
  261. {
  262. return gen_send_ex(gen, arg, 0, 0);
  263. }
  264. PyDoc_STRVAR(close_doc,
  265. "close() -> raise GeneratorExit inside generator.");
  266. /*
  267. * This helper function is used by gen_close and gen_throw to
  268. * close a subiterator being delegated to by yield-from.
  269. */
  270. static int
  271. gen_close_iter(PyObject *yf)
  272. {
  273. PyObject *retval = NULL;
  274. if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
  275. retval = gen_close((PyGenObject *)yf, NULL);
  276. if (retval == NULL)
  277. return -1;
  278. }
  279. else {
  280. PyObject *meth;
  281. if (_PyObject_LookupAttr(yf, &_Py_ID(close), &meth) < 0) {
  282. PyErr_WriteUnraisable(yf);
  283. }
  284. if (meth) {
  285. retval = _PyObject_CallNoArgs(meth);
  286. Py_DECREF(meth);
  287. if (retval == NULL)
  288. return -1;
  289. }
  290. }
  291. Py_XDECREF(retval);
  292. return 0;
  293. }
  294. static inline bool
  295. is_resume(_Py_CODEUNIT *instr)
  296. {
  297. return instr->op.code == RESUME || instr->op.code == INSTRUMENTED_RESUME;
  298. }
  299. static inline bool
  300. is_yield(_Py_CODEUNIT *instr)
  301. {
  302. return instr->op.code == YIELD_VALUE || instr->op.code == INSTRUMENTED_YIELD_VALUE;
  303. }
  304. PyObject *
  305. _PyGen_yf(PyGenObject *gen)
  306. {
  307. PyObject *yf = NULL;
  308. if (gen->gi_frame_state < FRAME_CLEARED) {
  309. _PyInterpreterFrame *frame = (_PyInterpreterFrame *)gen->gi_iframe;
  310. if (gen->gi_frame_state == FRAME_CREATED) {
  311. /* Return immediately if the frame didn't start yet. SEND
  312. always come after LOAD_CONST: a code object should not start
  313. with SEND */
  314. assert(_PyCode_CODE(_PyGen_GetCode(gen))[0].op.code != SEND);
  315. return NULL;
  316. }
  317. _Py_CODEUNIT next = frame->prev_instr[1];
  318. if (!is_resume(&next) || next.op.arg < 2)
  319. {
  320. /* Not in a yield from */
  321. return NULL;
  322. }
  323. yf = Py_NewRef(_PyFrame_StackPeek(frame));
  324. }
  325. return yf;
  326. }
  327. static PyObject *
  328. gen_close(PyGenObject *gen, PyObject *args)
  329. {
  330. PyObject *retval;
  331. int err = 0;
  332. if (gen->gi_frame_state == FRAME_CREATED) {
  333. gen->gi_frame_state = FRAME_COMPLETED;
  334. Py_RETURN_NONE;
  335. }
  336. if (gen->gi_frame_state >= FRAME_COMPLETED) {
  337. Py_RETURN_NONE;
  338. }
  339. PyObject *yf = _PyGen_yf(gen);
  340. if (yf) {
  341. PyFrameState state = gen->gi_frame_state;
  342. gen->gi_frame_state = FRAME_EXECUTING;
  343. err = gen_close_iter(yf);
  344. gen->gi_frame_state = state;
  345. Py_DECREF(yf);
  346. }
  347. _PyInterpreterFrame *frame = (_PyInterpreterFrame *)gen->gi_iframe;
  348. /* It is possible for the previous instruction to not be a
  349. * YIELD_VALUE if the debugger has changed the lineno. */
  350. if (err == 0 && is_yield(frame->prev_instr)) {
  351. assert(is_resume(frame->prev_instr + 1));
  352. int exception_handler_depth = frame->prev_instr[0].op.arg;
  353. assert(exception_handler_depth > 0);
  354. /* We can safely ignore the outermost try block
  355. * as it automatically generated to handle
  356. * StopIteration. */
  357. if (exception_handler_depth == 1) {
  358. gen->gi_frame_state = FRAME_COMPLETED;
  359. Py_RETURN_NONE;
  360. }
  361. }
  362. if (err == 0) {
  363. PyErr_SetNone(PyExc_GeneratorExit);
  364. }
  365. retval = gen_send_ex(gen, Py_None, 1, 1);
  366. if (retval) {
  367. const char *msg = "generator ignored GeneratorExit";
  368. if (PyCoro_CheckExact(gen)) {
  369. msg = "coroutine ignored GeneratorExit";
  370. } else if (PyAsyncGen_CheckExact(gen)) {
  371. msg = ASYNC_GEN_IGNORED_EXIT_MSG;
  372. }
  373. Py_DECREF(retval);
  374. PyErr_SetString(PyExc_RuntimeError, msg);
  375. return NULL;
  376. }
  377. if (PyErr_ExceptionMatches(PyExc_StopIteration)
  378. || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
  379. PyErr_Clear(); /* ignore these errors */
  380. Py_RETURN_NONE;
  381. }
  382. return NULL;
  383. }
  384. PyDoc_STRVAR(throw_doc,
  385. "throw(value)\n\
  386. throw(type[,value[,tb]])\n\
  387. \n\
  388. Raise exception in generator, return next yielded value or raise\n\
  389. StopIteration.\n\
  390. the (type, val, tb) signature is deprecated, \n\
  391. and may be removed in a future version of Python.");
  392. static PyObject *
  393. _gen_throw(PyGenObject *gen, int close_on_genexit,
  394. PyObject *typ, PyObject *val, PyObject *tb)
  395. {
  396. PyObject *yf = _PyGen_yf(gen);
  397. if (yf) {
  398. _PyInterpreterFrame *frame = (_PyInterpreterFrame *)gen->gi_iframe;
  399. PyObject *ret;
  400. int err;
  401. if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
  402. close_on_genexit
  403. ) {
  404. /* Asynchronous generators *should not* be closed right away.
  405. We have to allow some awaits to work it through, hence the
  406. `close_on_genexit` parameter here.
  407. */
  408. PyFrameState state = gen->gi_frame_state;
  409. gen->gi_frame_state = FRAME_EXECUTING;
  410. err = gen_close_iter(yf);
  411. gen->gi_frame_state = state;
  412. Py_DECREF(yf);
  413. if (err < 0)
  414. return gen_send_ex(gen, Py_None, 1, 0);
  415. goto throw_here;
  416. }
  417. if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
  418. /* `yf` is a generator or a coroutine. */
  419. PyThreadState *tstate = _PyThreadState_GET();
  420. /* Since we are fast-tracking things by skipping the eval loop,
  421. we need to update the current frame so the stack trace
  422. will be reported correctly to the user. */
  423. /* XXX We should probably be updating the current frame
  424. somewhere in ceval.c. */
  425. _PyInterpreterFrame *prev = tstate->cframe->current_frame;
  426. frame->previous = prev;
  427. tstate->cframe->current_frame = frame;
  428. /* Close the generator that we are currently iterating with
  429. 'yield from' or awaiting on with 'await'. */
  430. PyFrameState state = gen->gi_frame_state;
  431. gen->gi_frame_state = FRAME_EXECUTING;
  432. ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
  433. typ, val, tb);
  434. gen->gi_frame_state = state;
  435. tstate->cframe->current_frame = prev;
  436. frame->previous = NULL;
  437. } else {
  438. /* `yf` is an iterator or a coroutine-like object. */
  439. PyObject *meth;
  440. if (_PyObject_LookupAttr(yf, &_Py_ID(throw), &meth) < 0) {
  441. Py_DECREF(yf);
  442. return NULL;
  443. }
  444. if (meth == NULL) {
  445. Py_DECREF(yf);
  446. goto throw_here;
  447. }
  448. PyFrameState state = gen->gi_frame_state;
  449. gen->gi_frame_state = FRAME_EXECUTING;
  450. ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
  451. gen->gi_frame_state = state;
  452. Py_DECREF(meth);
  453. }
  454. Py_DECREF(yf);
  455. if (!ret) {
  456. ret = gen_send_ex(gen, Py_None, 1, 0);
  457. }
  458. return ret;
  459. }
  460. throw_here:
  461. /* First, check the traceback argument, replacing None with
  462. NULL. */
  463. if (tb == Py_None) {
  464. tb = NULL;
  465. }
  466. else if (tb != NULL && !PyTraceBack_Check(tb)) {
  467. PyErr_SetString(PyExc_TypeError,
  468. "throw() third argument must be a traceback object");
  469. return NULL;
  470. }
  471. Py_INCREF(typ);
  472. Py_XINCREF(val);
  473. Py_XINCREF(tb);
  474. if (PyExceptionClass_Check(typ))
  475. PyErr_NormalizeException(&typ, &val, &tb);
  476. else if (PyExceptionInstance_Check(typ)) {
  477. /* Raising an instance. The value should be a dummy. */
  478. if (val && val != Py_None) {
  479. PyErr_SetString(PyExc_TypeError,
  480. "instance exception may not have a separate value");
  481. goto failed_throw;
  482. }
  483. else {
  484. /* Normalize to raise <class>, <instance> */
  485. Py_XSETREF(val, typ);
  486. typ = Py_NewRef(PyExceptionInstance_Class(typ));
  487. if (tb == NULL)
  488. /* Returns NULL if there's no traceback */
  489. tb = PyException_GetTraceback(val);
  490. }
  491. }
  492. else {
  493. /* Not something you can raise. throw() fails. */
  494. PyErr_Format(PyExc_TypeError,
  495. "exceptions must be classes or instances "
  496. "deriving from BaseException, not %s",
  497. Py_TYPE(typ)->tp_name);
  498. goto failed_throw;
  499. }
  500. PyErr_Restore(typ, val, tb);
  501. return gen_send_ex(gen, Py_None, 1, 0);
  502. failed_throw:
  503. /* Didn't use our arguments, so restore their original refcounts */
  504. Py_DECREF(typ);
  505. Py_XDECREF(val);
  506. Py_XDECREF(tb);
  507. return NULL;
  508. }
  509. static PyObject *
  510. gen_throw(PyGenObject *gen, PyObject *const *args, Py_ssize_t nargs)
  511. {
  512. PyObject *typ;
  513. PyObject *tb = NULL;
  514. PyObject *val = NULL;
  515. if (!_PyArg_CheckPositional("throw", nargs, 1, 3)) {
  516. return NULL;
  517. }
  518. if (nargs > 1) {
  519. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  520. "the (type, exc, tb) signature of throw() is deprecated, "
  521. "use the single-arg signature instead.",
  522. 1) < 0) {
  523. return NULL;
  524. }
  525. }
  526. typ = args[0];
  527. if (nargs == 3) {
  528. val = args[1];
  529. tb = args[2];
  530. }
  531. else if (nargs == 2) {
  532. val = args[1];
  533. }
  534. return _gen_throw(gen, 1, typ, val, tb);
  535. }
  536. static PyObject *
  537. gen_iternext(PyGenObject *gen)
  538. {
  539. PyObject *result;
  540. assert(PyGen_CheckExact(gen) || PyCoro_CheckExact(gen));
  541. if (gen_send_ex2(gen, NULL, &result, 0, 0) == PYGEN_RETURN) {
  542. if (result != Py_None) {
  543. _PyGen_SetStopIterationValue(result);
  544. }
  545. Py_CLEAR(result);
  546. }
  547. return result;
  548. }
  549. /*
  550. * Set StopIteration with specified value. Value can be arbitrary object
  551. * or NULL.
  552. *
  553. * Returns 0 if StopIteration is set and -1 if any other exception is set.
  554. */
  555. int
  556. _PyGen_SetStopIterationValue(PyObject *value)
  557. {
  558. PyObject *e;
  559. if (value == NULL ||
  560. (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
  561. {
  562. /* Delay exception instantiation if we can */
  563. PyErr_SetObject(PyExc_StopIteration, value);
  564. return 0;
  565. }
  566. /* Construct an exception instance manually with
  567. * PyObject_CallOneArg and pass it to PyErr_SetObject.
  568. *
  569. * We do this to handle a situation when "value" is a tuple, in which
  570. * case PyErr_SetObject would set the value of StopIteration to
  571. * the first element of the tuple.
  572. *
  573. * (See PyErr_SetObject/_PyErr_CreateException code for details.)
  574. */
  575. e = PyObject_CallOneArg(PyExc_StopIteration, value);
  576. if (e == NULL) {
  577. return -1;
  578. }
  579. PyErr_SetObject(PyExc_StopIteration, e);
  580. Py_DECREF(e);
  581. return 0;
  582. }
  583. /*
  584. * If StopIteration exception is set, fetches its 'value'
  585. * attribute if any, otherwise sets pvalue to None.
  586. *
  587. * Returns 0 if no exception or StopIteration is set.
  588. * If any other exception is set, returns -1 and leaves
  589. * pvalue unchanged.
  590. */
  591. int
  592. _PyGen_FetchStopIterationValue(PyObject **pvalue)
  593. {
  594. PyObject *value = NULL;
  595. if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
  596. PyObject *exc = PyErr_GetRaisedException();
  597. value = Py_NewRef(((PyStopIterationObject *)exc)->value);
  598. Py_DECREF(exc);
  599. } else if (PyErr_Occurred()) {
  600. return -1;
  601. }
  602. if (value == NULL) {
  603. value = Py_NewRef(Py_None);
  604. }
  605. *pvalue = value;
  606. return 0;
  607. }
  608. static PyObject *
  609. gen_repr(PyGenObject *gen)
  610. {
  611. return PyUnicode_FromFormat("<generator object %S at %p>",
  612. gen->gi_qualname, gen);
  613. }
  614. static PyObject *
  615. gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
  616. {
  617. return Py_NewRef(op->gi_name);
  618. }
  619. static int
  620. gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
  621. {
  622. /* Not legal to del gen.gi_name or to set it to anything
  623. * other than a string object. */
  624. if (value == NULL || !PyUnicode_Check(value)) {
  625. PyErr_SetString(PyExc_TypeError,
  626. "__name__ must be set to a string object");
  627. return -1;
  628. }
  629. Py_XSETREF(op->gi_name, Py_NewRef(value));
  630. return 0;
  631. }
  632. static PyObject *
  633. gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
  634. {
  635. return Py_NewRef(op->gi_qualname);
  636. }
  637. static int
  638. gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
  639. {
  640. /* Not legal to del gen.__qualname__ or to set it to anything
  641. * other than a string object. */
  642. if (value == NULL || !PyUnicode_Check(value)) {
  643. PyErr_SetString(PyExc_TypeError,
  644. "__qualname__ must be set to a string object");
  645. return -1;
  646. }
  647. Py_XSETREF(op->gi_qualname, Py_NewRef(value));
  648. return 0;
  649. }
  650. static PyObject *
  651. gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
  652. {
  653. PyObject *yf = _PyGen_yf(gen);
  654. if (yf == NULL)
  655. Py_RETURN_NONE;
  656. return yf;
  657. }
  658. static PyObject *
  659. gen_getrunning(PyGenObject *gen, void *Py_UNUSED(ignored))
  660. {
  661. if (gen->gi_frame_state == FRAME_EXECUTING) {
  662. Py_RETURN_TRUE;
  663. }
  664. Py_RETURN_FALSE;
  665. }
  666. static PyObject *
  667. gen_getsuspended(PyGenObject *gen, void *Py_UNUSED(ignored))
  668. {
  669. return PyBool_FromLong(gen->gi_frame_state == FRAME_SUSPENDED);
  670. }
  671. static PyObject *
  672. _gen_getframe(PyGenObject *gen, const char *const name)
  673. {
  674. if (PySys_Audit("object.__getattr__", "Os", gen, name) < 0) {
  675. return NULL;
  676. }
  677. if (FRAME_STATE_FINISHED(gen->gi_frame_state)) {
  678. Py_RETURN_NONE;
  679. }
  680. return _Py_XNewRef((PyObject *)_PyFrame_GetFrameObject((_PyInterpreterFrame *)gen->gi_iframe));
  681. }
  682. static PyObject *
  683. gen_getframe(PyGenObject *gen, void *Py_UNUSED(ignored))
  684. {
  685. return _gen_getframe(gen, "gi_frame");
  686. }
  687. static PyObject *
  688. _gen_getcode(PyGenObject *gen, const char *const name)
  689. {
  690. if (PySys_Audit("object.__getattr__", "Os", gen, name) < 0) {
  691. return NULL;
  692. }
  693. return Py_NewRef(_PyGen_GetCode(gen));
  694. }
  695. static PyObject *
  696. gen_getcode(PyGenObject *gen, void *Py_UNUSED(ignored))
  697. {
  698. return _gen_getcode(gen, "gi_code");
  699. }
  700. static PyGetSetDef gen_getsetlist[] = {
  701. {"__name__", (getter)gen_get_name, (setter)gen_set_name,
  702. PyDoc_STR("name of the generator")},
  703. {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
  704. PyDoc_STR("qualified name of the generator")},
  705. {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
  706. PyDoc_STR("object being iterated by yield from, or None")},
  707. {"gi_running", (getter)gen_getrunning, NULL, NULL},
  708. {"gi_frame", (getter)gen_getframe, NULL, NULL},
  709. {"gi_suspended", (getter)gen_getsuspended, NULL, NULL},
  710. {"gi_code", (getter)gen_getcode, NULL, NULL},
  711. {NULL} /* Sentinel */
  712. };
  713. static PyMemberDef gen_memberlist[] = {
  714. {NULL} /* Sentinel */
  715. };
  716. static PyObject *
  717. gen_sizeof(PyGenObject *gen, PyObject *Py_UNUSED(ignored))
  718. {
  719. Py_ssize_t res;
  720. res = offsetof(PyGenObject, gi_iframe) + offsetof(_PyInterpreterFrame, localsplus);
  721. PyCodeObject *code = _PyGen_GetCode(gen);
  722. res += _PyFrame_NumSlotsForCodeObject(code) * sizeof(PyObject *);
  723. return PyLong_FromSsize_t(res);
  724. }
  725. PyDoc_STRVAR(sizeof__doc__,
  726. "gen.__sizeof__() -> size of gen in memory, in bytes");
  727. static PyMethodDef gen_methods[] = {
  728. {"send",(PyCFunction)gen_send, METH_O, send_doc},
  729. {"throw",_PyCFunction_CAST(gen_throw), METH_FASTCALL, throw_doc},
  730. {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
  731. {"__sizeof__", (PyCFunction)gen_sizeof, METH_NOARGS, sizeof__doc__},
  732. {NULL, NULL} /* Sentinel */
  733. };
  734. static PyAsyncMethods gen_as_async = {
  735. 0, /* am_await */
  736. 0, /* am_aiter */
  737. 0, /* am_anext */
  738. (sendfunc)PyGen_am_send, /* am_send */
  739. };
  740. PyTypeObject PyGen_Type = {
  741. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  742. "generator", /* tp_name */
  743. offsetof(PyGenObject, gi_iframe) +
  744. offsetof(_PyInterpreterFrame, localsplus), /* tp_basicsize */
  745. sizeof(PyObject *), /* tp_itemsize */
  746. /* methods */
  747. (destructor)gen_dealloc, /* tp_dealloc */
  748. 0, /* tp_vectorcall_offset */
  749. 0, /* tp_getattr */
  750. 0, /* tp_setattr */
  751. &gen_as_async, /* tp_as_async */
  752. (reprfunc)gen_repr, /* tp_repr */
  753. 0, /* tp_as_number */
  754. 0, /* tp_as_sequence */
  755. 0, /* tp_as_mapping */
  756. 0, /* tp_hash */
  757. 0, /* tp_call */
  758. 0, /* tp_str */
  759. PyObject_GenericGetAttr, /* tp_getattro */
  760. 0, /* tp_setattro */
  761. 0, /* tp_as_buffer */
  762. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  763. 0, /* tp_doc */
  764. (traverseproc)gen_traverse, /* tp_traverse */
  765. 0, /* tp_clear */
  766. 0, /* tp_richcompare */
  767. offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
  768. PyObject_SelfIter, /* tp_iter */
  769. (iternextfunc)gen_iternext, /* tp_iternext */
  770. gen_methods, /* tp_methods */
  771. gen_memberlist, /* tp_members */
  772. gen_getsetlist, /* tp_getset */
  773. 0, /* tp_base */
  774. 0, /* tp_dict */
  775. 0, /* tp_descr_get */
  776. 0, /* tp_descr_set */
  777. 0, /* tp_dictoffset */
  778. 0, /* tp_init */
  779. 0, /* tp_alloc */
  780. 0, /* tp_new */
  781. 0, /* tp_free */
  782. 0, /* tp_is_gc */
  783. 0, /* tp_bases */
  784. 0, /* tp_mro */
  785. 0, /* tp_cache */
  786. 0, /* tp_subclasses */
  787. 0, /* tp_weaklist */
  788. 0, /* tp_del */
  789. 0, /* tp_version_tag */
  790. _PyGen_Finalize, /* tp_finalize */
  791. };
  792. static PyObject *
  793. make_gen(PyTypeObject *type, PyFunctionObject *func)
  794. {
  795. PyCodeObject *code = (PyCodeObject *)func->func_code;
  796. int slots = _PyFrame_NumSlotsForCodeObject(code);
  797. PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, slots);
  798. if (gen == NULL) {
  799. return NULL;
  800. }
  801. gen->gi_frame_state = FRAME_CLEARED;
  802. gen->gi_weakreflist = NULL;
  803. gen->gi_exc_state.exc_value = NULL;
  804. gen->gi_exc_state.previous_item = NULL;
  805. assert(func->func_name != NULL);
  806. gen->gi_name = Py_NewRef(func->func_name);
  807. assert(func->func_qualname != NULL);
  808. gen->gi_qualname = Py_NewRef(func->func_qualname);
  809. _PyObject_GC_TRACK(gen);
  810. return (PyObject *)gen;
  811. }
  812. static PyObject *
  813. compute_cr_origin(int origin_depth, _PyInterpreterFrame *current_frame);
  814. PyObject *
  815. _Py_MakeCoro(PyFunctionObject *func)
  816. {
  817. int coro_flags = ((PyCodeObject *)func->func_code)->co_flags &
  818. (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR);
  819. assert(coro_flags);
  820. if (coro_flags == CO_GENERATOR) {
  821. return make_gen(&PyGen_Type, func);
  822. }
  823. if (coro_flags == CO_ASYNC_GENERATOR) {
  824. PyAsyncGenObject *o;
  825. o = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func);
  826. if (o == NULL) {
  827. return NULL;
  828. }
  829. o->ag_origin_or_finalizer = NULL;
  830. o->ag_closed = 0;
  831. o->ag_hooks_inited = 0;
  832. o->ag_running_async = 0;
  833. return (PyObject*)o;
  834. }
  835. assert (coro_flags == CO_COROUTINE);
  836. PyObject *coro = make_gen(&PyCoro_Type, func);
  837. if (!coro) {
  838. return NULL;
  839. }
  840. PyThreadState *tstate = _PyThreadState_GET();
  841. int origin_depth = tstate->coroutine_origin_tracking_depth;
  842. if (origin_depth == 0) {
  843. ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL;
  844. } else {
  845. _PyInterpreterFrame *frame = tstate->cframe->current_frame;
  846. assert(frame);
  847. assert(_PyFrame_IsIncomplete(frame));
  848. frame = _PyFrame_GetFirstComplete(frame->previous);
  849. PyObject *cr_origin = compute_cr_origin(origin_depth, frame);
  850. ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin;
  851. if (!cr_origin) {
  852. Py_DECREF(coro);
  853. return NULL;
  854. }
  855. }
  856. return coro;
  857. }
  858. static PyObject *
  859. gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
  860. PyObject *name, PyObject *qualname)
  861. {
  862. PyCodeObject *code = f->f_frame->f_code;
  863. int size = code->co_nlocalsplus + code->co_stacksize;
  864. PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, size);
  865. if (gen == NULL) {
  866. Py_DECREF(f);
  867. return NULL;
  868. }
  869. /* Copy the frame */
  870. assert(f->f_frame->frame_obj == NULL);
  871. assert(f->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT);
  872. _PyInterpreterFrame *frame = (_PyInterpreterFrame *)gen->gi_iframe;
  873. _PyFrame_Copy((_PyInterpreterFrame *)f->_f_frame_data, frame);
  874. gen->gi_frame_state = FRAME_CREATED;
  875. assert(frame->frame_obj == f);
  876. f->f_frame = frame;
  877. frame->owner = FRAME_OWNED_BY_GENERATOR;
  878. assert(PyObject_GC_IsTracked((PyObject *)f));
  879. Py_DECREF(f);
  880. gen->gi_weakreflist = NULL;
  881. gen->gi_exc_state.exc_value = NULL;
  882. gen->gi_exc_state.previous_item = NULL;
  883. if (name != NULL)
  884. gen->gi_name = Py_NewRef(name);
  885. else
  886. gen->gi_name = Py_NewRef(_PyGen_GetCode(gen)->co_name);
  887. if (qualname != NULL)
  888. gen->gi_qualname = Py_NewRef(qualname);
  889. else
  890. gen->gi_qualname = Py_NewRef(_PyGen_GetCode(gen)->co_qualname);
  891. _PyObject_GC_TRACK(gen);
  892. return (PyObject *)gen;
  893. }
  894. PyObject *
  895. PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
  896. {
  897. return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
  898. }
  899. PyObject *
  900. PyGen_New(PyFrameObject *f)
  901. {
  902. return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
  903. }
  904. /* Coroutine Object */
  905. typedef struct {
  906. PyObject_HEAD
  907. PyCoroObject *cw_coroutine;
  908. } PyCoroWrapper;
  909. static int
  910. gen_is_coroutine(PyObject *o)
  911. {
  912. if (PyGen_CheckExact(o)) {
  913. PyCodeObject *code = _PyGen_GetCode((PyGenObject*)o);
  914. if (code->co_flags & CO_ITERABLE_COROUTINE) {
  915. return 1;
  916. }
  917. }
  918. return 0;
  919. }
  920. /*
  921. * This helper function returns an awaitable for `o`:
  922. * - `o` if `o` is a coroutine-object;
  923. * - `type(o)->tp_as_async->am_await(o)`
  924. *
  925. * Raises a TypeError if it's not possible to return
  926. * an awaitable and returns NULL.
  927. */
  928. PyObject *
  929. _PyCoro_GetAwaitableIter(PyObject *o)
  930. {
  931. unaryfunc getter = NULL;
  932. PyTypeObject *ot;
  933. if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
  934. /* 'o' is a coroutine. */
  935. return Py_NewRef(o);
  936. }
  937. ot = Py_TYPE(o);
  938. if (ot->tp_as_async != NULL) {
  939. getter = ot->tp_as_async->am_await;
  940. }
  941. if (getter != NULL) {
  942. PyObject *res = (*getter)(o);
  943. if (res != NULL) {
  944. if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
  945. /* __await__ must return an *iterator*, not
  946. a coroutine or another awaitable (see PEP 492) */
  947. PyErr_SetString(PyExc_TypeError,
  948. "__await__() returned a coroutine");
  949. Py_CLEAR(res);
  950. } else if (!PyIter_Check(res)) {
  951. PyErr_Format(PyExc_TypeError,
  952. "__await__() returned non-iterator "
  953. "of type '%.100s'",
  954. Py_TYPE(res)->tp_name);
  955. Py_CLEAR(res);
  956. }
  957. }
  958. return res;
  959. }
  960. PyErr_Format(PyExc_TypeError,
  961. "object %.100s can't be used in 'await' expression",
  962. ot->tp_name);
  963. return NULL;
  964. }
  965. static PyObject *
  966. coro_repr(PyCoroObject *coro)
  967. {
  968. return PyUnicode_FromFormat("<coroutine object %S at %p>",
  969. coro->cr_qualname, coro);
  970. }
  971. static PyObject *
  972. coro_await(PyCoroObject *coro)
  973. {
  974. PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
  975. if (cw == NULL) {
  976. return NULL;
  977. }
  978. cw->cw_coroutine = (PyCoroObject*)Py_NewRef(coro);
  979. _PyObject_GC_TRACK(cw);
  980. return (PyObject *)cw;
  981. }
  982. static PyObject *
  983. coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
  984. {
  985. PyObject *yf = _PyGen_yf((PyGenObject *) coro);
  986. if (yf == NULL)
  987. Py_RETURN_NONE;
  988. return yf;
  989. }
  990. static PyObject *
  991. cr_getsuspended(PyCoroObject *coro, void *Py_UNUSED(ignored))
  992. {
  993. if (coro->cr_frame_state == FRAME_SUSPENDED) {
  994. Py_RETURN_TRUE;
  995. }
  996. Py_RETURN_FALSE;
  997. }
  998. static PyObject *
  999. cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
  1000. {
  1001. if (coro->cr_frame_state == FRAME_EXECUTING) {
  1002. Py_RETURN_TRUE;
  1003. }
  1004. Py_RETURN_FALSE;
  1005. }
  1006. static PyObject *
  1007. cr_getframe(PyCoroObject *coro, void *Py_UNUSED(ignored))
  1008. {
  1009. return _gen_getframe((PyGenObject *)coro, "cr_frame");
  1010. }
  1011. static PyObject *
  1012. cr_getcode(PyCoroObject *coro, void *Py_UNUSED(ignored))
  1013. {
  1014. return _gen_getcode((PyGenObject *)coro, "cr_code");
  1015. }
  1016. static PyGetSetDef coro_getsetlist[] = {
  1017. {"__name__", (getter)gen_get_name, (setter)gen_set_name,
  1018. PyDoc_STR("name of the coroutine")},
  1019. {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
  1020. PyDoc_STR("qualified name of the coroutine")},
  1021. {"cr_await", (getter)coro_get_cr_await, NULL,
  1022. PyDoc_STR("object being awaited on, or None")},
  1023. {"cr_running", (getter)cr_getrunning, NULL, NULL},
  1024. {"cr_frame", (getter)cr_getframe, NULL, NULL},
  1025. {"cr_code", (getter)cr_getcode, NULL, NULL},
  1026. {"cr_suspended", (getter)cr_getsuspended, NULL, NULL},
  1027. {NULL} /* Sentinel */
  1028. };
  1029. static PyMemberDef coro_memberlist[] = {
  1030. {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin_or_finalizer), READONLY},
  1031. {NULL} /* Sentinel */
  1032. };
  1033. PyDoc_STRVAR(coro_send_doc,
  1034. "send(arg) -> send 'arg' into coroutine,\n\
  1035. return next iterated value or raise StopIteration.");
  1036. PyDoc_STRVAR(coro_throw_doc,
  1037. "throw(value)\n\
  1038. throw(type[,value[,traceback]])\n\
  1039. \n\
  1040. Raise exception in coroutine, return next iterated value or raise\n\
  1041. StopIteration.\n\
  1042. the (type, val, tb) signature is deprecated, \n\
  1043. and may be removed in a future version of Python.");
  1044. PyDoc_STRVAR(coro_close_doc,
  1045. "close() -> raise GeneratorExit inside coroutine.");
  1046. static PyMethodDef coro_methods[] = {
  1047. {"send",(PyCFunction)gen_send, METH_O, coro_send_doc},
  1048. {"throw",_PyCFunction_CAST(gen_throw), METH_FASTCALL, coro_throw_doc},
  1049. {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
  1050. {"__sizeof__", (PyCFunction)gen_sizeof, METH_NOARGS, sizeof__doc__},
  1051. {NULL, NULL} /* Sentinel */
  1052. };
  1053. static PyAsyncMethods coro_as_async = {
  1054. (unaryfunc)coro_await, /* am_await */
  1055. 0, /* am_aiter */
  1056. 0, /* am_anext */
  1057. (sendfunc)PyGen_am_send, /* am_send */
  1058. };
  1059. PyTypeObject PyCoro_Type = {
  1060. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1061. "coroutine", /* tp_name */
  1062. offsetof(PyCoroObject, cr_iframe) +
  1063. offsetof(_PyInterpreterFrame, localsplus), /* tp_basicsize */
  1064. sizeof(PyObject *), /* tp_itemsize */
  1065. /* methods */
  1066. (destructor)gen_dealloc, /* tp_dealloc */
  1067. 0, /* tp_vectorcall_offset */
  1068. 0, /* tp_getattr */
  1069. 0, /* tp_setattr */
  1070. &coro_as_async, /* tp_as_async */
  1071. (reprfunc)coro_repr, /* tp_repr */
  1072. 0, /* tp_as_number */
  1073. 0, /* tp_as_sequence */
  1074. 0, /* tp_as_mapping */
  1075. 0, /* tp_hash */
  1076. 0, /* tp_call */
  1077. 0, /* tp_str */
  1078. PyObject_GenericGetAttr, /* tp_getattro */
  1079. 0, /* tp_setattro */
  1080. 0, /* tp_as_buffer */
  1081. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1082. 0, /* tp_doc */
  1083. (traverseproc)gen_traverse, /* tp_traverse */
  1084. 0, /* tp_clear */
  1085. 0, /* tp_richcompare */
  1086. offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
  1087. 0, /* tp_iter */
  1088. 0, /* tp_iternext */
  1089. coro_methods, /* tp_methods */
  1090. coro_memberlist, /* tp_members */
  1091. coro_getsetlist, /* tp_getset */
  1092. 0, /* tp_base */
  1093. 0, /* tp_dict */
  1094. 0, /* tp_descr_get */
  1095. 0, /* tp_descr_set */
  1096. 0, /* tp_dictoffset */
  1097. 0, /* tp_init */
  1098. 0, /* tp_alloc */
  1099. 0, /* tp_new */
  1100. 0, /* tp_free */
  1101. 0, /* tp_is_gc */
  1102. 0, /* tp_bases */
  1103. 0, /* tp_mro */
  1104. 0, /* tp_cache */
  1105. 0, /* tp_subclasses */
  1106. 0, /* tp_weaklist */
  1107. 0, /* tp_del */
  1108. 0, /* tp_version_tag */
  1109. _PyGen_Finalize, /* tp_finalize */
  1110. };
  1111. static void
  1112. coro_wrapper_dealloc(PyCoroWrapper *cw)
  1113. {
  1114. _PyObject_GC_UNTRACK((PyObject *)cw);
  1115. Py_CLEAR(cw->cw_coroutine);
  1116. PyObject_GC_Del(cw);
  1117. }
  1118. static PyObject *
  1119. coro_wrapper_iternext(PyCoroWrapper *cw)
  1120. {
  1121. return gen_iternext((PyGenObject *)cw->cw_coroutine);
  1122. }
  1123. static PyObject *
  1124. coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
  1125. {
  1126. return gen_send((PyGenObject *)cw->cw_coroutine, arg);
  1127. }
  1128. static PyObject *
  1129. coro_wrapper_throw(PyCoroWrapper *cw, PyObject *const *args, Py_ssize_t nargs)
  1130. {
  1131. return gen_throw((PyGenObject *)cw->cw_coroutine, args, nargs);
  1132. }
  1133. static PyObject *
  1134. coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
  1135. {
  1136. return gen_close((PyGenObject *)cw->cw_coroutine, args);
  1137. }
  1138. static int
  1139. coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
  1140. {
  1141. Py_VISIT((PyObject *)cw->cw_coroutine);
  1142. return 0;
  1143. }
  1144. static PyMethodDef coro_wrapper_methods[] = {
  1145. {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
  1146. {"throw",_PyCFunction_CAST(coro_wrapper_throw),
  1147. METH_FASTCALL, coro_throw_doc},
  1148. {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
  1149. {NULL, NULL} /* Sentinel */
  1150. };
  1151. PyTypeObject _PyCoroWrapper_Type = {
  1152. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1153. "coroutine_wrapper",
  1154. sizeof(PyCoroWrapper), /* tp_basicsize */
  1155. 0, /* tp_itemsize */
  1156. (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
  1157. 0, /* tp_vectorcall_offset */
  1158. 0, /* tp_getattr */
  1159. 0, /* tp_setattr */
  1160. 0, /* tp_as_async */
  1161. 0, /* tp_repr */
  1162. 0, /* tp_as_number */
  1163. 0, /* tp_as_sequence */
  1164. 0, /* tp_as_mapping */
  1165. 0, /* tp_hash */
  1166. 0, /* tp_call */
  1167. 0, /* tp_str */
  1168. PyObject_GenericGetAttr, /* tp_getattro */
  1169. 0, /* tp_setattro */
  1170. 0, /* tp_as_buffer */
  1171. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1172. "A wrapper object implementing __await__ for coroutines.",
  1173. (traverseproc)coro_wrapper_traverse, /* tp_traverse */
  1174. 0, /* tp_clear */
  1175. 0, /* tp_richcompare */
  1176. 0, /* tp_weaklistoffset */
  1177. PyObject_SelfIter, /* tp_iter */
  1178. (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
  1179. coro_wrapper_methods, /* tp_methods */
  1180. 0, /* tp_members */
  1181. 0, /* tp_getset */
  1182. 0, /* tp_base */
  1183. 0, /* tp_dict */
  1184. 0, /* tp_descr_get */
  1185. 0, /* tp_descr_set */
  1186. 0, /* tp_dictoffset */
  1187. 0, /* tp_init */
  1188. 0, /* tp_alloc */
  1189. 0, /* tp_new */
  1190. 0, /* tp_free */
  1191. };
  1192. static PyObject *
  1193. compute_cr_origin(int origin_depth, _PyInterpreterFrame *current_frame)
  1194. {
  1195. _PyInterpreterFrame *frame = current_frame;
  1196. /* First count how many frames we have */
  1197. int frame_count = 0;
  1198. for (; frame && frame_count < origin_depth; ++frame_count) {
  1199. frame = _PyFrame_GetFirstComplete(frame->previous);
  1200. }
  1201. /* Now collect them */
  1202. PyObject *cr_origin = PyTuple_New(frame_count);
  1203. if (cr_origin == NULL) {
  1204. return NULL;
  1205. }
  1206. frame = current_frame;
  1207. for (int i = 0; i < frame_count; ++i) {
  1208. PyCodeObject *code = frame->f_code;
  1209. int line = PyUnstable_InterpreterFrame_GetLine(frame);
  1210. PyObject *frameinfo = Py_BuildValue("OiO", code->co_filename, line,
  1211. code->co_name);
  1212. if (!frameinfo) {
  1213. Py_DECREF(cr_origin);
  1214. return NULL;
  1215. }
  1216. PyTuple_SET_ITEM(cr_origin, i, frameinfo);
  1217. frame = _PyFrame_GetFirstComplete(frame->previous);
  1218. }
  1219. return cr_origin;
  1220. }
  1221. PyObject *
  1222. PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
  1223. {
  1224. PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
  1225. if (!coro) {
  1226. return NULL;
  1227. }
  1228. PyThreadState *tstate = _PyThreadState_GET();
  1229. int origin_depth = tstate->coroutine_origin_tracking_depth;
  1230. if (origin_depth == 0) {
  1231. ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL;
  1232. } else {
  1233. PyObject *cr_origin = compute_cr_origin(origin_depth, _PyEval_GetFrame());
  1234. ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin;
  1235. if (!cr_origin) {
  1236. Py_DECREF(coro);
  1237. return NULL;
  1238. }
  1239. }
  1240. return coro;
  1241. }
  1242. /* ========= Asynchronous Generators ========= */
  1243. typedef enum {
  1244. AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
  1245. AWAITABLE_STATE_ITER, /* being iterated */
  1246. AWAITABLE_STATE_CLOSED, /* closed */
  1247. } AwaitableState;
  1248. typedef struct PyAsyncGenASend {
  1249. PyObject_HEAD
  1250. PyAsyncGenObject *ags_gen;
  1251. /* Can be NULL, when in the __anext__() mode
  1252. (equivalent of "asend(None)") */
  1253. PyObject *ags_sendval;
  1254. AwaitableState ags_state;
  1255. } PyAsyncGenASend;
  1256. typedef struct PyAsyncGenAThrow {
  1257. PyObject_HEAD
  1258. PyAsyncGenObject *agt_gen;
  1259. /* Can be NULL, when in the "aclose()" mode
  1260. (equivalent of "athrow(GeneratorExit)") */
  1261. PyObject *agt_args;
  1262. AwaitableState agt_state;
  1263. } PyAsyncGenAThrow;
  1264. typedef struct _PyAsyncGenWrappedValue {
  1265. PyObject_HEAD
  1266. PyObject *agw_val;
  1267. } _PyAsyncGenWrappedValue;
  1268. #define _PyAsyncGenWrappedValue_CheckExact(o) \
  1269. Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
  1270. static int
  1271. async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
  1272. {
  1273. Py_VISIT(gen->ag_origin_or_finalizer);
  1274. return gen_traverse((PyGenObject*)gen, visit, arg);
  1275. }
  1276. static PyObject *
  1277. async_gen_repr(PyAsyncGenObject *o)
  1278. {
  1279. return PyUnicode_FromFormat("<async_generator object %S at %p>",
  1280. o->ag_qualname, o);
  1281. }
  1282. static int
  1283. async_gen_init_hooks(PyAsyncGenObject *o)
  1284. {
  1285. PyThreadState *tstate;
  1286. PyObject *finalizer;
  1287. PyObject *firstiter;
  1288. if (o->ag_hooks_inited) {
  1289. return 0;
  1290. }
  1291. o->ag_hooks_inited = 1;
  1292. tstate = _PyThreadState_GET();
  1293. finalizer = tstate->async_gen_finalizer;
  1294. if (finalizer) {
  1295. o->ag_origin_or_finalizer = Py_NewRef(finalizer);
  1296. }
  1297. firstiter = tstate->async_gen_firstiter;
  1298. if (firstiter) {
  1299. PyObject *res;
  1300. Py_INCREF(firstiter);
  1301. res = PyObject_CallOneArg(firstiter, (PyObject *)o);
  1302. Py_DECREF(firstiter);
  1303. if (res == NULL) {
  1304. return 1;
  1305. }
  1306. Py_DECREF(res);
  1307. }
  1308. return 0;
  1309. }
  1310. static PyObject *
  1311. async_gen_anext(PyAsyncGenObject *o)
  1312. {
  1313. if (async_gen_init_hooks(o)) {
  1314. return NULL;
  1315. }
  1316. return async_gen_asend_new(o, NULL);
  1317. }
  1318. static PyObject *
  1319. async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
  1320. {
  1321. if (async_gen_init_hooks(o)) {
  1322. return NULL;
  1323. }
  1324. return async_gen_asend_new(o, arg);
  1325. }
  1326. static PyObject *
  1327. async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
  1328. {
  1329. if (async_gen_init_hooks(o)) {
  1330. return NULL;
  1331. }
  1332. return async_gen_athrow_new(o, NULL);
  1333. }
  1334. static PyObject *
  1335. async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
  1336. {
  1337. if (PyTuple_GET_SIZE(args) > 1) {
  1338. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  1339. "the (type, exc, tb) signature of athrow() is deprecated, "
  1340. "use the single-arg signature instead.",
  1341. 1) < 0) {
  1342. return NULL;
  1343. }
  1344. }
  1345. if (async_gen_init_hooks(o)) {
  1346. return NULL;
  1347. }
  1348. return async_gen_athrow_new(o, args);
  1349. }
  1350. static PyObject *
  1351. ag_getframe(PyAsyncGenObject *ag, void *Py_UNUSED(ignored))
  1352. {
  1353. return _gen_getframe((PyGenObject *)ag, "ag_frame");
  1354. }
  1355. static PyObject *
  1356. ag_getcode(PyGenObject *gen, void *Py_UNUSED(ignored))
  1357. {
  1358. return _gen_getcode(gen, "ag_code");
  1359. }
  1360. static PyObject *
  1361. ag_getsuspended(PyAsyncGenObject *ag, void *Py_UNUSED(ignored))
  1362. {
  1363. if (ag->ag_frame_state == FRAME_SUSPENDED) {
  1364. Py_RETURN_TRUE;
  1365. }
  1366. Py_RETURN_FALSE;
  1367. }
  1368. static PyGetSetDef async_gen_getsetlist[] = {
  1369. {"__name__", (getter)gen_get_name, (setter)gen_set_name,
  1370. PyDoc_STR("name of the async generator")},
  1371. {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
  1372. PyDoc_STR("qualified name of the async generator")},
  1373. {"ag_await", (getter)coro_get_cr_await, NULL,
  1374. PyDoc_STR("object being awaited on, or None")},
  1375. {"ag_frame", (getter)ag_getframe, NULL, NULL},
  1376. {"ag_code", (getter)ag_getcode, NULL, NULL},
  1377. {"ag_suspended", (getter)ag_getsuspended, NULL, NULL},
  1378. {NULL} /* Sentinel */
  1379. };
  1380. static PyMemberDef async_gen_memberlist[] = {
  1381. {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
  1382. READONLY},
  1383. {NULL} /* Sentinel */
  1384. };
  1385. PyDoc_STRVAR(async_aclose_doc,
  1386. "aclose() -> raise GeneratorExit inside generator.");
  1387. PyDoc_STRVAR(async_asend_doc,
  1388. "asend(v) -> send 'v' in generator.");
  1389. PyDoc_STRVAR(async_athrow_doc,
  1390. "athrow(value)\n\
  1391. athrow(type[,value[,tb]])\n\
  1392. \n\
  1393. raise exception in generator.\n\
  1394. the (type, val, tb) signature is deprecated, \n\
  1395. and may be removed in a future version of Python.");
  1396. static PyMethodDef async_gen_methods[] = {
  1397. {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
  1398. {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
  1399. {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
  1400. {"__sizeof__", (PyCFunction)gen_sizeof, METH_NOARGS, sizeof__doc__},
  1401. {"__class_getitem__", Py_GenericAlias,
  1402. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  1403. {NULL, NULL} /* Sentinel */
  1404. };
  1405. static PyAsyncMethods async_gen_as_async = {
  1406. 0, /* am_await */
  1407. PyObject_SelfIter, /* am_aiter */
  1408. (unaryfunc)async_gen_anext, /* am_anext */
  1409. (sendfunc)PyGen_am_send, /* am_send */
  1410. };
  1411. PyTypeObject PyAsyncGen_Type = {
  1412. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1413. "async_generator", /* tp_name */
  1414. offsetof(PyAsyncGenObject, ag_iframe) +
  1415. offsetof(_PyInterpreterFrame, localsplus), /* tp_basicsize */
  1416. sizeof(PyObject *), /* tp_itemsize */
  1417. /* methods */
  1418. (destructor)gen_dealloc, /* tp_dealloc */
  1419. 0, /* tp_vectorcall_offset */
  1420. 0, /* tp_getattr */
  1421. 0, /* tp_setattr */
  1422. &async_gen_as_async, /* tp_as_async */
  1423. (reprfunc)async_gen_repr, /* tp_repr */
  1424. 0, /* tp_as_number */
  1425. 0, /* tp_as_sequence */
  1426. 0, /* tp_as_mapping */
  1427. 0, /* tp_hash */
  1428. 0, /* tp_call */
  1429. 0, /* tp_str */
  1430. PyObject_GenericGetAttr, /* tp_getattro */
  1431. 0, /* tp_setattro */
  1432. 0, /* tp_as_buffer */
  1433. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1434. 0, /* tp_doc */
  1435. (traverseproc)async_gen_traverse, /* tp_traverse */
  1436. 0, /* tp_clear */
  1437. 0, /* tp_richcompare */
  1438. offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
  1439. 0, /* tp_iter */
  1440. 0, /* tp_iternext */
  1441. async_gen_methods, /* tp_methods */
  1442. async_gen_memberlist, /* tp_members */
  1443. async_gen_getsetlist, /* tp_getset */
  1444. 0, /* tp_base */
  1445. 0, /* tp_dict */
  1446. 0, /* tp_descr_get */
  1447. 0, /* tp_descr_set */
  1448. 0, /* tp_dictoffset */
  1449. 0, /* tp_init */
  1450. 0, /* tp_alloc */
  1451. 0, /* tp_new */
  1452. 0, /* tp_free */
  1453. 0, /* tp_is_gc */
  1454. 0, /* tp_bases */
  1455. 0, /* tp_mro */
  1456. 0, /* tp_cache */
  1457. 0, /* tp_subclasses */
  1458. 0, /* tp_weaklist */
  1459. 0, /* tp_del */
  1460. 0, /* tp_version_tag */
  1461. _PyGen_Finalize, /* tp_finalize */
  1462. };
  1463. #if _PyAsyncGen_MAXFREELIST > 0
  1464. static struct _Py_async_gen_state *
  1465. get_async_gen_state(void)
  1466. {
  1467. PyInterpreterState *interp = _PyInterpreterState_GET();
  1468. return &interp->async_gen;
  1469. }
  1470. #endif
  1471. PyObject *
  1472. PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
  1473. {
  1474. PyAsyncGenObject *o;
  1475. o = (PyAsyncGenObject *)gen_new_with_qualname(
  1476. &PyAsyncGen_Type, f, name, qualname);
  1477. if (o == NULL) {
  1478. return NULL;
  1479. }
  1480. o->ag_origin_or_finalizer = NULL;
  1481. o->ag_closed = 0;
  1482. o->ag_hooks_inited = 0;
  1483. o->ag_running_async = 0;
  1484. return (PyObject*)o;
  1485. }
  1486. void
  1487. _PyAsyncGen_ClearFreeLists(PyInterpreterState *interp)
  1488. {
  1489. #if _PyAsyncGen_MAXFREELIST > 0
  1490. struct _Py_async_gen_state *state = &interp->async_gen;
  1491. while (state->value_numfree) {
  1492. _PyAsyncGenWrappedValue *o;
  1493. o = state->value_freelist[--state->value_numfree];
  1494. assert(_PyAsyncGenWrappedValue_CheckExact(o));
  1495. PyObject_GC_Del(o);
  1496. }
  1497. while (state->asend_numfree) {
  1498. PyAsyncGenASend *o;
  1499. o = state->asend_freelist[--state->asend_numfree];
  1500. assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
  1501. PyObject_GC_Del(o);
  1502. }
  1503. #endif
  1504. }
  1505. void
  1506. _PyAsyncGen_Fini(PyInterpreterState *interp)
  1507. {
  1508. _PyAsyncGen_ClearFreeLists(interp);
  1509. #if defined(Py_DEBUG) && _PyAsyncGen_MAXFREELIST > 0
  1510. struct _Py_async_gen_state *state = &interp->async_gen;
  1511. state->value_numfree = -1;
  1512. state->asend_numfree = -1;
  1513. #endif
  1514. }
  1515. static PyObject *
  1516. async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
  1517. {
  1518. if (result == NULL) {
  1519. if (!PyErr_Occurred()) {
  1520. PyErr_SetNone(PyExc_StopAsyncIteration);
  1521. }
  1522. if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
  1523. || PyErr_ExceptionMatches(PyExc_GeneratorExit)
  1524. ) {
  1525. gen->ag_closed = 1;
  1526. }
  1527. gen->ag_running_async = 0;
  1528. return NULL;
  1529. }
  1530. if (_PyAsyncGenWrappedValue_CheckExact(result)) {
  1531. /* async yield */
  1532. _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
  1533. Py_DECREF(result);
  1534. gen->ag_running_async = 0;
  1535. return NULL;
  1536. }
  1537. return result;
  1538. }
  1539. /* ---------- Async Generator ASend Awaitable ------------ */
  1540. static void
  1541. async_gen_asend_dealloc(PyAsyncGenASend *o)
  1542. {
  1543. _PyObject_GC_UNTRACK((PyObject *)o);
  1544. Py_CLEAR(o->ags_gen);
  1545. Py_CLEAR(o->ags_sendval);
  1546. #if _PyAsyncGen_MAXFREELIST > 0
  1547. struct _Py_async_gen_state *state = get_async_gen_state();
  1548. #ifdef Py_DEBUG
  1549. // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
  1550. assert(state->asend_numfree != -1);
  1551. #endif
  1552. if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
  1553. assert(PyAsyncGenASend_CheckExact(o));
  1554. state->asend_freelist[state->asend_numfree++] = o;
  1555. }
  1556. else
  1557. #endif
  1558. {
  1559. PyObject_GC_Del(o);
  1560. }
  1561. }
  1562. static int
  1563. async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
  1564. {
  1565. Py_VISIT(o->ags_gen);
  1566. Py_VISIT(o->ags_sendval);
  1567. return 0;
  1568. }
  1569. static PyObject *
  1570. async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
  1571. {
  1572. PyObject *result;
  1573. if (o->ags_state == AWAITABLE_STATE_CLOSED) {
  1574. PyErr_SetString(
  1575. PyExc_RuntimeError,
  1576. "cannot reuse already awaited __anext__()/asend()");
  1577. return NULL;
  1578. }
  1579. if (o->ags_state == AWAITABLE_STATE_INIT) {
  1580. if (o->ags_gen->ag_running_async) {
  1581. PyErr_SetString(
  1582. PyExc_RuntimeError,
  1583. "anext(): asynchronous generator is already running");
  1584. return NULL;
  1585. }
  1586. if (arg == NULL || arg == Py_None) {
  1587. arg = o->ags_sendval;
  1588. }
  1589. o->ags_state = AWAITABLE_STATE_ITER;
  1590. }
  1591. o->ags_gen->ag_running_async = 1;
  1592. result = gen_send((PyGenObject*)o->ags_gen, arg);
  1593. result = async_gen_unwrap_value(o->ags_gen, result);
  1594. if (result == NULL) {
  1595. o->ags_state = AWAITABLE_STATE_CLOSED;
  1596. }
  1597. return result;
  1598. }
  1599. static PyObject *
  1600. async_gen_asend_iternext(PyAsyncGenASend *o)
  1601. {
  1602. return async_gen_asend_send(o, NULL);
  1603. }
  1604. static PyObject *
  1605. async_gen_asend_throw(PyAsyncGenASend *o, PyObject *const *args, Py_ssize_t nargs)
  1606. {
  1607. PyObject *result;
  1608. if (o->ags_state == AWAITABLE_STATE_CLOSED) {
  1609. PyErr_SetString(
  1610. PyExc_RuntimeError,
  1611. "cannot reuse already awaited __anext__()/asend()");
  1612. return NULL;
  1613. }
  1614. result = gen_throw((PyGenObject*)o->ags_gen, args, nargs);
  1615. result = async_gen_unwrap_value(o->ags_gen, result);
  1616. if (result == NULL) {
  1617. o->ags_state = AWAITABLE_STATE_CLOSED;
  1618. }
  1619. return result;
  1620. }
  1621. static PyObject *
  1622. async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
  1623. {
  1624. o->ags_state = AWAITABLE_STATE_CLOSED;
  1625. Py_RETURN_NONE;
  1626. }
  1627. static PyMethodDef async_gen_asend_methods[] = {
  1628. {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
  1629. {"throw", _PyCFunction_CAST(async_gen_asend_throw), METH_FASTCALL, throw_doc},
  1630. {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
  1631. {NULL, NULL} /* Sentinel */
  1632. };
  1633. static PyAsyncMethods async_gen_asend_as_async = {
  1634. PyObject_SelfIter, /* am_await */
  1635. 0, /* am_aiter */
  1636. 0, /* am_anext */
  1637. 0, /* am_send */
  1638. };
  1639. PyTypeObject _PyAsyncGenASend_Type = {
  1640. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1641. "async_generator_asend", /* tp_name */
  1642. sizeof(PyAsyncGenASend), /* tp_basicsize */
  1643. 0, /* tp_itemsize */
  1644. /* methods */
  1645. (destructor)async_gen_asend_dealloc, /* tp_dealloc */
  1646. 0, /* tp_vectorcall_offset */
  1647. 0, /* tp_getattr */
  1648. 0, /* tp_setattr */
  1649. &async_gen_asend_as_async, /* tp_as_async */
  1650. 0, /* tp_repr */
  1651. 0, /* tp_as_number */
  1652. 0, /* tp_as_sequence */
  1653. 0, /* tp_as_mapping */
  1654. 0, /* tp_hash */
  1655. 0, /* tp_call */
  1656. 0, /* tp_str */
  1657. PyObject_GenericGetAttr, /* tp_getattro */
  1658. 0, /* tp_setattro */
  1659. 0, /* tp_as_buffer */
  1660. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1661. 0, /* tp_doc */
  1662. (traverseproc)async_gen_asend_traverse, /* tp_traverse */
  1663. 0, /* tp_clear */
  1664. 0, /* tp_richcompare */
  1665. 0, /* tp_weaklistoffset */
  1666. PyObject_SelfIter, /* tp_iter */
  1667. (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
  1668. async_gen_asend_methods, /* tp_methods */
  1669. 0, /* tp_members */
  1670. 0, /* tp_getset */
  1671. 0, /* tp_base */
  1672. 0, /* tp_dict */
  1673. 0, /* tp_descr_get */
  1674. 0, /* tp_descr_set */
  1675. 0, /* tp_dictoffset */
  1676. 0, /* tp_init */
  1677. 0, /* tp_alloc */
  1678. 0, /* tp_new */
  1679. };
  1680. static PyObject *
  1681. async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
  1682. {
  1683. PyAsyncGenASend *o;
  1684. #if _PyAsyncGen_MAXFREELIST > 0
  1685. struct _Py_async_gen_state *state = get_async_gen_state();
  1686. #ifdef Py_DEBUG
  1687. // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
  1688. assert(state->asend_numfree != -1);
  1689. #endif
  1690. if (state->asend_numfree) {
  1691. state->asend_numfree--;
  1692. o = state->asend_freelist[state->asend_numfree];
  1693. _Py_NewReference((PyObject *)o);
  1694. }
  1695. else
  1696. #endif
  1697. {
  1698. o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
  1699. if (o == NULL) {
  1700. return NULL;
  1701. }
  1702. }
  1703. o->ags_gen = (PyAsyncGenObject*)Py_NewRef(gen);
  1704. o->ags_sendval = Py_XNewRef(sendval);
  1705. o->ags_state = AWAITABLE_STATE_INIT;
  1706. _PyObject_GC_TRACK((PyObject*)o);
  1707. return (PyObject*)o;
  1708. }
  1709. /* ---------- Async Generator Value Wrapper ------------ */
  1710. static void
  1711. async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
  1712. {
  1713. _PyObject_GC_UNTRACK((PyObject *)o);
  1714. Py_CLEAR(o->agw_val);
  1715. #if _PyAsyncGen_MAXFREELIST > 0
  1716. struct _Py_async_gen_state *state = get_async_gen_state();
  1717. #ifdef Py_DEBUG
  1718. // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
  1719. assert(state->value_numfree != -1);
  1720. #endif
  1721. if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
  1722. assert(_PyAsyncGenWrappedValue_CheckExact(o));
  1723. state->value_freelist[state->value_numfree++] = o;
  1724. OBJECT_STAT_INC(to_freelist);
  1725. }
  1726. else
  1727. #endif
  1728. {
  1729. PyObject_GC_Del(o);
  1730. }
  1731. }
  1732. static int
  1733. async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
  1734. visitproc visit, void *arg)
  1735. {
  1736. Py_VISIT(o->agw_val);
  1737. return 0;
  1738. }
  1739. PyTypeObject _PyAsyncGenWrappedValue_Type = {
  1740. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1741. "async_generator_wrapped_value", /* tp_name */
  1742. sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
  1743. 0, /* tp_itemsize */
  1744. /* methods */
  1745. (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
  1746. 0, /* tp_vectorcall_offset */
  1747. 0, /* tp_getattr */
  1748. 0, /* tp_setattr */
  1749. 0, /* tp_as_async */
  1750. 0, /* tp_repr */
  1751. 0, /* tp_as_number */
  1752. 0, /* tp_as_sequence */
  1753. 0, /* tp_as_mapping */
  1754. 0, /* tp_hash */
  1755. 0, /* tp_call */
  1756. 0, /* tp_str */
  1757. PyObject_GenericGetAttr, /* tp_getattro */
  1758. 0, /* tp_setattro */
  1759. 0, /* tp_as_buffer */
  1760. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1761. 0, /* tp_doc */
  1762. (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
  1763. 0, /* tp_clear */
  1764. 0, /* tp_richcompare */
  1765. 0, /* tp_weaklistoffset */
  1766. 0, /* tp_iter */
  1767. 0, /* tp_iternext */
  1768. 0, /* tp_methods */
  1769. 0, /* tp_members */
  1770. 0, /* tp_getset */
  1771. 0, /* tp_base */
  1772. 0, /* tp_dict */
  1773. 0, /* tp_descr_get */
  1774. 0, /* tp_descr_set */
  1775. 0, /* tp_dictoffset */
  1776. 0, /* tp_init */
  1777. 0, /* tp_alloc */
  1778. 0, /* tp_new */
  1779. };
  1780. PyObject *
  1781. _PyAsyncGenValueWrapperNew(PyThreadState *tstate, PyObject *val)
  1782. {
  1783. _PyAsyncGenWrappedValue *o;
  1784. assert(val);
  1785. #if _PyAsyncGen_MAXFREELIST > 0
  1786. struct _Py_async_gen_state *state = &tstate->interp->async_gen;
  1787. #ifdef Py_DEBUG
  1788. // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
  1789. assert(state->value_numfree != -1);
  1790. #endif
  1791. if (state->value_numfree) {
  1792. state->value_numfree--;
  1793. o = state->value_freelist[state->value_numfree];
  1794. OBJECT_STAT_INC(from_freelist);
  1795. assert(_PyAsyncGenWrappedValue_CheckExact(o));
  1796. _Py_NewReference((PyObject*)o);
  1797. }
  1798. else
  1799. #endif
  1800. {
  1801. o = PyObject_GC_New(_PyAsyncGenWrappedValue,
  1802. &_PyAsyncGenWrappedValue_Type);
  1803. if (o == NULL) {
  1804. return NULL;
  1805. }
  1806. }
  1807. o->agw_val = Py_NewRef(val);
  1808. _PyObject_GC_TRACK((PyObject*)o);
  1809. return (PyObject*)o;
  1810. }
  1811. /* ---------- Async Generator AThrow awaitable ------------ */
  1812. static void
  1813. async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
  1814. {
  1815. _PyObject_GC_UNTRACK((PyObject *)o);
  1816. Py_CLEAR(o->agt_gen);
  1817. Py_CLEAR(o->agt_args);
  1818. PyObject_GC_Del(o);
  1819. }
  1820. static int
  1821. async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
  1822. {
  1823. Py_VISIT(o->agt_gen);
  1824. Py_VISIT(o->agt_args);
  1825. return 0;
  1826. }
  1827. static PyObject *
  1828. async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
  1829. {
  1830. PyGenObject *gen = (PyGenObject*)o->agt_gen;
  1831. PyObject *retval;
  1832. if (o->agt_state == AWAITABLE_STATE_CLOSED) {
  1833. PyErr_SetString(
  1834. PyExc_RuntimeError,
  1835. "cannot reuse already awaited aclose()/athrow()");
  1836. return NULL;
  1837. }
  1838. if (gen->gi_frame_state >= FRAME_COMPLETED) {
  1839. o->agt_state = AWAITABLE_STATE_CLOSED;
  1840. PyErr_SetNone(PyExc_StopIteration);
  1841. return NULL;
  1842. }
  1843. if (o->agt_state == AWAITABLE_STATE_INIT) {
  1844. if (o->agt_gen->ag_running_async) {
  1845. o->agt_state = AWAITABLE_STATE_CLOSED;
  1846. if (o->agt_args == NULL) {
  1847. PyErr_SetString(
  1848. PyExc_RuntimeError,
  1849. "aclose(): asynchronous generator is already running");
  1850. }
  1851. else {
  1852. PyErr_SetString(
  1853. PyExc_RuntimeError,
  1854. "athrow(): asynchronous generator is already running");
  1855. }
  1856. return NULL;
  1857. }
  1858. if (o->agt_gen->ag_closed) {
  1859. o->agt_state = AWAITABLE_STATE_CLOSED;
  1860. PyErr_SetNone(PyExc_StopAsyncIteration);
  1861. return NULL;
  1862. }
  1863. if (arg != Py_None) {
  1864. PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
  1865. return NULL;
  1866. }
  1867. o->agt_state = AWAITABLE_STATE_ITER;
  1868. o->agt_gen->ag_running_async = 1;
  1869. if (o->agt_args == NULL) {
  1870. /* aclose() mode */
  1871. o->agt_gen->ag_closed = 1;
  1872. retval = _gen_throw((PyGenObject *)gen,
  1873. 0, /* Do not close generator when
  1874. PyExc_GeneratorExit is passed */
  1875. PyExc_GeneratorExit, NULL, NULL);
  1876. if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
  1877. Py_DECREF(retval);
  1878. goto yield_close;
  1879. }
  1880. } else {
  1881. PyObject *typ;
  1882. PyObject *tb = NULL;
  1883. PyObject *val = NULL;
  1884. if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
  1885. &typ, &val, &tb)) {
  1886. return NULL;
  1887. }
  1888. retval = _gen_throw((PyGenObject *)gen,
  1889. 0, /* Do not close generator when
  1890. PyExc_GeneratorExit is passed */
  1891. typ, val, tb);
  1892. retval = async_gen_unwrap_value(o->agt_gen, retval);
  1893. }
  1894. if (retval == NULL) {
  1895. goto check_error;
  1896. }
  1897. return retval;
  1898. }
  1899. assert(o->agt_state == AWAITABLE_STATE_ITER);
  1900. retval = gen_send((PyGenObject *)gen, arg);
  1901. if (o->agt_args) {
  1902. return async_gen_unwrap_value(o->agt_gen, retval);
  1903. } else {
  1904. /* aclose() mode */
  1905. if (retval) {
  1906. if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
  1907. Py_DECREF(retval);
  1908. goto yield_close;
  1909. }
  1910. else {
  1911. return retval;
  1912. }
  1913. }
  1914. else {
  1915. goto check_error;
  1916. }
  1917. }
  1918. yield_close:
  1919. o->agt_gen->ag_running_async = 0;
  1920. o->agt_state = AWAITABLE_STATE_CLOSED;
  1921. PyErr_SetString(
  1922. PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
  1923. return NULL;
  1924. check_error:
  1925. o->agt_gen->ag_running_async = 0;
  1926. o->agt_state = AWAITABLE_STATE_CLOSED;
  1927. if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
  1928. PyErr_ExceptionMatches(PyExc_GeneratorExit))
  1929. {
  1930. if (o->agt_args == NULL) {
  1931. /* when aclose() is called we don't want to propagate
  1932. StopAsyncIteration or GeneratorExit; just raise
  1933. StopIteration, signalling that this 'aclose()' await
  1934. is done.
  1935. */
  1936. PyErr_Clear();
  1937. PyErr_SetNone(PyExc_StopIteration);
  1938. }
  1939. }
  1940. return NULL;
  1941. }
  1942. static PyObject *
  1943. async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *const *args, Py_ssize_t nargs)
  1944. {
  1945. PyObject *retval;
  1946. if (o->agt_state == AWAITABLE_STATE_CLOSED) {
  1947. PyErr_SetString(
  1948. PyExc_RuntimeError,
  1949. "cannot reuse already awaited aclose()/athrow()");
  1950. return NULL;
  1951. }
  1952. retval = gen_throw((PyGenObject*)o->agt_gen, args, nargs);
  1953. if (o->agt_args) {
  1954. return async_gen_unwrap_value(o->agt_gen, retval);
  1955. } else {
  1956. /* aclose() mode */
  1957. if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
  1958. o->agt_gen->ag_running_async = 0;
  1959. o->agt_state = AWAITABLE_STATE_CLOSED;
  1960. Py_DECREF(retval);
  1961. PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
  1962. return NULL;
  1963. }
  1964. if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
  1965. PyErr_ExceptionMatches(PyExc_GeneratorExit))
  1966. {
  1967. /* when aclose() is called we don't want to propagate
  1968. StopAsyncIteration or GeneratorExit; just raise
  1969. StopIteration, signalling that this 'aclose()' await
  1970. is done.
  1971. */
  1972. PyErr_Clear();
  1973. PyErr_SetNone(PyExc_StopIteration);
  1974. }
  1975. return retval;
  1976. }
  1977. }
  1978. static PyObject *
  1979. async_gen_athrow_iternext(PyAsyncGenAThrow *o)
  1980. {
  1981. return async_gen_athrow_send(o, Py_None);
  1982. }
  1983. static PyObject *
  1984. async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
  1985. {
  1986. o->agt_state = AWAITABLE_STATE_CLOSED;
  1987. Py_RETURN_NONE;
  1988. }
  1989. static PyMethodDef async_gen_athrow_methods[] = {
  1990. {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
  1991. {"throw", _PyCFunction_CAST(async_gen_athrow_throw),
  1992. METH_FASTCALL, throw_doc},
  1993. {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
  1994. {NULL, NULL} /* Sentinel */
  1995. };
  1996. static PyAsyncMethods async_gen_athrow_as_async = {
  1997. PyObject_SelfIter, /* am_await */
  1998. 0, /* am_aiter */
  1999. 0, /* am_anext */
  2000. 0, /* am_send */
  2001. };
  2002. PyTypeObject _PyAsyncGenAThrow_Type = {
  2003. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2004. "async_generator_athrow", /* tp_name */
  2005. sizeof(PyAsyncGenAThrow), /* tp_basicsize */
  2006. 0, /* tp_itemsize */
  2007. /* methods */
  2008. (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
  2009. 0, /* tp_vectorcall_offset */
  2010. 0, /* tp_getattr */
  2011. 0, /* tp_setattr */
  2012. &async_gen_athrow_as_async, /* tp_as_async */
  2013. 0, /* tp_repr */
  2014. 0, /* tp_as_number */
  2015. 0, /* tp_as_sequence */
  2016. 0, /* tp_as_mapping */
  2017. 0, /* tp_hash */
  2018. 0, /* tp_call */
  2019. 0, /* tp_str */
  2020. PyObject_GenericGetAttr, /* tp_getattro */
  2021. 0, /* tp_setattro */
  2022. 0, /* tp_as_buffer */
  2023. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  2024. 0, /* tp_doc */
  2025. (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
  2026. 0, /* tp_clear */
  2027. 0, /* tp_richcompare */
  2028. 0, /* tp_weaklistoffset */
  2029. PyObject_SelfIter, /* tp_iter */
  2030. (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
  2031. async_gen_athrow_methods, /* tp_methods */
  2032. 0, /* tp_members */
  2033. 0, /* tp_getset */
  2034. 0, /* tp_base */
  2035. 0, /* tp_dict */
  2036. 0, /* tp_descr_get */
  2037. 0, /* tp_descr_set */
  2038. 0, /* tp_dictoffset */
  2039. 0, /* tp_init */
  2040. 0, /* tp_alloc */
  2041. 0, /* tp_new */
  2042. };
  2043. static PyObject *
  2044. async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
  2045. {
  2046. PyAsyncGenAThrow *o;
  2047. o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
  2048. if (o == NULL) {
  2049. return NULL;
  2050. }
  2051. o->agt_gen = (PyAsyncGenObject*)Py_NewRef(gen);
  2052. o->agt_args = Py_XNewRef(args);
  2053. o->agt_state = AWAITABLE_STATE_INIT;
  2054. _PyObject_GC_TRACK((PyObject*)o);
  2055. return (PyObject*)o;
  2056. }