genobject.c 77 KB

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