blob: c1b26e9da33bea467d9563d3c29c06ad8b4c3bbc [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02004#include "pycore_ceval.h" // _PyEval_EvalFrame()
Victor Stinnerbcda8f12018-11-21 22:27:47 +01005#include "pycore_object.h"
Chris Jerdonekda742ba2020-05-17 22:47:31 -07006#include "pycore_pyerrors.h" // _PyErr_ClearExcState()
Victor Stinner4a21e572020-04-15 02:35:41 +02007#include "pycore_pystate.h" // _PyThreadState_GET()
Martin v. Löwise440e472004-06-01 15:22:42 +00008#include "frameobject.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02009#include "structmember.h" // PyMemberDef
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +000011
Yury Selivanoveb636452016-09-08 22:01:51 -070012static PyObject *gen_close(PyGenObject *, PyObject *);
13static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
14static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
15
Andy Lester7386a702020-02-13 22:42:56 -060016static const char *NON_INIT_CORO_MSG = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -070017 "just-started coroutine";
18
Andy Lester7386a702020-02-13 22:42:56 -060019static const char *ASYNC_GEN_IGNORED_EXIT_MSG =
Yury Selivanoveb636452016-09-08 22:01:51 -070020 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100021
Mark Shannonae3087c2017-10-22 22:41:51 +010022static inline int
23exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
24{
25 Py_VISIT(exc_state->exc_type);
26 Py_VISIT(exc_state->exc_value);
27 Py_VISIT(exc_state->exc_traceback);
28 return 0;
29}
30
Martin v. Löwise440e472004-06-01 15:22:42 +000031static int
32gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
33{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Py_VISIT((PyObject *)gen->gi_frame);
35 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020036 Py_VISIT(gen->gi_name);
37 Py_VISIT(gen->gi_qualname);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080038 /* No need to visit cr_origin, because it's just tuples/str/int, so can't
39 participate in a reference cycle. */
Mark Shannonae3087c2017-10-22 22:41:51 +010040 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000041}
42
Antoine Pitrou58720d62013-08-05 23:26:40 +020043void
44_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020045{
46 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070047 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020048 PyObject *error_type, *error_value, *error_traceback;
49
Mark Shannoncb9879b2020-07-17 11:44:23 +010050 if (gen->gi_frame == NULL || _PyFrameHasCompleted(gen->gi_frame)) {
Antoine Pitrou796564c2013-07-30 19:59:21 +020051 /* Generator isn't paused, so no need to close */
52 return;
Yury Selivanov2a2270d2018-01-29 14:31:47 -050053 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020054
Yury Selivanoveb636452016-09-08 22:01:51 -070055 if (PyAsyncGen_CheckExact(self)) {
56 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
57 PyObject *finalizer = agen->ag_finalizer;
58 if (finalizer && !agen->ag_closed) {
59 /* Save the current exception, if any. */
60 PyErr_Fetch(&error_type, &error_value, &error_traceback);
61
Petr Viktorinffd97532020-02-11 17:46:57 +010062 res = PyObject_CallOneArg(finalizer, self);
Yury Selivanoveb636452016-09-08 22:01:51 -070063
64 if (res == NULL) {
65 PyErr_WriteUnraisable(self);
66 } else {
67 Py_DECREF(res);
68 }
69 /* Restore the saved exception. */
70 PyErr_Restore(error_type, error_value, error_traceback);
71 return;
72 }
73 }
74
Antoine Pitrou796564c2013-07-30 19:59:21 +020075 /* Save the current exception, if any. */
76 PyErr_Fetch(&error_type, &error_value, &error_traceback);
77
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070078 /* If `gen` is a coroutine, and if it was never awaited on,
79 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070080 if (gen->gi_code != NULL &&
81 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
Yury Selivanov2a2270d2018-01-29 14:31:47 -050082 gen->gi_frame->f_lasti == -1)
83 {
84 _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070085 }
86 else {
87 res = gen_close(gen, NULL);
88 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020089
Benjamin Petersonb88db872016-09-07 08:46:59 -070090 if (res == NULL) {
Yury Selivanov2a2270d2018-01-29 14:31:47 -050091 if (PyErr_Occurred()) {
Benjamin Petersonb88db872016-09-07 08:46:59 -070092 PyErr_WriteUnraisable(self);
Yury Selivanov2a2270d2018-01-29 14:31:47 -050093 }
Benjamin Petersonb88db872016-09-07 08:46:59 -070094 }
95 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020096 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070097 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020098
99 /* Restore the saved exception. */
100 PyErr_Restore(error_type, error_value, error_traceback);
101}
102
103static void
Martin v. Löwise440e472004-06-01 15:22:42 +0000104gen_dealloc(PyGenObject *gen)
105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (gen->gi_weakreflist != NULL)
111 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000112
Antoine Pitrou93963562013-05-14 20:37:52 +0200113 _PyObject_GC_TRACK(self);
114
Antoine Pitrou796564c2013-07-30 19:59:21 +0200115 if (PyObject_CallFinalizerFromDealloc(self))
116 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200117
118 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700119 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_finalizer);
124 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700125 if (gen->gi_frame != NULL) {
126 gen->gi_frame->f_gen = NULL;
127 Py_CLEAR(gen->gi_frame);
128 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800129 if (((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE) {
130 Py_CLEAR(((PyCoroObject *)gen)->cr_origin);
131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200133 Py_CLEAR(gen->gi_name);
134 Py_CLEAR(gen->gi_qualname);
Chris Jerdonekda742ba2020-05-17 22:47:31 -0700135 _PyErr_ClearExcState(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000137}
138
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300139static PySendResult
140gen_send_ex2(PyGenObject *gen, PyObject *arg, PyObject **presult,
141 int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000142{
Victor Stinner50b48572018-11-01 01:51:40 +0100143 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200145 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000146
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300147 *presult = NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100148 if (f != NULL && _PyFrame_IsExecuting(f)) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200149 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700150 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400151 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700152 }
153 else if (PyAsyncGen_CheckExact(gen)) {
154 msg = "async generator already executing";
155 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400156 PyErr_SetString(PyExc_ValueError, msg);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300157 return PYGEN_ERROR;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500158 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100159 if (f == NULL || _PyFrameHasCompleted(f)) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500160 if (PyCoro_CheckExact(gen) && !closing) {
161 /* `gen` is an exhausted coroutine: raise an error,
162 except when called from gen_close(), which should
163 always be a silent method. */
164 PyErr_SetString(
165 PyExc_RuntimeError,
166 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700167 }
168 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500169 /* `gen` is an exhausted generator:
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300170 only return value if called from send(). */
171 *presult = Py_None;
172 Py_INCREF(*presult);
173 return PYGEN_RETURN;
Yury Selivanov77c96812016-02-13 17:59:05 -0500174 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300175 return PYGEN_ERROR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000177
Mark Shannoncb9879b2020-07-17 11:44:23 +0100178 assert(_PyFrame_IsRunnable(f));
Antoine Pitrou93963562013-05-14 20:37:52 +0200179 if (f->f_lasti == -1) {
180 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200181 const char *msg = "can't send non-None value to a "
182 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700183 if (PyCoro_CheckExact(gen)) {
184 msg = NON_INIT_CORO_MSG;
185 }
186 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400187 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700188 "just-started async generator";
189 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400190 PyErr_SetString(PyExc_TypeError, msg);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300191 return PYGEN_ERROR;
Antoine Pitrou93963562013-05-14 20:37:52 +0200192 }
193 } else {
194 /* Push arg onto the frame's value stack */
195 result = arg ? arg : Py_None;
196 Py_INCREF(result);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100197 gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth] = result;
198 gen->gi_frame->f_stackdepth++;
Antoine Pitrou93963562013-05-14 20:37:52 +0200199 }
200
201 /* Generators always return to their most recent caller, not
202 * necessarily their creator. */
203 Py_XINCREF(tstate->frame);
204 assert(f->f_back == NULL);
205 f->f_back = tstate->frame;
206
Mark Shannonae3087c2017-10-22 22:41:51 +0100207 gen->gi_exc_state.previous_item = tstate->exc_info;
208 tstate->exc_info = &gen->gi_exc_state;
Chris Jerdonek7c30d122020-05-22 13:33:27 -0700209
210 if (exc) {
211 assert(_PyErr_Occurred(tstate));
212 _PyErr_ChainStackItem(NULL);
213 }
214
Victor Stinnerb9e68122019-11-14 12:20:46 +0100215 result = _PyEval_EvalFrame(tstate, f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100216 tstate->exc_info = gen->gi_exc_state.previous_item;
217 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200218
219 /* Don't keep the reference to f_back any longer than necessary. It
220 * may keep a chain of frames alive or it could create a reference
221 * cycle. */
222 assert(f->f_back == tstate->frame);
223 Py_CLEAR(f->f_back);
224
225 /* If the generator just returned (as opposed to yielding), signal
226 * that the generator is exhausted. */
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300227 if (result) {
228 if (!_PyFrameHasCompleted(f)) {
229 *presult = result;
230 return PYGEN_NEXT;
231 }
232 assert(result == Py_None || !PyAsyncGen_CheckExact(gen));
233 if (result == Py_None && !PyAsyncGen_CheckExact(gen) && !arg) {
234 /* Return NULL if called by gen_iternext() */
235 Py_CLEAR(result);
236 }
237 }
238 else {
239 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
240 const char *msg = "generator raised StopIteration";
241 if (PyCoro_CheckExact(gen)) {
242 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700243 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300244 else if (PyAsyncGen_CheckExact(gen)) {
245 msg = "async generator raised StopIteration";
Vladimir Matveev2b053612020-09-18 18:38:38 -0700246 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300247 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
248 }
249 else if (PyAsyncGen_CheckExact(gen) &&
250 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
251 {
252 /* code in `gen` raised a StopAsyncIteration error:
253 raise a RuntimeError.
254 */
255 const char *msg = "async generator raised StopAsyncIteration";
256 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
257 }
258 }
259
260 /* generator can't be rerun, so release the frame */
261 /* first clean reference cycle through stored exception traceback */
262 _PyErr_ClearExcState(&gen->gi_exc_state);
263 gen->gi_frame->f_gen = NULL;
264 gen->gi_frame = NULL;
265 Py_DECREF(f);
266
267 *presult = result;
268 return result ? PYGEN_RETURN : PYGEN_ERROR;
269}
270
271PySendResult
Vladimir Matveev24a54c02020-10-12 12:10:42 -0700272PyIter_Send(PyObject *iter, PyObject *arg, PyObject **result)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300273{
Vladimir Matveev24a54c02020-10-12 12:10:42 -0700274 _Py_IDENTIFIER(send);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300275 assert(arg != NULL);
Vladimir Matveev24a54c02020-10-12 12:10:42 -0700276 assert(result != NULL);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300277
Vladimir Matveev24a54c02020-10-12 12:10:42 -0700278 if (PyGen_CheckExact(iter) || PyCoro_CheckExact(iter)) {
279 return gen_send_ex2((PyGenObject *)iter, arg, result, 0, 0);
280 }
281
282 if (arg == Py_None && PyIter_Check(iter)) {
283 *result = Py_TYPE(iter)->tp_iternext(iter);
284 }
285 else {
286 *result = _PyObject_CallMethodIdOneArg(iter, &PyId_send, arg);
287 }
288 if (*result != NULL) {
289 return PYGEN_NEXT;
290 }
291 if (_PyGen_FetchStopIterationValue(result) == 0) {
292 return PYGEN_RETURN;
293 }
294 return PYGEN_ERROR;
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300295}
296
297static PyObject *
298gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
299{
300 PyObject *result;
301 if (gen_send_ex2(gen, arg, &result, exc, closing) == PYGEN_RETURN) {
302 if (PyAsyncGen_CheckExact(gen)) {
303 assert(result == Py_None);
304 PyErr_SetNone(PyExc_StopAsyncIteration);
305 }
306 else if (result == Py_None) {
307 PyErr_SetNone(PyExc_StopIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -0700308 }
309 else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300310 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200311 }
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300312 Py_CLEAR(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200313 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200314 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000315}
316
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000317PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000318"send(arg) -> send 'arg' into generator,\n\
319return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000320
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300321static PyObject *
322gen_send(PyGenObject *gen, PyObject *arg)
323{
324 return gen_send_ex(gen, arg, 0, 0);
325}
326
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000327PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400328"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000329
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000330/*
331 * This helper function is used by gen_close and gen_throw to
332 * close a subiterator being delegated to by yield-from.
333 */
334
Antoine Pitrou93963562013-05-14 20:37:52 +0200335static int
336gen_close_iter(PyObject *yf)
337{
338 PyObject *retval = NULL;
339 _Py_IDENTIFIER(close);
340
Yury Selivanoveb636452016-09-08 22:01:51 -0700341 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200342 retval = gen_close((PyGenObject *)yf, NULL);
343 if (retval == NULL)
344 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700345 }
346 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200347 PyObject *meth;
348 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
349 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700350 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200351 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700352 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200353 Py_DECREF(meth);
354 if (retval == NULL)
355 return -1;
356 }
357 }
358 Py_XDECREF(retval);
359 return 0;
360}
361
Yury Selivanovc724bae2016-03-02 11:30:46 -0500362PyObject *
363_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500364{
Antoine Pitrou93963562013-05-14 20:37:52 +0200365 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500366 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200367
Mark Shannoncb9879b2020-07-17 11:44:23 +0100368 if (f) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200369 PyObject *bytecode = f->f_code->co_code;
370 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
371
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100372 if (f->f_lasti < 0) {
373 /* Return immediately if the frame didn't start yet. YIELD_FROM
374 always come after LOAD_CONST: a code object should not start
375 with YIELD_FROM */
376 assert(code[0] != YIELD_FROM);
377 return NULL;
378 }
379
Serhiy Storchakaab874002016-09-11 13:48:15 +0300380 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200381 return NULL;
Mark Shannoncb9879b2020-07-17 11:44:23 +0100382 assert(f->f_stackdepth > 0);
383 yf = f->f_valuestack[f->f_stackdepth-1];
Antoine Pitrou93963562013-05-14 20:37:52 +0200384 Py_INCREF(yf);
385 }
386
387 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500388}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000389
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000390static PyObject *
391gen_close(PyGenObject *gen, PyObject *args)
392{
Antoine Pitrou93963562013-05-14 20:37:52 +0200393 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500394 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200395 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000396
Antoine Pitrou93963562013-05-14 20:37:52 +0200397 if (yf) {
Mark Shannoncb9879b2020-07-17 11:44:23 +0100398 PyFrameState state = gen->gi_frame->f_state;
399 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200400 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100401 gen->gi_frame->f_state = state;
Antoine Pitrou93963562013-05-14 20:37:52 +0200402 Py_DECREF(yf);
403 }
404 if (err == 0)
405 PyErr_SetNone(PyExc_GeneratorExit);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300406 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200407 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200408 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700409 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400410 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700411 } else if (PyAsyncGen_CheckExact(gen)) {
412 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
413 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200414 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400415 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 return NULL;
417 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200418 if (PyErr_ExceptionMatches(PyExc_StopIteration)
419 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
420 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200421 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200422 }
423 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000424}
425
Antoine Pitrou93963562013-05-14 20:37:52 +0200426
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000427PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000428"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
429return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000430
431static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700432_gen_throw(PyGenObject *gen, int close_on_genexit,
433 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000434{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500435 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000436 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000437
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 if (yf) {
439 PyObject *ret;
440 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700441 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
442 close_on_genexit
443 ) {
444 /* Asynchronous generators *should not* be closed right away.
445 We have to allow some awaits to work it through, hence the
446 `close_on_genexit` parameter here.
447 */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100448 PyFrameState state = gen->gi_frame->f_state;
449 gen->gi_frame->f_state = FRAME_EXECUTING;
Antoine Pitrou93963562013-05-14 20:37:52 +0200450 err = gen_close_iter(yf);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100451 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000452 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000453 if (err < 0)
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300454 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000455 goto throw_here;
456 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700457 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
458 /* `yf` is a generator or a coroutine. */
Chris Jerdonek8b339612020-07-09 06:27:23 -0700459 PyThreadState *tstate = _PyThreadState_GET();
460 PyFrameObject *f = tstate->frame;
461
Chris Jerdonek8b339612020-07-09 06:27:23 -0700462 /* Since we are fast-tracking things by skipping the eval loop,
463 we need to update the current frame so the stack trace
464 will be reported correctly to the user. */
465 /* XXX We should probably be updating the current frame
466 somewhere in ceval.c. */
467 tstate->frame = gen->gi_frame;
Yury Selivanoveb636452016-09-08 22:01:51 -0700468 /* Close the generator that we are currently iterating with
469 'yield from' or awaiting on with 'await'. */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100470 PyFrameState state = gen->gi_frame->f_state;
471 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700472 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
473 typ, val, tb);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100474 gen->gi_frame->f_state = state;
Chris Jerdonek8b339612020-07-09 06:27:23 -0700475 tstate->frame = f;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000476 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700477 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200478 PyObject *meth;
479 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
480 Py_DECREF(yf);
481 return NULL;
482 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000483 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000484 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000485 goto throw_here;
486 }
Mark Shannoncb9879b2020-07-17 11:44:23 +0100487 PyFrameState state = gen->gi_frame->f_state;
488 gen->gi_frame->f_state = FRAME_EXECUTING;
Yury Selivanoveb636452016-09-08 22:01:51 -0700489 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Mark Shannoncb9879b2020-07-17 11:44:23 +0100490 gen->gi_frame->f_state = state;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000491 Py_DECREF(meth);
492 }
493 Py_DECREF(yf);
494 if (!ret) {
495 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500496 /* Pop subiterator from stack */
Mark Shannoncb9879b2020-07-17 11:44:23 +0100497 assert(gen->gi_frame->f_stackdepth > 0);
498 gen->gi_frame->f_stackdepth--;
499 ret = gen->gi_frame->f_valuestack[gen->gi_frame->f_stackdepth];
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500500 assert(ret == yf);
501 Py_DECREF(ret);
502 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100503 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300504 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000505 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300506 ret = gen_send(gen, val);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000507 Py_DECREF(val);
508 } else {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300509 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000510 }
511 }
512 return ret;
513 }
514
515throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* First, check the traceback argument, replacing None with
517 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400518 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400520 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 else if (tb != NULL && !PyTraceBack_Check(tb)) {
522 PyErr_SetString(PyExc_TypeError,
523 "throw() third argument must be a traceback object");
524 return NULL;
525 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 Py_INCREF(typ);
528 Py_XINCREF(val);
529 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000530
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400531 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 else if (PyExceptionInstance_Check(typ)) {
535 /* Raising an instance. The value should be a dummy. */
536 if (val && val != Py_None) {
537 PyErr_SetString(PyExc_TypeError,
538 "instance exception may not have a separate value");
539 goto failed_throw;
540 }
541 else {
542 /* Normalize to raise <class>, <instance> */
543 Py_XDECREF(val);
544 val = typ;
545 typ = PyExceptionInstance_Class(typ);
546 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200547
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400548 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200549 /* Returns NULL if there's no traceback */
550 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
552 }
553 else {
554 /* Not something you can raise. throw() fails. */
555 PyErr_Format(PyExc_TypeError,
556 "exceptions must be classes or instances "
557 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000558 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 goto failed_throw;
560 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 PyErr_Restore(typ, val, tb);
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300563 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000564
565failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 /* Didn't use our arguments, so restore their original refcounts */
567 Py_DECREF(typ);
568 Py_XDECREF(val);
569 Py_XDECREF(tb);
570 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000571}
572
573
574static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700575gen_throw(PyGenObject *gen, PyObject *args)
576{
577 PyObject *typ;
578 PyObject *tb = NULL;
579 PyObject *val = NULL;
580
581 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
582 return NULL;
583 }
584
585 return _gen_throw(gen, 1, typ, val, tb);
586}
587
588
589static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000590gen_iternext(PyGenObject *gen)
591{
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300592 PyObject *result;
593 assert(PyGen_CheckExact(gen) || PyCoro_CheckExact(gen));
594 if (gen_send_ex2(gen, NULL, &result, 0, 0) == PYGEN_RETURN) {
595 if (result != Py_None) {
596 _PyGen_SetStopIterationValue(result);
597 }
598 Py_CLEAR(result);
599 }
600 return result;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000601}
602
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000603/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200604 * Set StopIteration with specified value. Value can be arbitrary object
605 * or NULL.
606 *
607 * Returns 0 if StopIteration is set and -1 if any other exception is set.
608 */
609int
610_PyGen_SetStopIterationValue(PyObject *value)
611{
612 PyObject *e;
613
614 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400615 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200616 {
617 /* Delay exception instantiation if we can */
618 PyErr_SetObject(PyExc_StopIteration, value);
619 return 0;
620 }
621 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100622 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200623 *
624 * We do this to handle a situation when "value" is a tuple, in which
625 * case PyErr_SetObject would set the value of StopIteration to
626 * the first element of the tuple.
627 *
628 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
629 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100630 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200631 if (e == NULL) {
632 return -1;
633 }
634 PyErr_SetObject(PyExc_StopIteration, e);
635 Py_DECREF(e);
636 return 0;
637}
638
639/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000640 * If StopIteration exception is set, fetches its 'value'
641 * attribute if any, otherwise sets pvalue to None.
642 *
643 * Returns 0 if no exception or StopIteration is set.
644 * If any other exception is set, returns -1 and leaves
645 * pvalue unchanged.
646 */
647
648int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200649_PyGen_FetchStopIterationValue(PyObject **pvalue)
650{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000651 PyObject *et, *ev, *tb;
652 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500653
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000654 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
655 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200656 if (ev) {
657 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300658 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200659 value = ((PyStopIterationObject *)ev)->value;
660 Py_INCREF(value);
661 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200662 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
663 /* Avoid normalisation and take ev as value.
664 *
665 * Normalization is required if the value is a tuple, in
666 * that case the value of StopIteration would be set to
667 * the first element of the tuple.
668 *
669 * (See _PyErr_CreateException code for details.)
670 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200671 value = ev;
672 } else {
673 /* normalisation required */
674 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300675 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200676 PyErr_Restore(et, ev, tb);
677 return -1;
678 }
679 value = ((PyStopIterationObject *)ev)->value;
680 Py_INCREF(value);
681 Py_DECREF(ev);
682 }
683 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000684 Py_XDECREF(et);
685 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000686 } else if (PyErr_Occurred()) {
687 return -1;
688 }
689 if (value == NULL) {
690 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100691 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000692 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000693 *pvalue = value;
694 return 0;
695}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000696
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000697static PyObject *
698gen_repr(PyGenObject *gen)
699{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400700 return PyUnicode_FromFormat("<generator object %S at %p>",
701 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000702}
703
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000704static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200705gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000706{
Victor Stinner40ee3012014-06-16 15:59:28 +0200707 Py_INCREF(op->gi_name);
708 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000709}
710
Victor Stinner40ee3012014-06-16 15:59:28 +0200711static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200712gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200713{
Victor Stinner40ee3012014-06-16 15:59:28 +0200714 /* Not legal to del gen.gi_name or to set it to anything
715 * other than a string object. */
716 if (value == NULL || !PyUnicode_Check(value)) {
717 PyErr_SetString(PyExc_TypeError,
718 "__name__ must be set to a string object");
719 return -1;
720 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200721 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300722 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200723 return 0;
724}
725
726static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200727gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200728{
729 Py_INCREF(op->gi_qualname);
730 return op->gi_qualname;
731}
732
733static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200734gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200735{
Victor Stinner40ee3012014-06-16 15:59:28 +0200736 /* Not legal to del gen.__qualname__ or to set it to anything
737 * other than a string object. */
738 if (value == NULL || !PyUnicode_Check(value)) {
739 PyErr_SetString(PyExc_TypeError,
740 "__qualname__ must be set to a string object");
741 return -1;
742 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200743 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300744 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200745 return 0;
746}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000747
Yury Selivanove13f8f32015-07-03 00:23:30 -0400748static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200749gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400750{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500751 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400752 if (yf == NULL)
753 Py_RETURN_NONE;
754 return yf;
755}
756
Mark Shannoncb9879b2020-07-17 11:44:23 +0100757
758static PyObject *
759gen_getrunning(PyGenObject *gen, void *Py_UNUSED(ignored))
760{
761 if (gen->gi_frame == NULL) {
762 Py_RETURN_FALSE;
763 }
764 return PyBool_FromLong(_PyFrame_IsExecuting(gen->gi_frame));
765}
766
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000767static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200768 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
769 PyDoc_STR("name of the generator")},
770 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
771 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400772 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
773 PyDoc_STR("object being iterated by yield from, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +0100774 {"gi_running", (getter)gen_getrunning, NULL, NULL},
Victor Stinner40ee3012014-06-16 15:59:28 +0200775 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000776};
777
Martin v. Löwise440e472004-06-01 15:22:42 +0000778static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200779 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
Victor Stinner40ee3012014-06-16 15:59:28 +0200780 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000782};
783
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000784static PyMethodDef gen_methods[] = {
Serhiy Storchaka6c333852020-09-22 08:08:54 +0300785 {"send",(PyCFunction)gen_send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
787 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
788 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000789};
790
Martin v. Löwise440e472004-06-01 15:22:42 +0000791PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PyVarObject_HEAD_INIT(&PyType_Type, 0)
793 "generator", /* tp_name */
794 sizeof(PyGenObject), /* tp_basicsize */
795 0, /* tp_itemsize */
796 /* methods */
797 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200798 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 0, /* tp_getattr */
800 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400801 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 (reprfunc)gen_repr, /* tp_repr */
803 0, /* tp_as_number */
804 0, /* tp_as_sequence */
805 0, /* tp_as_mapping */
806 0, /* tp_hash */
807 0, /* tp_call */
808 0, /* tp_str */
809 PyObject_GenericGetAttr, /* tp_getattro */
810 0, /* tp_setattro */
811 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200812 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 0, /* tp_doc */
814 (traverseproc)gen_traverse, /* tp_traverse */
815 0, /* tp_clear */
816 0, /* tp_richcompare */
817 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400818 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 (iternextfunc)gen_iternext, /* tp_iternext */
820 gen_methods, /* tp_methods */
821 gen_memberlist, /* tp_members */
822 gen_getsetlist, /* tp_getset */
823 0, /* tp_base */
824 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 0, /* tp_descr_get */
827 0, /* tp_descr_set */
828 0, /* tp_dictoffset */
829 0, /* tp_init */
830 0, /* tp_alloc */
831 0, /* tp_new */
832 0, /* tp_free */
833 0, /* tp_is_gc */
834 0, /* tp_bases */
835 0, /* tp_mro */
836 0, /* tp_cache */
837 0, /* tp_subclasses */
838 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200839 0, /* tp_del */
840 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200841 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000842};
843
Yury Selivanov5376ba92015-06-22 12:19:30 -0400844static PyObject *
845gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
846 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000847{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400848 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (gen == NULL) {
850 Py_DECREF(f);
851 return NULL;
852 }
853 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200854 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 Py_INCREF(f->f_code);
856 gen->gi_code = (PyObject *)(f->f_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100858 gen->gi_exc_state.exc_type = NULL;
859 gen->gi_exc_state.exc_value = NULL;
860 gen->gi_exc_state.exc_traceback = NULL;
861 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200862 if (name != NULL)
863 gen->gi_name = name;
864 else
865 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
866 Py_INCREF(gen->gi_name);
867 if (qualname != NULL)
868 gen->gi_qualname = qualname;
869 else
870 gen->gi_qualname = gen->gi_name;
871 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 _PyObject_GC_TRACK(gen);
873 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000874}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000875
Victor Stinner40ee3012014-06-16 15:59:28 +0200876PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400877PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
878{
879 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
880}
881
882PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200883PyGen_New(PyFrameObject *f)
884{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400885 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200886}
887
Yury Selivanov5376ba92015-06-22 12:19:30 -0400888/* Coroutine Object */
889
890typedef struct {
891 PyObject_HEAD
892 PyCoroObject *cw_coroutine;
893} PyCoroWrapper;
894
895static int
896gen_is_coroutine(PyObject *o)
897{
898 if (PyGen_CheckExact(o)) {
899 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
900 if (code->co_flags & CO_ITERABLE_COROUTINE) {
901 return 1;
902 }
903 }
904 return 0;
905}
906
Yury Selivanov75445082015-05-11 22:57:16 -0400907/*
908 * This helper function returns an awaitable for `o`:
909 * - `o` if `o` is a coroutine-object;
910 * - `type(o)->tp_as_async->am_await(o)`
911 *
912 * Raises a TypeError if it's not possible to return
913 * an awaitable and returns NULL.
914 */
915PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400916_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400917{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400918 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400919 PyTypeObject *ot;
920
Yury Selivanov5376ba92015-06-22 12:19:30 -0400921 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
922 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400923 Py_INCREF(o);
924 return o;
925 }
926
927 ot = Py_TYPE(o);
928 if (ot->tp_as_async != NULL) {
929 getter = ot->tp_as_async->am_await;
930 }
931 if (getter != NULL) {
932 PyObject *res = (*getter)(o);
933 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400934 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
935 /* __await__ must return an *iterator*, not
936 a coroutine or another awaitable (see PEP 492) */
937 PyErr_SetString(PyExc_TypeError,
938 "__await__() returned a coroutine");
939 Py_CLEAR(res);
940 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400941 PyErr_Format(PyExc_TypeError,
942 "__await__() returned non-iterator "
943 "of type '%.100s'",
944 Py_TYPE(res)->tp_name);
945 Py_CLEAR(res);
946 }
Yury Selivanov75445082015-05-11 22:57:16 -0400947 }
948 return res;
949 }
950
951 PyErr_Format(PyExc_TypeError,
952 "object %.100s can't be used in 'await' expression",
953 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400954 return NULL;
955}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400956
957static PyObject *
958coro_repr(PyCoroObject *coro)
959{
960 return PyUnicode_FromFormat("<coroutine object %S at %p>",
961 coro->cr_qualname, coro);
962}
963
964static PyObject *
965coro_await(PyCoroObject *coro)
966{
967 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
968 if (cw == NULL) {
969 return NULL;
970 }
971 Py_INCREF(coro);
972 cw->cw_coroutine = coro;
973 _PyObject_GC_TRACK(cw);
974 return (PyObject *)cw;
975}
976
Yury Selivanove13f8f32015-07-03 00:23:30 -0400977static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200978coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400979{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500980 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400981 if (yf == NULL)
982 Py_RETURN_NONE;
983 return yf;
984}
985
Mark Shannoncb9879b2020-07-17 11:44:23 +0100986static PyObject *
987cr_getrunning(PyCoroObject *coro, void *Py_UNUSED(ignored))
988{
989 if (coro->cr_frame == NULL) {
990 Py_RETURN_FALSE;
991 }
992 return PyBool_FromLong(_PyFrame_IsExecuting(coro->cr_frame));
993}
994
Yury Selivanov5376ba92015-06-22 12:19:30 -0400995static PyGetSetDef coro_getsetlist[] = {
996 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
997 PyDoc_STR("name of the coroutine")},
998 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
999 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -04001000 {"cr_await", (getter)coro_get_cr_await, NULL,
1001 PyDoc_STR("object being awaited on, or None")},
Mark Shannoncb9879b2020-07-17 11:44:23 +01001002 {"cr_running", (getter)cr_getrunning, NULL, NULL},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001003 {NULL} /* Sentinel */
1004};
1005
1006static PyMemberDef coro_memberlist[] = {
1007 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001008 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001009 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001010 {NULL} /* Sentinel */
1011};
1012
1013PyDoc_STRVAR(coro_send_doc,
1014"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001015return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001016
1017PyDoc_STRVAR(coro_throw_doc,
1018"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -04001019return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001020
1021PyDoc_STRVAR(coro_close_doc,
1022"close() -> raise GeneratorExit inside coroutine.");
1023
1024static PyMethodDef coro_methods[] = {
Vladimir Matveev037245c2020-10-09 17:15:15 -07001025 {"send",(PyCFunction)gen_send, METH_O, coro_send_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001026 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
1027 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
1028 {NULL, NULL} /* Sentinel */
1029};
1030
1031static PyAsyncMethods coro_as_async = {
1032 (unaryfunc)coro_await, /* am_await */
1033 0, /* am_aiter */
1034 0 /* am_anext */
1035};
1036
1037PyTypeObject PyCoro_Type = {
1038 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1039 "coroutine", /* tp_name */
1040 sizeof(PyCoroObject), /* tp_basicsize */
1041 0, /* tp_itemsize */
1042 /* methods */
1043 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001044 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001045 0, /* tp_getattr */
1046 0, /* tp_setattr */
1047 &coro_as_async, /* tp_as_async */
1048 (reprfunc)coro_repr, /* tp_repr */
1049 0, /* tp_as_number */
1050 0, /* tp_as_sequence */
1051 0, /* tp_as_mapping */
1052 0, /* tp_hash */
1053 0, /* tp_call */
1054 0, /* tp_str */
1055 PyObject_GenericGetAttr, /* tp_getattro */
1056 0, /* tp_setattro */
1057 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001058 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001059 0, /* tp_doc */
1060 (traverseproc)gen_traverse, /* tp_traverse */
1061 0, /* tp_clear */
1062 0, /* tp_richcompare */
1063 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1064 0, /* tp_iter */
1065 0, /* tp_iternext */
1066 coro_methods, /* tp_methods */
1067 coro_memberlist, /* tp_members */
1068 coro_getsetlist, /* tp_getset */
1069 0, /* tp_base */
1070 0, /* tp_dict */
1071 0, /* tp_descr_get */
1072 0, /* tp_descr_set */
1073 0, /* tp_dictoffset */
1074 0, /* tp_init */
1075 0, /* tp_alloc */
1076 0, /* tp_new */
1077 0, /* tp_free */
1078 0, /* tp_is_gc */
1079 0, /* tp_bases */
1080 0, /* tp_mro */
1081 0, /* tp_cache */
1082 0, /* tp_subclasses */
1083 0, /* tp_weaklist */
1084 0, /* tp_del */
1085 0, /* tp_version_tag */
1086 _PyGen_Finalize, /* tp_finalize */
1087};
1088
1089static void
1090coro_wrapper_dealloc(PyCoroWrapper *cw)
1091{
1092 _PyObject_GC_UNTRACK((PyObject *)cw);
1093 Py_CLEAR(cw->cw_coroutine);
1094 PyObject_GC_Del(cw);
1095}
1096
1097static PyObject *
1098coro_wrapper_iternext(PyCoroWrapper *cw)
1099{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001100 return gen_iternext((PyGenObject *)cw->cw_coroutine);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001101}
1102
1103static PyObject *
1104coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1105{
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001106 return gen_send((PyGenObject *)cw->cw_coroutine, arg);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001107}
1108
1109static PyObject *
1110coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1111{
1112 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1113}
1114
1115static PyObject *
1116coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1117{
1118 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1119}
1120
1121static int
1122coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1123{
1124 Py_VISIT((PyObject *)cw->cw_coroutine);
1125 return 0;
1126}
1127
1128static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001129 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1130 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1131 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001132 {NULL, NULL} /* Sentinel */
1133};
1134
1135PyTypeObject _PyCoroWrapper_Type = {
1136 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1137 "coroutine_wrapper",
1138 sizeof(PyCoroWrapper), /* tp_basicsize */
1139 0, /* tp_itemsize */
1140 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001141 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001142 0, /* tp_getattr */
1143 0, /* tp_setattr */
1144 0, /* tp_as_async */
1145 0, /* tp_repr */
1146 0, /* tp_as_number */
1147 0, /* tp_as_sequence */
1148 0, /* tp_as_mapping */
1149 0, /* tp_hash */
1150 0, /* tp_call */
1151 0, /* tp_str */
1152 PyObject_GenericGetAttr, /* tp_getattro */
1153 0, /* tp_setattro */
1154 0, /* tp_as_buffer */
1155 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1156 "A wrapper object implementing __await__ for coroutines.",
1157 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1158 0, /* tp_clear */
1159 0, /* tp_richcompare */
1160 0, /* tp_weaklistoffset */
1161 PyObject_SelfIter, /* tp_iter */
1162 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1163 coro_wrapper_methods, /* tp_methods */
1164 0, /* tp_members */
1165 0, /* tp_getset */
1166 0, /* tp_base */
1167 0, /* tp_dict */
1168 0, /* tp_descr_get */
1169 0, /* tp_descr_set */
1170 0, /* tp_dictoffset */
1171 0, /* tp_init */
1172 0, /* tp_alloc */
1173 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001174 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001175};
1176
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001177static PyObject *
1178compute_cr_origin(int origin_depth)
1179{
1180 PyFrameObject *frame = PyEval_GetFrame();
1181 /* First count how many frames we have */
1182 int frame_count = 0;
1183 for (; frame && frame_count < origin_depth; ++frame_count) {
1184 frame = frame->f_back;
1185 }
1186
1187 /* Now collect them */
1188 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001189 if (cr_origin == NULL) {
1190 return NULL;
1191 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001192 frame = PyEval_GetFrame();
1193 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001194 PyCodeObject *code = frame->f_code;
1195 PyObject *frameinfo = Py_BuildValue("OiO",
1196 code->co_filename,
1197 PyFrame_GetLineNumber(frame),
1198 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001199 if (!frameinfo) {
1200 Py_DECREF(cr_origin);
1201 return NULL;
1202 }
1203 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1204 frame = frame->f_back;
1205 }
1206
1207 return cr_origin;
1208}
1209
Yury Selivanov5376ba92015-06-22 12:19:30 -04001210PyObject *
1211PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1212{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001213 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1214 if (!coro) {
1215 return NULL;
1216 }
1217
Victor Stinner50b48572018-11-01 01:51:40 +01001218 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001219 int origin_depth = tstate->coroutine_origin_tracking_depth;
1220
1221 if (origin_depth == 0) {
1222 ((PyCoroObject *)coro)->cr_origin = NULL;
1223 } else {
1224 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001225 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001226 if (!cr_origin) {
1227 Py_DECREF(coro);
1228 return NULL;
1229 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001230 }
1231
1232 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001233}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001234
1235
Yury Selivanoveb636452016-09-08 22:01:51 -07001236/* ========= Asynchronous Generators ========= */
1237
1238
1239typedef enum {
1240 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1241 AWAITABLE_STATE_ITER, /* being iterated */
1242 AWAITABLE_STATE_CLOSED, /* closed */
1243} AwaitableState;
1244
1245
Victor Stinner78a02c22020-06-05 02:34:14 +02001246typedef struct PyAsyncGenASend {
Yury Selivanoveb636452016-09-08 22:01:51 -07001247 PyObject_HEAD
1248 PyAsyncGenObject *ags_gen;
1249
1250 /* Can be NULL, when in the __anext__() mode
1251 (equivalent of "asend(None)") */
1252 PyObject *ags_sendval;
1253
1254 AwaitableState ags_state;
1255} PyAsyncGenASend;
1256
1257
Victor Stinner78a02c22020-06-05 02:34:14 +02001258typedef struct PyAsyncGenAThrow {
Yury Selivanoveb636452016-09-08 22:01:51 -07001259 PyObject_HEAD
1260 PyAsyncGenObject *agt_gen;
1261
1262 /* Can be NULL, when in the "aclose()" mode
1263 (equivalent of "athrow(GeneratorExit)") */
1264 PyObject *agt_args;
1265
1266 AwaitableState agt_state;
1267} PyAsyncGenAThrow;
1268
1269
Victor Stinner78a02c22020-06-05 02:34:14 +02001270typedef struct _PyAsyncGenWrappedValue {
Yury Selivanoveb636452016-09-08 22:01:51 -07001271 PyObject_HEAD
1272 PyObject *agw_val;
1273} _PyAsyncGenWrappedValue;
1274
1275
Yury Selivanoveb636452016-09-08 22:01:51 -07001276#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001277 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001278
1279#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001280 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001281
1282
1283static int
1284async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1285{
1286 Py_VISIT(gen->ag_finalizer);
1287 return gen_traverse((PyGenObject*)gen, visit, arg);
1288}
1289
1290
1291static PyObject *
1292async_gen_repr(PyAsyncGenObject *o)
1293{
1294 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1295 o->ag_qualname, o);
1296}
1297
1298
1299static int
1300async_gen_init_hooks(PyAsyncGenObject *o)
1301{
1302 PyThreadState *tstate;
1303 PyObject *finalizer;
1304 PyObject *firstiter;
1305
1306 if (o->ag_hooks_inited) {
1307 return 0;
1308 }
1309
1310 o->ag_hooks_inited = 1;
1311
Victor Stinner50b48572018-11-01 01:51:40 +01001312 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001313
1314 finalizer = tstate->async_gen_finalizer;
1315 if (finalizer) {
1316 Py_INCREF(finalizer);
1317 o->ag_finalizer = finalizer;
1318 }
1319
1320 firstiter = tstate->async_gen_firstiter;
1321 if (firstiter) {
1322 PyObject *res;
1323
1324 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001325 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001326 Py_DECREF(firstiter);
1327 if (res == NULL) {
1328 return 1;
1329 }
1330 Py_DECREF(res);
1331 }
1332
1333 return 0;
1334}
1335
1336
1337static PyObject *
1338async_gen_anext(PyAsyncGenObject *o)
1339{
1340 if (async_gen_init_hooks(o)) {
1341 return NULL;
1342 }
1343 return async_gen_asend_new(o, NULL);
1344}
1345
1346
1347static PyObject *
1348async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1349{
1350 if (async_gen_init_hooks(o)) {
1351 return NULL;
1352 }
1353 return async_gen_asend_new(o, arg);
1354}
1355
1356
1357static PyObject *
1358async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1359{
1360 if (async_gen_init_hooks(o)) {
1361 return NULL;
1362 }
1363 return async_gen_athrow_new(o, NULL);
1364}
1365
1366static PyObject *
1367async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1368{
1369 if (async_gen_init_hooks(o)) {
1370 return NULL;
1371 }
1372 return async_gen_athrow_new(o, args);
1373}
1374
1375
1376static PyGetSetDef async_gen_getsetlist[] = {
1377 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1378 PyDoc_STR("name of the async generator")},
1379 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1380 PyDoc_STR("qualified name of the async generator")},
1381 {"ag_await", (getter)coro_get_cr_await, NULL,
1382 PyDoc_STR("object being awaited on, or None")},
1383 {NULL} /* Sentinel */
1384};
1385
1386static PyMemberDef async_gen_memberlist[] = {
1387 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001388 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1389 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001390 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1391 {NULL} /* Sentinel */
1392};
1393
1394PyDoc_STRVAR(async_aclose_doc,
1395"aclose() -> raise GeneratorExit inside generator.");
1396
1397PyDoc_STRVAR(async_asend_doc,
1398"asend(v) -> send 'v' in generator.");
1399
1400PyDoc_STRVAR(async_athrow_doc,
1401"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1402
1403static PyMethodDef async_gen_methods[] = {
1404 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1405 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1406 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001407 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1408 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001409 {NULL, NULL} /* Sentinel */
1410};
1411
1412
1413static PyAsyncMethods async_gen_as_async = {
1414 0, /* am_await */
1415 PyObject_SelfIter, /* am_aiter */
1416 (unaryfunc)async_gen_anext /* am_anext */
1417};
1418
1419
1420PyTypeObject PyAsyncGen_Type = {
1421 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1422 "async_generator", /* tp_name */
1423 sizeof(PyAsyncGenObject), /* tp_basicsize */
1424 0, /* tp_itemsize */
1425 /* methods */
1426 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001427 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001428 0, /* tp_getattr */
1429 0, /* tp_setattr */
1430 &async_gen_as_async, /* tp_as_async */
1431 (reprfunc)async_gen_repr, /* tp_repr */
1432 0, /* tp_as_number */
1433 0, /* tp_as_sequence */
1434 0, /* tp_as_mapping */
1435 0, /* tp_hash */
1436 0, /* tp_call */
1437 0, /* tp_str */
1438 PyObject_GenericGetAttr, /* tp_getattro */
1439 0, /* tp_setattro */
1440 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001441 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001442 0, /* tp_doc */
1443 (traverseproc)async_gen_traverse, /* tp_traverse */
1444 0, /* tp_clear */
1445 0, /* tp_richcompare */
1446 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1447 0, /* tp_iter */
1448 0, /* tp_iternext */
1449 async_gen_methods, /* tp_methods */
1450 async_gen_memberlist, /* tp_members */
1451 async_gen_getsetlist, /* tp_getset */
1452 0, /* tp_base */
1453 0, /* tp_dict */
1454 0, /* tp_descr_get */
1455 0, /* tp_descr_set */
1456 0, /* tp_dictoffset */
1457 0, /* tp_init */
1458 0, /* tp_alloc */
1459 0, /* tp_new */
1460 0, /* tp_free */
1461 0, /* tp_is_gc */
1462 0, /* tp_bases */
1463 0, /* tp_mro */
1464 0, /* tp_cache */
1465 0, /* tp_subclasses */
1466 0, /* tp_weaklist */
1467 0, /* tp_del */
1468 0, /* tp_version_tag */
1469 _PyGen_Finalize, /* tp_finalize */
1470};
1471
1472
Victor Stinner522691c2020-06-23 16:40:40 +02001473static struct _Py_async_gen_state *
1474get_async_gen_state(void)
1475{
1476 PyInterpreterState *interp = _PyInterpreterState_GET();
1477 return &interp->async_gen;
1478}
1479
1480
Yury Selivanoveb636452016-09-08 22:01:51 -07001481PyObject *
1482PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1483{
1484 PyAsyncGenObject *o;
1485 o = (PyAsyncGenObject *)gen_new_with_qualname(
1486 &PyAsyncGen_Type, f, name, qualname);
1487 if (o == NULL) {
1488 return NULL;
1489 }
1490 o->ag_finalizer = NULL;
1491 o->ag_closed = 0;
1492 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001493 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001494 return (PyObject*)o;
1495}
1496
1497
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001498void
Victor Stinner78a02c22020-06-05 02:34:14 +02001499_PyAsyncGen_ClearFreeLists(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001500{
Victor Stinner78a02c22020-06-05 02:34:14 +02001501 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1502
1503 while (state->value_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001504 _PyAsyncGenWrappedValue *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001505 o = state->value_freelist[--state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001506 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001507 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001508 }
1509
Victor Stinner78a02c22020-06-05 02:34:14 +02001510 while (state->asend_numfree) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001511 PyAsyncGenASend *o;
Victor Stinner78a02c22020-06-05 02:34:14 +02001512 o = state->asend_freelist[--state->asend_numfree];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001513 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001514 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001515 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001516}
1517
1518void
Victor Stinner78a02c22020-06-05 02:34:14 +02001519_PyAsyncGen_Fini(PyThreadState *tstate)
Yury Selivanoveb636452016-09-08 22:01:51 -07001520{
Victor Stinner78a02c22020-06-05 02:34:14 +02001521 _PyAsyncGen_ClearFreeLists(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +02001522#ifdef Py_DEBUG
1523 struct _Py_async_gen_state *state = &tstate->interp->async_gen;
1524 state->value_numfree = -1;
1525 state->asend_numfree = -1;
1526#endif
Yury Selivanoveb636452016-09-08 22:01:51 -07001527}
1528
1529
1530static PyObject *
1531async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1532{
1533 if (result == NULL) {
1534 if (!PyErr_Occurred()) {
1535 PyErr_SetNone(PyExc_StopAsyncIteration);
1536 }
1537
1538 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1539 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1540 ) {
1541 gen->ag_closed = 1;
1542 }
1543
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001544 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001545 return NULL;
1546 }
1547
1548 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1549 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001550 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001551 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001552 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001553 return NULL;
1554 }
1555
1556 return result;
1557}
1558
1559
1560/* ---------- Async Generator ASend Awaitable ------------ */
1561
1562
1563static void
1564async_gen_asend_dealloc(PyAsyncGenASend *o)
1565{
Yury Selivanov29310c42016-11-08 19:46:22 -05001566 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001567 Py_CLEAR(o->ags_gen);
1568 Py_CLEAR(o->ags_sendval);
Victor Stinner522691c2020-06-23 16:40:40 +02001569 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001570#ifdef Py_DEBUG
1571 // async_gen_asend_dealloc() must not be called after _PyAsyncGen_Fini()
1572 assert(state->asend_numfree != -1);
1573#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001574 if (state->asend_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001575 assert(PyAsyncGenASend_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001576 state->asend_freelist[state->asend_numfree++] = o;
1577 }
1578 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001579 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001580 }
1581}
1582
Yury Selivanov29310c42016-11-08 19:46:22 -05001583static int
1584async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1585{
1586 Py_VISIT(o->ags_gen);
1587 Py_VISIT(o->ags_sendval);
1588 return 0;
1589}
1590
Yury Selivanoveb636452016-09-08 22:01:51 -07001591
1592static PyObject *
1593async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1594{
1595 PyObject *result;
1596
1597 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001598 PyErr_SetString(
1599 PyExc_RuntimeError,
1600 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001601 return NULL;
1602 }
1603
1604 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001605 if (o->ags_gen->ag_running_async) {
1606 PyErr_SetString(
1607 PyExc_RuntimeError,
1608 "anext(): asynchronous generator is already running");
1609 return NULL;
1610 }
1611
Yury Selivanoveb636452016-09-08 22:01:51 -07001612 if (arg == NULL || arg == Py_None) {
1613 arg = o->ags_sendval;
1614 }
1615 o->ags_state = AWAITABLE_STATE_ITER;
1616 }
1617
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001618 o->ags_gen->ag_running_async = 1;
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001619 result = gen_send((PyGenObject*)o->ags_gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001620 result = async_gen_unwrap_value(o->ags_gen, result);
1621
1622 if (result == NULL) {
1623 o->ags_state = AWAITABLE_STATE_CLOSED;
1624 }
1625
1626 return result;
1627}
1628
1629
1630static PyObject *
1631async_gen_asend_iternext(PyAsyncGenASend *o)
1632{
1633 return async_gen_asend_send(o, NULL);
1634}
1635
1636
1637static PyObject *
1638async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1639{
1640 PyObject *result;
1641
1642 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001643 PyErr_SetString(
1644 PyExc_RuntimeError,
1645 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001646 return NULL;
1647 }
1648
1649 result = gen_throw((PyGenObject*)o->ags_gen, args);
1650 result = async_gen_unwrap_value(o->ags_gen, result);
1651
1652 if (result == NULL) {
1653 o->ags_state = AWAITABLE_STATE_CLOSED;
1654 }
1655
1656 return result;
1657}
1658
1659
1660static PyObject *
1661async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1662{
1663 o->ags_state = AWAITABLE_STATE_CLOSED;
1664 Py_RETURN_NONE;
1665}
1666
1667
1668static PyMethodDef async_gen_asend_methods[] = {
1669 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1670 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1671 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1672 {NULL, NULL} /* Sentinel */
1673};
1674
1675
1676static PyAsyncMethods async_gen_asend_as_async = {
1677 PyObject_SelfIter, /* am_await */
1678 0, /* am_aiter */
1679 0 /* am_anext */
1680};
1681
1682
1683PyTypeObject _PyAsyncGenASend_Type = {
1684 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1685 "async_generator_asend", /* tp_name */
1686 sizeof(PyAsyncGenASend), /* tp_basicsize */
1687 0, /* tp_itemsize */
1688 /* methods */
1689 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001690 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001691 0, /* tp_getattr */
1692 0, /* tp_setattr */
1693 &async_gen_asend_as_async, /* tp_as_async */
1694 0, /* tp_repr */
1695 0, /* tp_as_number */
1696 0, /* tp_as_sequence */
1697 0, /* tp_as_mapping */
1698 0, /* tp_hash */
1699 0, /* tp_call */
1700 0, /* tp_str */
1701 PyObject_GenericGetAttr, /* tp_getattro */
1702 0, /* tp_setattro */
1703 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001704 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001705 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001706 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001707 0, /* tp_clear */
1708 0, /* tp_richcompare */
1709 0, /* tp_weaklistoffset */
1710 PyObject_SelfIter, /* tp_iter */
1711 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1712 async_gen_asend_methods, /* tp_methods */
1713 0, /* tp_members */
1714 0, /* tp_getset */
1715 0, /* tp_base */
1716 0, /* tp_dict */
1717 0, /* tp_descr_get */
1718 0, /* tp_descr_set */
1719 0, /* tp_dictoffset */
1720 0, /* tp_init */
1721 0, /* tp_alloc */
1722 0, /* tp_new */
1723};
1724
1725
1726static PyObject *
1727async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1728{
1729 PyAsyncGenASend *o;
Victor Stinner522691c2020-06-23 16:40:40 +02001730 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001731#ifdef Py_DEBUG
1732 // async_gen_asend_new() must not be called after _PyAsyncGen_Fini()
1733 assert(state->asend_numfree != -1);
1734#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001735 if (state->asend_numfree) {
1736 state->asend_numfree--;
1737 o = state->asend_freelist[state->asend_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001738 _Py_NewReference((PyObject *)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001739 }
1740 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001741 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001742 if (o == NULL) {
1743 return NULL;
1744 }
1745 }
1746
1747 Py_INCREF(gen);
1748 o->ags_gen = gen;
1749
1750 Py_XINCREF(sendval);
1751 o->ags_sendval = sendval;
1752
1753 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001754
1755 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001756 return (PyObject*)o;
1757}
1758
1759
1760/* ---------- Async Generator Value Wrapper ------------ */
1761
1762
1763static void
1764async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1765{
Yury Selivanov29310c42016-11-08 19:46:22 -05001766 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001767 Py_CLEAR(o->agw_val);
Victor Stinner522691c2020-06-23 16:40:40 +02001768 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001769#ifdef Py_DEBUG
1770 // async_gen_wrapped_val_dealloc() must not be called after _PyAsyncGen_Fini()
1771 assert(state->value_numfree != -1);
1772#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001773 if (state->value_numfree < _PyAsyncGen_MAXFREELIST) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001774 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Victor Stinner78a02c22020-06-05 02:34:14 +02001775 state->value_freelist[state->value_numfree++] = o;
1776 }
1777 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001778 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001779 }
1780}
1781
1782
Yury Selivanov29310c42016-11-08 19:46:22 -05001783static int
1784async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1785 visitproc visit, void *arg)
1786{
1787 Py_VISIT(o->agw_val);
1788 return 0;
1789}
1790
1791
Yury Selivanoveb636452016-09-08 22:01:51 -07001792PyTypeObject _PyAsyncGenWrappedValue_Type = {
1793 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1794 "async_generator_wrapped_value", /* tp_name */
1795 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1796 0, /* tp_itemsize */
1797 /* methods */
1798 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001799 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001800 0, /* tp_getattr */
1801 0, /* tp_setattr */
1802 0, /* tp_as_async */
1803 0, /* tp_repr */
1804 0, /* tp_as_number */
1805 0, /* tp_as_sequence */
1806 0, /* tp_as_mapping */
1807 0, /* tp_hash */
1808 0, /* tp_call */
1809 0, /* tp_str */
1810 PyObject_GenericGetAttr, /* tp_getattro */
1811 0, /* tp_setattro */
1812 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001813 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001814 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001815 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001816 0, /* tp_clear */
1817 0, /* tp_richcompare */
1818 0, /* tp_weaklistoffset */
1819 0, /* tp_iter */
1820 0, /* tp_iternext */
1821 0, /* tp_methods */
1822 0, /* tp_members */
1823 0, /* tp_getset */
1824 0, /* tp_base */
1825 0, /* tp_dict */
1826 0, /* tp_descr_get */
1827 0, /* tp_descr_set */
1828 0, /* tp_dictoffset */
1829 0, /* tp_init */
1830 0, /* tp_alloc */
1831 0, /* tp_new */
1832};
1833
1834
1835PyObject *
1836_PyAsyncGenValueWrapperNew(PyObject *val)
1837{
1838 _PyAsyncGenWrappedValue *o;
1839 assert(val);
1840
Victor Stinner522691c2020-06-23 16:40:40 +02001841 struct _Py_async_gen_state *state = get_async_gen_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +02001842#ifdef Py_DEBUG
1843 // _PyAsyncGenValueWrapperNew() must not be called after _PyAsyncGen_Fini()
1844 assert(state->value_numfree != -1);
1845#endif
Victor Stinner78a02c22020-06-05 02:34:14 +02001846 if (state->value_numfree) {
1847 state->value_numfree--;
1848 o = state->value_freelist[state->value_numfree];
Yury Selivanoveb636452016-09-08 22:01:51 -07001849 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1850 _Py_NewReference((PyObject*)o);
Victor Stinner78a02c22020-06-05 02:34:14 +02001851 }
1852 else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001853 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1854 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001855 if (o == NULL) {
1856 return NULL;
1857 }
1858 }
1859 o->agw_val = val;
1860 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001861 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001862 return (PyObject*)o;
1863}
1864
1865
1866/* ---------- Async Generator AThrow awaitable ------------ */
1867
1868
1869static void
1870async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1871{
Yury Selivanov29310c42016-11-08 19:46:22 -05001872 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001873 Py_CLEAR(o->agt_gen);
1874 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001875 PyObject_GC_Del(o);
1876}
1877
1878
1879static int
1880async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1881{
1882 Py_VISIT(o->agt_gen);
1883 Py_VISIT(o->agt_args);
1884 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001885}
1886
1887
1888static PyObject *
1889async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1890{
1891 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1892 PyFrameObject *f = gen->gi_frame;
1893 PyObject *retval;
1894
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001895 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001896 PyErr_SetString(
1897 PyExc_RuntimeError,
1898 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001899 return NULL;
1900 }
1901
Mark Shannoncb9879b2020-07-17 11:44:23 +01001902 if (f == NULL || _PyFrameHasCompleted(f)) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001903 o->agt_state = AWAITABLE_STATE_CLOSED;
1904 PyErr_SetNone(PyExc_StopIteration);
1905 return NULL;
1906 }
1907
Yury Selivanoveb636452016-09-08 22:01:51 -07001908 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001909 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001910 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001911 if (o->agt_args == NULL) {
1912 PyErr_SetString(
1913 PyExc_RuntimeError,
1914 "aclose(): asynchronous generator is already running");
1915 }
1916 else {
1917 PyErr_SetString(
1918 PyExc_RuntimeError,
1919 "athrow(): asynchronous generator is already running");
1920 }
1921 return NULL;
1922 }
1923
Yury Selivanoveb636452016-09-08 22:01:51 -07001924 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001925 o->agt_state = AWAITABLE_STATE_CLOSED;
1926 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001927 return NULL;
1928 }
1929
1930 if (arg != Py_None) {
1931 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1932 return NULL;
1933 }
1934
1935 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001936 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001937
1938 if (o->agt_args == NULL) {
1939 /* aclose() mode */
1940 o->agt_gen->ag_closed = 1;
1941
1942 retval = _gen_throw((PyGenObject *)gen,
1943 0, /* Do not close generator when
1944 PyExc_GeneratorExit is passed */
1945 PyExc_GeneratorExit, NULL, NULL);
1946
1947 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1948 Py_DECREF(retval);
1949 goto yield_close;
1950 }
1951 } else {
1952 PyObject *typ;
1953 PyObject *tb = NULL;
1954 PyObject *val = NULL;
1955
1956 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1957 &typ, &val, &tb)) {
1958 return NULL;
1959 }
1960
1961 retval = _gen_throw((PyGenObject *)gen,
1962 0, /* Do not close generator when
1963 PyExc_GeneratorExit is passed */
1964 typ, val, tb);
1965 retval = async_gen_unwrap_value(o->agt_gen, retval);
1966 }
1967 if (retval == NULL) {
1968 goto check_error;
1969 }
1970 return retval;
1971 }
1972
1973 assert(o->agt_state == AWAITABLE_STATE_ITER);
1974
Serhiy Storchaka6c333852020-09-22 08:08:54 +03001975 retval = gen_send((PyGenObject *)gen, arg);
Yury Selivanoveb636452016-09-08 22:01:51 -07001976 if (o->agt_args) {
1977 return async_gen_unwrap_value(o->agt_gen, retval);
1978 } else {
1979 /* aclose() mode */
1980 if (retval) {
1981 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1982 Py_DECREF(retval);
1983 goto yield_close;
1984 }
1985 else {
1986 return retval;
1987 }
1988 }
1989 else {
1990 goto check_error;
1991 }
1992 }
1993
1994yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001995 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001996 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001997 PyErr_SetString(
1998 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1999 return NULL;
2000
2001check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07002002 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08002003 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04002004 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2005 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2006 {
Yury Selivanov41782e42016-11-16 18:16:17 -05002007 if (o->agt_args == NULL) {
2008 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04002009 StopAsyncIteration or GeneratorExit; just raise
2010 StopIteration, signalling that this 'aclose()' await
2011 is done.
2012 */
Yury Selivanov41782e42016-11-16 18:16:17 -05002013 PyErr_Clear();
2014 PyErr_SetNone(PyExc_StopIteration);
2015 }
2016 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002017 return NULL;
2018}
2019
2020
2021static PyObject *
2022async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
2023{
2024 PyObject *retval;
2025
Yury Selivanoveb636452016-09-08 22:01:51 -07002026 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02002027 PyErr_SetString(
2028 PyExc_RuntimeError,
2029 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07002030 return NULL;
2031 }
2032
2033 retval = gen_throw((PyGenObject*)o->agt_gen, args);
2034 if (o->agt_args) {
2035 return async_gen_unwrap_value(o->agt_gen, retval);
2036 } else {
2037 /* aclose() mode */
2038 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07002039 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08002040 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07002041 Py_DECREF(retval);
2042 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2043 return NULL;
2044 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08002045 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2046 PyErr_ExceptionMatches(PyExc_GeneratorExit))
2047 {
2048 /* when aclose() is called we don't want to propagate
2049 StopAsyncIteration or GeneratorExit; just raise
2050 StopIteration, signalling that this 'aclose()' await
2051 is done.
2052 */
2053 PyErr_Clear();
2054 PyErr_SetNone(PyExc_StopIteration);
2055 }
Yury Selivanoveb636452016-09-08 22:01:51 -07002056 return retval;
2057 }
2058}
2059
2060
2061static PyObject *
2062async_gen_athrow_iternext(PyAsyncGenAThrow *o)
2063{
2064 return async_gen_athrow_send(o, Py_None);
2065}
2066
2067
2068static PyObject *
2069async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
2070{
2071 o->agt_state = AWAITABLE_STATE_CLOSED;
2072 Py_RETURN_NONE;
2073}
2074
2075
2076static PyMethodDef async_gen_athrow_methods[] = {
2077 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
2078 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
2079 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
2080 {NULL, NULL} /* Sentinel */
2081};
2082
2083
2084static PyAsyncMethods async_gen_athrow_as_async = {
2085 PyObject_SelfIter, /* am_await */
2086 0, /* am_aiter */
2087 0 /* am_anext */
2088};
2089
2090
2091PyTypeObject _PyAsyncGenAThrow_Type = {
2092 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2093 "async_generator_athrow", /* tp_name */
2094 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2095 0, /* tp_itemsize */
2096 /* methods */
2097 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002098 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002099 0, /* tp_getattr */
2100 0, /* tp_setattr */
2101 &async_gen_athrow_as_async, /* tp_as_async */
2102 0, /* tp_repr */
2103 0, /* tp_as_number */
2104 0, /* tp_as_sequence */
2105 0, /* tp_as_mapping */
2106 0, /* tp_hash */
2107 0, /* tp_call */
2108 0, /* tp_str */
2109 PyObject_GenericGetAttr, /* tp_getattro */
2110 0, /* tp_setattro */
2111 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002113 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002114 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002115 0, /* tp_clear */
2116 0, /* tp_richcompare */
2117 0, /* tp_weaklistoffset */
2118 PyObject_SelfIter, /* tp_iter */
2119 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2120 async_gen_athrow_methods, /* tp_methods */
2121 0, /* tp_members */
2122 0, /* tp_getset */
2123 0, /* tp_base */
2124 0, /* tp_dict */
2125 0, /* tp_descr_get */
2126 0, /* tp_descr_set */
2127 0, /* tp_dictoffset */
2128 0, /* tp_init */
2129 0, /* tp_alloc */
2130 0, /* tp_new */
2131};
2132
2133
2134static PyObject *
2135async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2136{
2137 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002138 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002139 if (o == NULL) {
2140 return NULL;
2141 }
2142 o->agt_gen = gen;
2143 o->agt_args = args;
2144 o->agt_state = AWAITABLE_STATE_INIT;
2145 Py_INCREF(gen);
2146 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002147 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002148 return (PyObject*)o;
2149}