genobject.c 77 KB

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