genobject.c 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339
  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. PyErr_SetString(
  1581. PyExc_RuntimeError,
  1582. "anext(): asynchronous generator is already running");
  1583. return NULL;
  1584. }
  1585. if (arg == NULL || arg == Py_None) {
  1586. arg = o->ags_sendval;
  1587. }
  1588. o->ags_state = AWAITABLE_STATE_ITER;
  1589. }
  1590. o->ags_gen->ag_running_async = 1;
  1591. result = gen_send((PyGenObject*)o->ags_gen, arg);
  1592. result = async_gen_unwrap_value(o->ags_gen, result);
  1593. if (result == NULL) {
  1594. o->ags_state = AWAITABLE_STATE_CLOSED;
  1595. }
  1596. return result;
  1597. }
  1598. static PyObject *
  1599. async_gen_asend_iternext(PyAsyncGenASend *o)
  1600. {
  1601. return async_gen_asend_send(o, NULL);
  1602. }
  1603. static PyObject *
  1604. async_gen_asend_throw(PyAsyncGenASend *o, PyObject *const *args, Py_ssize_t nargs)
  1605. {
  1606. PyObject *result;
  1607. if (o->ags_state == AWAITABLE_STATE_CLOSED) {
  1608. PyErr_SetString(
  1609. PyExc_RuntimeError,
  1610. "cannot reuse already awaited __anext__()/asend()");
  1611. return NULL;
  1612. }
  1613. result = gen_throw((PyGenObject*)o->ags_gen, args, nargs);
  1614. result = async_gen_unwrap_value(o->ags_gen, result);
  1615. if (result == NULL) {
  1616. o->ags_state = AWAITABLE_STATE_CLOSED;
  1617. }
  1618. return result;
  1619. }
  1620. static PyObject *
  1621. async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
  1622. {
  1623. o->ags_state = AWAITABLE_STATE_CLOSED;
  1624. Py_RETURN_NONE;
  1625. }
  1626. static PyMethodDef async_gen_asend_methods[] = {
  1627. {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
  1628. {"throw", _PyCFunction_CAST(async_gen_asend_throw), METH_FASTCALL, throw_doc},
  1629. {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
  1630. {NULL, NULL} /* Sentinel */
  1631. };
  1632. static PyAsyncMethods async_gen_asend_as_async = {
  1633. PyObject_SelfIter, /* am_await */
  1634. 0, /* am_aiter */
  1635. 0, /* am_anext */
  1636. 0, /* am_send */
  1637. };
  1638. PyTypeObject _PyAsyncGenASend_Type = {
  1639. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1640. "async_generator_asend", /* tp_name */
  1641. sizeof(PyAsyncGenASend), /* tp_basicsize */
  1642. 0, /* tp_itemsize */
  1643. /* methods */
  1644. (destructor)async_gen_asend_dealloc, /* tp_dealloc */
  1645. 0, /* tp_vectorcall_offset */
  1646. 0, /* tp_getattr */
  1647. 0, /* tp_setattr */
  1648. &async_gen_asend_as_async, /* tp_as_async */
  1649. 0, /* tp_repr */
  1650. 0, /* tp_as_number */
  1651. 0, /* tp_as_sequence */
  1652. 0, /* tp_as_mapping */
  1653. 0, /* tp_hash */
  1654. 0, /* tp_call */
  1655. 0, /* tp_str */
  1656. PyObject_GenericGetAttr, /* tp_getattro */
  1657. 0, /* tp_setattro */
  1658. 0, /* tp_as_buffer */
  1659. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1660. 0, /* tp_doc */
  1661. (traverseproc)async_gen_asend_traverse, /* tp_traverse */
  1662. 0, /* tp_clear */
  1663. 0, /* tp_richcompare */
  1664. 0, /* tp_weaklistoffset */
  1665. PyObject_SelfIter, /* tp_iter */
  1666. (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
  1667. async_gen_asend_methods, /* tp_methods */
  1668. 0, /* tp_members */
  1669. 0, /* tp_getset */
  1670. 0, /* tp_base */
  1671. 0, /* tp_dict */
  1672. 0, /* tp_descr_get */
  1673. 0, /* tp_descr_set */
  1674. 0, /* tp_dictoffset */
  1675. 0, /* tp_init */
  1676. 0, /* tp_alloc */
  1677. 0, /* tp_new */
  1678. };
  1679. static PyObject *
  1680. async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
  1681. {
  1682. PyAsyncGenASend *o;
  1683. #if _PyAsyncGen_MAXFREELIST > 0
  1684. struct _Py_async_gen_state *state = get_async_gen_state();
  1685. #ifdef Py_DEBUG
  1686. // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
  1687. assert(state->asend_numfree != -1);
  1688. #endif
  1689. if (state->asend_numfree) {
  1690. state->asend_numfree--;
  1691. o = state->asend_freelist[state->asend_numfree];
  1692. _Py_NewReference((PyObject *)o);
  1693. }
  1694. else
  1695. #endif
  1696. {
  1697. o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
  1698. if (o == NULL) {
  1699. return NULL;
  1700. }
  1701. }
  1702. o->ags_gen = (PyAsyncGenObject*)Py_NewRef(gen);
  1703. o->ags_sendval = Py_XNewRef(sendval);
  1704. o->ags_state = AWAITABLE_STATE_INIT;
  1705. _PyObject_GC_TRACK((PyObject*)o);
  1706. return (PyObject*)o;
  1707. }
  1708. /* ---------- Async Generator Value Wrapper ------------ */
  1709. static void
  1710. async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
  1711. {
  1712. _PyObject_GC_UNTRACK((PyObject *)o);
  1713. Py_CLEAR(o->agw_val);
  1714. #if _PyAsyncGen_MAXFREELIST > 0
  1715. struct _Py_async_gen_state *state = get_async_gen_state();
  1716. #ifdef Py_DEBUG
  1717. // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
  1718. assert(state->value_numfree != -1);
  1719. #endif
  1720. if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
  1721. assert(_PyAsyncGenWrappedValue_CheckExact(o));
  1722. state->value_freelist[state->value_numfree++] = o;
  1723. OBJECT_STAT_INC(to_freelist);
  1724. }
  1725. else
  1726. #endif
  1727. {
  1728. PyObject_GC_Del(o);
  1729. }
  1730. }
  1731. static int
  1732. async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
  1733. visitproc visit, void *arg)
  1734. {
  1735. Py_VISIT(o->agw_val);
  1736. return 0;
  1737. }
  1738. PyTypeObject _PyAsyncGenWrappedValue_Type = {
  1739. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1740. "async_generator_wrapped_value", /* tp_name */
  1741. sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
  1742. 0, /* tp_itemsize */
  1743. /* methods */
  1744. (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
  1745. 0, /* tp_vectorcall_offset */
  1746. 0, /* tp_getattr */
  1747. 0, /* tp_setattr */
  1748. 0, /* tp_as_async */
  1749. 0, /* tp_repr */
  1750. 0, /* tp_as_number */
  1751. 0, /* tp_as_sequence */
  1752. 0, /* tp_as_mapping */
  1753. 0, /* tp_hash */
  1754. 0, /* tp_call */
  1755. 0, /* tp_str */
  1756. PyObject_GenericGetAttr, /* tp_getattro */
  1757. 0, /* tp_setattro */
  1758. 0, /* tp_as_buffer */
  1759. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1760. 0, /* tp_doc */
  1761. (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
  1762. 0, /* tp_clear */
  1763. 0, /* tp_richcompare */
  1764. 0, /* tp_weaklistoffset */
  1765. 0, /* tp_iter */
  1766. 0, /* tp_iternext */
  1767. 0, /* tp_methods */
  1768. 0, /* tp_members */
  1769. 0, /* tp_getset */
  1770. 0, /* tp_base */
  1771. 0, /* tp_dict */
  1772. 0, /* tp_descr_get */
  1773. 0, /* tp_descr_set */
  1774. 0, /* tp_dictoffset */
  1775. 0, /* tp_init */
  1776. 0, /* tp_alloc */
  1777. 0, /* tp_new */
  1778. };
  1779. PyObject *
  1780. _PyAsyncGenValueWrapperNew(PyThreadState *tstate, PyObject *val)
  1781. {
  1782. _PyAsyncGenWrappedValue *o;
  1783. assert(val);
  1784. #if _PyAsyncGen_MAXFREELIST > 0
  1785. struct _Py_async_gen_state *state = &tstate->interp->async_gen;
  1786. #ifdef Py_DEBUG
  1787. // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
  1788. assert(state->value_numfree != -1);
  1789. #endif
  1790. if (state->value_numfree) {
  1791. state->value_numfree--;
  1792. o = state->value_freelist[state->value_numfree];
  1793. OBJECT_STAT_INC(from_freelist);
  1794. assert(_PyAsyncGenWrappedValue_CheckExact(o));
  1795. _Py_NewReference((PyObject*)o);
  1796. }
  1797. else
  1798. #endif
  1799. {
  1800. o = PyObject_GC_New(_PyAsyncGenWrappedValue,
  1801. &_PyAsyncGenWrappedValue_Type);
  1802. if (o == NULL) {
  1803. return NULL;
  1804. }
  1805. }
  1806. o->agw_val = Py_NewRef(val);
  1807. _PyObject_GC_TRACK((PyObject*)o);
  1808. return (PyObject*)o;
  1809. }
  1810. /* ---------- Async Generator AThrow awaitable ------------ */
  1811. static void
  1812. async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
  1813. {
  1814. _PyObject_GC_UNTRACK((PyObject *)o);
  1815. Py_CLEAR(o->agt_gen);
  1816. Py_CLEAR(o->agt_args);
  1817. PyObject_GC_Del(o);
  1818. }
  1819. static int
  1820. async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
  1821. {
  1822. Py_VISIT(o->agt_gen);
  1823. Py_VISIT(o->agt_args);
  1824. return 0;
  1825. }
  1826. static PyObject *
  1827. async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
  1828. {
  1829. PyGenObject *gen = (PyGenObject*)o->agt_gen;
  1830. PyObject *retval;
  1831. if (o->agt_state == AWAITABLE_STATE_CLOSED) {
  1832. PyErr_SetString(
  1833. PyExc_RuntimeError,
  1834. "cannot reuse already awaited aclose()/athrow()");
  1835. return NULL;
  1836. }
  1837. if (gen->gi_frame_state >= FRAME_COMPLETED) {
  1838. o->agt_state = AWAITABLE_STATE_CLOSED;
  1839. PyErr_SetNone(PyExc_StopIteration);
  1840. return NULL;
  1841. }
  1842. if (o->agt_state == AWAITABLE_STATE_INIT) {
  1843. if (o->agt_gen->ag_running_async) {
  1844. o->agt_state = AWAITABLE_STATE_CLOSED;
  1845. if (o->agt_args == NULL) {
  1846. PyErr_SetString(
  1847. PyExc_RuntimeError,
  1848. "aclose(): asynchronous generator is already running");
  1849. }
  1850. else {
  1851. PyErr_SetString(
  1852. PyExc_RuntimeError,
  1853. "athrow(): asynchronous generator is already running");
  1854. }
  1855. return NULL;
  1856. }
  1857. if (o->agt_gen->ag_closed) {
  1858. o->agt_state = AWAITABLE_STATE_CLOSED;
  1859. PyErr_SetNone(PyExc_StopAsyncIteration);
  1860. return NULL;
  1861. }
  1862. if (arg != Py_None) {
  1863. PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
  1864. return NULL;
  1865. }
  1866. o->agt_state = AWAITABLE_STATE_ITER;
  1867. o->agt_gen->ag_running_async = 1;
  1868. if (o->agt_args == NULL) {
  1869. /* aclose() mode */
  1870. o->agt_gen->ag_closed = 1;
  1871. retval = _gen_throw((PyGenObject *)gen,
  1872. 0, /* Do not close generator when
  1873. PyExc_GeneratorExit is passed */
  1874. PyExc_GeneratorExit, NULL, NULL);
  1875. if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
  1876. Py_DECREF(retval);
  1877. goto yield_close;
  1878. }
  1879. } else {
  1880. PyObject *typ;
  1881. PyObject *tb = NULL;
  1882. PyObject *val = NULL;
  1883. if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
  1884. &typ, &val, &tb)) {
  1885. return NULL;
  1886. }
  1887. retval = _gen_throw((PyGenObject *)gen,
  1888. 0, /* Do not close generator when
  1889. PyExc_GeneratorExit is passed */
  1890. typ, val, tb);
  1891. retval = async_gen_unwrap_value(o->agt_gen, retval);
  1892. }
  1893. if (retval == NULL) {
  1894. goto check_error;
  1895. }
  1896. return retval;
  1897. }
  1898. assert(o->agt_state == AWAITABLE_STATE_ITER);
  1899. retval = gen_send((PyGenObject *)gen, arg);
  1900. if (o->agt_args) {
  1901. return async_gen_unwrap_value(o->agt_gen, retval);
  1902. } else {
  1903. /* aclose() mode */
  1904. if (retval) {
  1905. if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
  1906. Py_DECREF(retval);
  1907. goto yield_close;
  1908. }
  1909. else {
  1910. return retval;
  1911. }
  1912. }
  1913. else {
  1914. goto check_error;
  1915. }
  1916. }
  1917. yield_close:
  1918. o->agt_gen->ag_running_async = 0;
  1919. o->agt_state = AWAITABLE_STATE_CLOSED;
  1920. PyErr_SetString(
  1921. PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
  1922. return NULL;
  1923. check_error:
  1924. o->agt_gen->ag_running_async = 0;
  1925. o->agt_state = AWAITABLE_STATE_CLOSED;
  1926. if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
  1927. PyErr_ExceptionMatches(PyExc_GeneratorExit))
  1928. {
  1929. if (o->agt_args == NULL) {
  1930. /* when aclose() is called we don't want to propagate
  1931. StopAsyncIteration or GeneratorExit; just raise
  1932. StopIteration, signalling that this 'aclose()' await
  1933. is done.
  1934. */
  1935. PyErr_Clear();
  1936. PyErr_SetNone(PyExc_StopIteration);
  1937. }
  1938. }
  1939. return NULL;
  1940. }
  1941. static PyObject *
  1942. async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *const *args, Py_ssize_t nargs)
  1943. {
  1944. PyObject *retval;
  1945. if (o->agt_state == AWAITABLE_STATE_CLOSED) {
  1946. PyErr_SetString(
  1947. PyExc_RuntimeError,
  1948. "cannot reuse already awaited aclose()/athrow()");
  1949. return NULL;
  1950. }
  1951. retval = gen_throw((PyGenObject*)o->agt_gen, args, nargs);
  1952. if (o->agt_args) {
  1953. return async_gen_unwrap_value(o->agt_gen, retval);
  1954. } else {
  1955. /* aclose() mode */
  1956. if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
  1957. o->agt_gen->ag_running_async = 0;
  1958. o->agt_state = AWAITABLE_STATE_CLOSED;
  1959. Py_DECREF(retval);
  1960. PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
  1961. return NULL;
  1962. }
  1963. if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
  1964. PyErr_ExceptionMatches(PyExc_GeneratorExit))
  1965. {
  1966. /* when aclose() is called we don't want to propagate
  1967. StopAsyncIteration or GeneratorExit; just raise
  1968. StopIteration, signalling that this 'aclose()' await
  1969. is done.
  1970. */
  1971. PyErr_Clear();
  1972. PyErr_SetNone(PyExc_StopIteration);
  1973. }
  1974. return retval;
  1975. }
  1976. }
  1977. static PyObject *
  1978. async_gen_athrow_iternext(PyAsyncGenAThrow *o)
  1979. {
  1980. return async_gen_athrow_send(o, Py_None);
  1981. }
  1982. static PyObject *
  1983. async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
  1984. {
  1985. o->agt_state = AWAITABLE_STATE_CLOSED;
  1986. Py_RETURN_NONE;
  1987. }
  1988. static PyMethodDef async_gen_athrow_methods[] = {
  1989. {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
  1990. {"throw", _PyCFunction_CAST(async_gen_athrow_throw),
  1991. METH_FASTCALL, throw_doc},
  1992. {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
  1993. {NULL, NULL} /* Sentinel */
  1994. };
  1995. static PyAsyncMethods async_gen_athrow_as_async = {
  1996. PyObject_SelfIter, /* am_await */
  1997. 0, /* am_aiter */
  1998. 0, /* am_anext */
  1999. 0, /* am_send */
  2000. };
  2001. PyTypeObject _PyAsyncGenAThrow_Type = {
  2002. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2003. "async_generator_athrow", /* tp_name */
  2004. sizeof(PyAsyncGenAThrow), /* tp_basicsize */
  2005. 0, /* tp_itemsize */
  2006. /* methods */
  2007. (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
  2008. 0, /* tp_vectorcall_offset */
  2009. 0, /* tp_getattr */
  2010. 0, /* tp_setattr */
  2011. &async_gen_athrow_as_async, /* tp_as_async */
  2012. 0, /* tp_repr */
  2013. 0, /* tp_as_number */
  2014. 0, /* tp_as_sequence */
  2015. 0, /* tp_as_mapping */
  2016. 0, /* tp_hash */
  2017. 0, /* tp_call */
  2018. 0, /* tp_str */
  2019. PyObject_GenericGetAttr, /* tp_getattro */
  2020. 0, /* tp_setattro */
  2021. 0, /* tp_as_buffer */
  2022. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  2023. 0, /* tp_doc */
  2024. (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
  2025. 0, /* tp_clear */
  2026. 0, /* tp_richcompare */
  2027. 0, /* tp_weaklistoffset */
  2028. PyObject_SelfIter, /* tp_iter */
  2029. (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
  2030. async_gen_athrow_methods, /* tp_methods */
  2031. 0, /* tp_members */
  2032. 0, /* tp_getset */
  2033. 0, /* tp_base */
  2034. 0, /* tp_dict */
  2035. 0, /* tp_descr_get */
  2036. 0, /* tp_descr_set */
  2037. 0, /* tp_dictoffset */
  2038. 0, /* tp_init */
  2039. 0, /* tp_alloc */
  2040. 0, /* tp_new */
  2041. };
  2042. static PyObject *
  2043. async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
  2044. {
  2045. PyAsyncGenAThrow *o;
  2046. o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
  2047. if (o == NULL) {
  2048. return NULL;
  2049. }
  2050. o->agt_gen = (PyAsyncGenObject*)Py_NewRef(gen);
  2051. o->agt_args = Py_XNewRef(args);
  2052. o->agt_state = AWAITABLE_STATE_INIT;
  2053. _PyObject_GC_TRACK((PyObject*)o);
  2054. return (PyObject*)o;
  2055. }