blob: 09efbab69a7d3af4eed62fa9045b8a6892f55670 [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
Yury Selivanov2a2270d2018-01-29 14:31:47 -050050 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) {
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
139static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500140gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000141{
Victor Stinner50b48572018-11-01 01:51:40 +0100142 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200144 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000145
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500146 if (gen->gi_running) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200147 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700148 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400149 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700150 }
151 else if (PyAsyncGen_CheckExact(gen)) {
152 msg = "async generator already executing";
153 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400154 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500155 return NULL;
156 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200157 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500158 if (PyCoro_CheckExact(gen) && !closing) {
159 /* `gen` is an exhausted coroutine: raise an error,
160 except when called from gen_close(), which should
161 always be a silent method. */
162 PyErr_SetString(
163 PyExc_RuntimeError,
164 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700165 }
166 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500167 /* `gen` is an exhausted generator:
168 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700169 if (PyAsyncGen_CheckExact(gen)) {
170 PyErr_SetNone(PyExc_StopAsyncIteration);
171 }
172 else {
173 PyErr_SetNone(PyExc_StopIteration);
174 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 return NULL;
177 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000178
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);
Antoine Pitrou93963562013-05-14 20:37:52 +0200191 return NULL;
192 }
193 } else {
194 /* Push arg onto the frame's value stack */
195 result = arg ? arg : Py_None;
196 Py_INCREF(result);
197 *(f->f_stacktop++) = result;
198 }
199
200 /* Generators always return to their most recent caller, not
201 * necessarily their creator. */
202 Py_XINCREF(tstate->frame);
203 assert(f->f_back == NULL);
204 f->f_back = tstate->frame;
205
206 gen->gi_running = 1;
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;
Miss Islington (bot)7f77ac42020-05-22 14:35:22 -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 gen->gi_running = 0;
219
220 /* Don't keep the reference to f_back any longer than necessary. It
221 * may keep a chain of frames alive or it could create a reference
222 * cycle. */
223 assert(f->f_back == tstate->frame);
224 Py_CLEAR(f->f_back);
225
226 /* If the generator just returned (as opposed to yielding), signal
227 * that the generator is exhausted. */
228 if (result && f->f_stacktop == NULL) {
229 if (result == Py_None) {
230 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700231 if (PyAsyncGen_CheckExact(gen)) {
232 PyErr_SetNone(PyExc_StopAsyncIteration);
233 }
234 else {
235 PyErr_SetNone(PyExc_StopIteration);
236 }
237 }
238 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700239 /* Async generators cannot return anything but None */
240 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200241 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200242 }
243 Py_CLEAR(result);
244 }
Yury Selivanov68333392015-05-22 11:16:47 -0400245 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500246 const char *msg = "generator raised StopIteration";
247 if (PyCoro_CheckExact(gen)) {
248 msg = "coroutine raised StopIteration";
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400249 }
Dong-hee Nad905df72020-02-14 02:37:17 +0900250 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500251 msg = "async generator raised StopIteration";
Yury Selivanov68333392015-05-22 11:16:47 -0400252 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500253 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
254
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400255 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500256 else if (!result && PyAsyncGen_CheckExact(gen) &&
Yury Selivanoveb636452016-09-08 22:01:51 -0700257 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
258 {
259 /* code in `gen` raised a StopAsyncIteration error:
260 raise a RuntimeError.
261 */
262 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300263 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700264 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200265
266 if (!result || f->f_stacktop == NULL) {
267 /* generator can't be rerun, so release the frame */
268 /* first clean reference cycle through stored exception traceback */
Chris Jerdonekda742ba2020-05-17 22:47:31 -0700269 _PyErr_ClearExcState(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200270 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200271 gen->gi_frame = NULL;
272 Py_DECREF(f);
273 }
274
275 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000276}
277
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000278PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000279"send(arg) -> send 'arg' into generator,\n\
280return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000281
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500282PyObject *
283_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000284{
Yury Selivanov77c96812016-02-13 17:59:05 -0500285 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000286}
287
288PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400289"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000290
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000291/*
292 * This helper function is used by gen_close and gen_throw to
293 * close a subiterator being delegated to by yield-from.
294 */
295
Antoine Pitrou93963562013-05-14 20:37:52 +0200296static int
297gen_close_iter(PyObject *yf)
298{
299 PyObject *retval = NULL;
300 _Py_IDENTIFIER(close);
301
Yury Selivanoveb636452016-09-08 22:01:51 -0700302 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200303 retval = gen_close((PyGenObject *)yf, NULL);
304 if (retval == NULL)
305 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700306 }
307 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200308 PyObject *meth;
309 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
310 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700311 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200312 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700313 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200314 Py_DECREF(meth);
315 if (retval == NULL)
316 return -1;
317 }
318 }
319 Py_XDECREF(retval);
320 return 0;
321}
322
Yury Selivanovc724bae2016-03-02 11:30:46 -0500323PyObject *
324_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500325{
Antoine Pitrou93963562013-05-14 20:37:52 +0200326 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500327 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200328
329 if (f && f->f_stacktop) {
330 PyObject *bytecode = f->f_code->co_code;
331 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
332
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100333 if (f->f_lasti < 0) {
334 /* Return immediately if the frame didn't start yet. YIELD_FROM
335 always come after LOAD_CONST: a code object should not start
336 with YIELD_FROM */
337 assert(code[0] != YIELD_FROM);
338 return NULL;
339 }
340
Serhiy Storchakaab874002016-09-11 13:48:15 +0300341 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200342 return NULL;
343 yf = f->f_stacktop[-1];
344 Py_INCREF(yf);
345 }
346
347 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500348}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000349
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000350static PyObject *
351gen_close(PyGenObject *gen, PyObject *args)
352{
Antoine Pitrou93963562013-05-14 20:37:52 +0200353 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500354 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200355 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000356
Antoine Pitrou93963562013-05-14 20:37:52 +0200357 if (yf) {
358 gen->gi_running = 1;
359 err = gen_close_iter(yf);
360 gen->gi_running = 0;
361 Py_DECREF(yf);
362 }
363 if (err == 0)
364 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500365 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200366 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200367 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700368 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400369 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700370 } else if (PyAsyncGen_CheckExact(gen)) {
371 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
372 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200373 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400374 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 return NULL;
376 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200377 if (PyErr_ExceptionMatches(PyExc_StopIteration)
378 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
379 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200380 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200381 }
382 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000383}
384
Antoine Pitrou93963562013-05-14 20:37:52 +0200385
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000386PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
388return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000389
390static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700391_gen_throw(PyGenObject *gen, int close_on_genexit,
392 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000393{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500394 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000395 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000396
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000397 if (yf) {
398 PyObject *ret;
399 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700400 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 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500407 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200408 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500409 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000410 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000411 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500412 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000413 goto throw_here;
414 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700415 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
416 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500417 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700418 /* Close the generator that we are currently iterating with
419 'yield from' or awaiting on with 'await'. */
420 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
421 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500422 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000423 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700424 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200425 PyObject *meth;
426 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
427 Py_DECREF(yf);
428 return NULL;
429 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000430 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000431 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000432 goto throw_here;
433 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500434 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700435 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500436 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000437 Py_DECREF(meth);
438 }
439 Py_DECREF(yf);
440 if (!ret) {
441 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500442 /* Pop subiterator from stack */
443 ret = *(--gen->gi_frame->f_stacktop);
444 assert(ret == yf);
445 Py_DECREF(ret);
446 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100447 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300448 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000449 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500450 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000451 Py_DECREF(val);
452 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500453 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000454 }
455 }
456 return ret;
457 }
458
459throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 /* First, check the traceback argument, replacing None with
461 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400462 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 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 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_INCREF(typ);
472 Py_XINCREF(val);
473 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000474
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400475 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 else if (PyExceptionInstance_Check(typ)) {
479 /* Raising an instance. The value should be a dummy. */
480 if (val && val != Py_None) {
481 PyErr_SetString(PyExc_TypeError,
482 "instance exception may not have a separate value");
483 goto failed_throw;
484 }
485 else {
486 /* Normalize to raise <class>, <instance> */
487 Py_XDECREF(val);
488 val = typ;
489 typ = PyExceptionInstance_Class(typ);
490 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200491
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400492 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200493 /* Returns NULL if there's no traceback */
494 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 }
496 }
497 else {
498 /* Not something you can raise. throw() fails. */
499 PyErr_Format(PyExc_TypeError,
500 "exceptions must be classes or instances "
501 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000502 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 goto failed_throw;
504 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500507 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000508
509failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* Didn't use our arguments, so restore their original refcounts */
511 Py_DECREF(typ);
512 Py_XDECREF(val);
513 Py_XDECREF(tb);
514 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000515}
516
517
518static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700519gen_throw(PyGenObject *gen, PyObject *args)
520{
521 PyObject *typ;
522 PyObject *tb = NULL;
523 PyObject *val = NULL;
524
525 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
526 return NULL;
527 }
528
529 return _gen_throw(gen, 1, typ, val, tb);
530}
531
532
533static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000534gen_iternext(PyGenObject *gen)
535{
Yury Selivanov77c96812016-02-13 17:59:05 -0500536 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000537}
538
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000539/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200540 * Set StopIteration with specified value. Value can be arbitrary object
541 * or NULL.
542 *
543 * Returns 0 if StopIteration is set and -1 if any other exception is set.
544 */
545int
546_PyGen_SetStopIterationValue(PyObject *value)
547{
548 PyObject *e;
549
550 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400551 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200552 {
553 /* Delay exception instantiation if we can */
554 PyErr_SetObject(PyExc_StopIteration, value);
555 return 0;
556 }
557 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100558 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200559 *
560 * We do this to handle a situation when "value" is a tuple, in which
561 * case PyErr_SetObject would set the value of StopIteration to
562 * the first element of the tuple.
563 *
564 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
565 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100566 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200567 if (e == NULL) {
568 return -1;
569 }
570 PyErr_SetObject(PyExc_StopIteration, e);
571 Py_DECREF(e);
572 return 0;
573}
574
575/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000576 * If StopIteration exception is set, fetches its 'value'
577 * attribute if any, otherwise sets pvalue to None.
578 *
579 * Returns 0 if no exception or StopIteration is set.
580 * If any other exception is set, returns -1 and leaves
581 * pvalue unchanged.
582 */
583
584int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200585_PyGen_FetchStopIterationValue(PyObject **pvalue)
586{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000587 PyObject *et, *ev, *tb;
588 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500589
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000590 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
591 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200592 if (ev) {
593 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300594 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200595 value = ((PyStopIterationObject *)ev)->value;
596 Py_INCREF(value);
597 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200598 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
599 /* Avoid normalisation and take ev as value.
600 *
601 * Normalization is required if the value is a tuple, in
602 * that case the value of StopIteration would be set to
603 * the first element of the tuple.
604 *
605 * (See _PyErr_CreateException code for details.)
606 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200607 value = ev;
608 } else {
609 /* normalisation required */
610 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300611 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200612 PyErr_Restore(et, ev, tb);
613 return -1;
614 }
615 value = ((PyStopIterationObject *)ev)->value;
616 Py_INCREF(value);
617 Py_DECREF(ev);
618 }
619 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000620 Py_XDECREF(et);
621 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000622 } else if (PyErr_Occurred()) {
623 return -1;
624 }
625 if (value == NULL) {
626 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100627 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000628 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000629 *pvalue = value;
630 return 0;
631}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000632
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000633static PyObject *
634gen_repr(PyGenObject *gen)
635{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400636 return PyUnicode_FromFormat("<generator object %S at %p>",
637 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000638}
639
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000640static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200641gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000642{
Victor Stinner40ee3012014-06-16 15:59:28 +0200643 Py_INCREF(op->gi_name);
644 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000645}
646
Victor Stinner40ee3012014-06-16 15:59:28 +0200647static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200648gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200649{
Victor Stinner40ee3012014-06-16 15:59:28 +0200650 /* Not legal to del gen.gi_name or to set it to anything
651 * other than a string object. */
652 if (value == NULL || !PyUnicode_Check(value)) {
653 PyErr_SetString(PyExc_TypeError,
654 "__name__ must be set to a string object");
655 return -1;
656 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200657 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300658 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200659 return 0;
660}
661
662static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200663gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200664{
665 Py_INCREF(op->gi_qualname);
666 return op->gi_qualname;
667}
668
669static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200670gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200671{
Victor Stinner40ee3012014-06-16 15:59:28 +0200672 /* Not legal to del gen.__qualname__ or to set it to anything
673 * other than a string object. */
674 if (value == NULL || !PyUnicode_Check(value)) {
675 PyErr_SetString(PyExc_TypeError,
676 "__qualname__ must be set to a string object");
677 return -1;
678 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200679 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300680 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200681 return 0;
682}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000683
Yury Selivanove13f8f32015-07-03 00:23:30 -0400684static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200685gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400686{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500687 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400688 if (yf == NULL)
689 Py_RETURN_NONE;
690 return yf;
691}
692
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000693static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200694 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
695 PyDoc_STR("name of the generator")},
696 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
697 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400698 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
699 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200700 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000701};
702
Martin v. Löwise440e472004-06-01 15:22:42 +0000703static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200704 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
705 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
706 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000708};
709
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000710static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500711 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
713 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
714 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000715};
716
Martin v. Löwise440e472004-06-01 15:22:42 +0000717PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 PyVarObject_HEAD_INIT(&PyType_Type, 0)
719 "generator", /* tp_name */
720 sizeof(PyGenObject), /* tp_basicsize */
721 0, /* tp_itemsize */
722 /* methods */
723 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200724 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 0, /* tp_getattr */
726 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400727 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 (reprfunc)gen_repr, /* tp_repr */
729 0, /* tp_as_number */
730 0, /* tp_as_sequence */
731 0, /* tp_as_mapping */
732 0, /* tp_hash */
733 0, /* tp_call */
734 0, /* tp_str */
735 PyObject_GenericGetAttr, /* tp_getattro */
736 0, /* tp_setattro */
737 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200738 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 0, /* tp_doc */
740 (traverseproc)gen_traverse, /* tp_traverse */
741 0, /* tp_clear */
742 0, /* tp_richcompare */
743 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400744 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 (iternextfunc)gen_iternext, /* tp_iternext */
746 gen_methods, /* tp_methods */
747 gen_memberlist, /* tp_members */
748 gen_getsetlist, /* tp_getset */
749 0, /* tp_base */
750 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 0, /* tp_descr_get */
753 0, /* tp_descr_set */
754 0, /* tp_dictoffset */
755 0, /* tp_init */
756 0, /* tp_alloc */
757 0, /* tp_new */
758 0, /* tp_free */
759 0, /* tp_is_gc */
760 0, /* tp_bases */
761 0, /* tp_mro */
762 0, /* tp_cache */
763 0, /* tp_subclasses */
764 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200765 0, /* tp_del */
766 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200767 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000768};
769
Yury Selivanov5376ba92015-06-22 12:19:30 -0400770static PyObject *
771gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
772 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000773{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400774 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (gen == NULL) {
776 Py_DECREF(f);
777 return NULL;
778 }
779 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200780 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 Py_INCREF(f->f_code);
782 gen->gi_code = (PyObject *)(f->f_code);
783 gen->gi_running = 0;
784 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100785 gen->gi_exc_state.exc_type = NULL;
786 gen->gi_exc_state.exc_value = NULL;
787 gen->gi_exc_state.exc_traceback = NULL;
788 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200789 if (name != NULL)
790 gen->gi_name = name;
791 else
792 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
793 Py_INCREF(gen->gi_name);
794 if (qualname != NULL)
795 gen->gi_qualname = qualname;
796 else
797 gen->gi_qualname = gen->gi_name;
798 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 _PyObject_GC_TRACK(gen);
800 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000801}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000802
Victor Stinner40ee3012014-06-16 15:59:28 +0200803PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400804PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
805{
806 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
807}
808
809PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200810PyGen_New(PyFrameObject *f)
811{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400812 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200813}
814
Yury Selivanov5376ba92015-06-22 12:19:30 -0400815/* Coroutine Object */
816
817typedef struct {
818 PyObject_HEAD
819 PyCoroObject *cw_coroutine;
820} PyCoroWrapper;
821
822static int
823gen_is_coroutine(PyObject *o)
824{
825 if (PyGen_CheckExact(o)) {
826 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
827 if (code->co_flags & CO_ITERABLE_COROUTINE) {
828 return 1;
829 }
830 }
831 return 0;
832}
833
Yury Selivanov75445082015-05-11 22:57:16 -0400834/*
835 * This helper function returns an awaitable for `o`:
836 * - `o` if `o` is a coroutine-object;
837 * - `type(o)->tp_as_async->am_await(o)`
838 *
839 * Raises a TypeError if it's not possible to return
840 * an awaitable and returns NULL.
841 */
842PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400843_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400844{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400845 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400846 PyTypeObject *ot;
847
Yury Selivanov5376ba92015-06-22 12:19:30 -0400848 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
849 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400850 Py_INCREF(o);
851 return o;
852 }
853
854 ot = Py_TYPE(o);
855 if (ot->tp_as_async != NULL) {
856 getter = ot->tp_as_async->am_await;
857 }
858 if (getter != NULL) {
859 PyObject *res = (*getter)(o);
860 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400861 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
862 /* __await__ must return an *iterator*, not
863 a coroutine or another awaitable (see PEP 492) */
864 PyErr_SetString(PyExc_TypeError,
865 "__await__() returned a coroutine");
866 Py_CLEAR(res);
867 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400868 PyErr_Format(PyExc_TypeError,
869 "__await__() returned non-iterator "
870 "of type '%.100s'",
871 Py_TYPE(res)->tp_name);
872 Py_CLEAR(res);
873 }
Yury Selivanov75445082015-05-11 22:57:16 -0400874 }
875 return res;
876 }
877
878 PyErr_Format(PyExc_TypeError,
879 "object %.100s can't be used in 'await' expression",
880 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400881 return NULL;
882}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400883
884static PyObject *
885coro_repr(PyCoroObject *coro)
886{
887 return PyUnicode_FromFormat("<coroutine object %S at %p>",
888 coro->cr_qualname, coro);
889}
890
891static PyObject *
892coro_await(PyCoroObject *coro)
893{
894 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
895 if (cw == NULL) {
896 return NULL;
897 }
898 Py_INCREF(coro);
899 cw->cw_coroutine = coro;
900 _PyObject_GC_TRACK(cw);
901 return (PyObject *)cw;
902}
903
Yury Selivanove13f8f32015-07-03 00:23:30 -0400904static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200905coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400906{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500907 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400908 if (yf == NULL)
909 Py_RETURN_NONE;
910 return yf;
911}
912
Yury Selivanov5376ba92015-06-22 12:19:30 -0400913static PyGetSetDef coro_getsetlist[] = {
914 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
915 PyDoc_STR("name of the coroutine")},
916 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
917 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400918 {"cr_await", (getter)coro_get_cr_await, NULL,
919 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400920 {NULL} /* Sentinel */
921};
922
923static PyMemberDef coro_memberlist[] = {
924 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
925 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
926 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800927 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400928 {NULL} /* Sentinel */
929};
930
931PyDoc_STRVAR(coro_send_doc,
932"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400933return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400934
935PyDoc_STRVAR(coro_throw_doc,
936"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400937return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400938
939PyDoc_STRVAR(coro_close_doc,
940"close() -> raise GeneratorExit inside coroutine.");
941
942static PyMethodDef coro_methods[] = {
943 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
944 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
945 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
946 {NULL, NULL} /* Sentinel */
947};
948
949static PyAsyncMethods coro_as_async = {
950 (unaryfunc)coro_await, /* am_await */
951 0, /* am_aiter */
952 0 /* am_anext */
953};
954
955PyTypeObject PyCoro_Type = {
956 PyVarObject_HEAD_INIT(&PyType_Type, 0)
957 "coroutine", /* tp_name */
958 sizeof(PyCoroObject), /* tp_basicsize */
959 0, /* tp_itemsize */
960 /* methods */
961 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200962 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400963 0, /* tp_getattr */
964 0, /* tp_setattr */
965 &coro_as_async, /* tp_as_async */
966 (reprfunc)coro_repr, /* tp_repr */
967 0, /* tp_as_number */
968 0, /* tp_as_sequence */
969 0, /* tp_as_mapping */
970 0, /* tp_hash */
971 0, /* tp_call */
972 0, /* tp_str */
973 PyObject_GenericGetAttr, /* tp_getattro */
974 0, /* tp_setattro */
975 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200976 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400977 0, /* tp_doc */
978 (traverseproc)gen_traverse, /* tp_traverse */
979 0, /* tp_clear */
980 0, /* tp_richcompare */
981 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
982 0, /* tp_iter */
983 0, /* tp_iternext */
984 coro_methods, /* tp_methods */
985 coro_memberlist, /* tp_members */
986 coro_getsetlist, /* tp_getset */
987 0, /* tp_base */
988 0, /* tp_dict */
989 0, /* tp_descr_get */
990 0, /* tp_descr_set */
991 0, /* tp_dictoffset */
992 0, /* tp_init */
993 0, /* tp_alloc */
994 0, /* tp_new */
995 0, /* tp_free */
996 0, /* tp_is_gc */
997 0, /* tp_bases */
998 0, /* tp_mro */
999 0, /* tp_cache */
1000 0, /* tp_subclasses */
1001 0, /* tp_weaklist */
1002 0, /* tp_del */
1003 0, /* tp_version_tag */
1004 _PyGen_Finalize, /* tp_finalize */
1005};
1006
1007static void
1008coro_wrapper_dealloc(PyCoroWrapper *cw)
1009{
1010 _PyObject_GC_UNTRACK((PyObject *)cw);
1011 Py_CLEAR(cw->cw_coroutine);
1012 PyObject_GC_Del(cw);
1013}
1014
1015static PyObject *
1016coro_wrapper_iternext(PyCoroWrapper *cw)
1017{
Yury Selivanov77c96812016-02-13 17:59:05 -05001018 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001019}
1020
1021static PyObject *
1022coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1023{
Yury Selivanov77c96812016-02-13 17:59:05 -05001024 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001025}
1026
1027static PyObject *
1028coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1029{
1030 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1031}
1032
1033static PyObject *
1034coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1035{
1036 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1037}
1038
1039static int
1040coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1041{
1042 Py_VISIT((PyObject *)cw->cw_coroutine);
1043 return 0;
1044}
1045
1046static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001047 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1048 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1049 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001050 {NULL, NULL} /* Sentinel */
1051};
1052
1053PyTypeObject _PyCoroWrapper_Type = {
1054 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1055 "coroutine_wrapper",
1056 sizeof(PyCoroWrapper), /* tp_basicsize */
1057 0, /* tp_itemsize */
1058 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001059 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001060 0, /* tp_getattr */
1061 0, /* tp_setattr */
1062 0, /* tp_as_async */
1063 0, /* tp_repr */
1064 0, /* tp_as_number */
1065 0, /* tp_as_sequence */
1066 0, /* tp_as_mapping */
1067 0, /* tp_hash */
1068 0, /* tp_call */
1069 0, /* tp_str */
1070 PyObject_GenericGetAttr, /* tp_getattro */
1071 0, /* tp_setattro */
1072 0, /* tp_as_buffer */
1073 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1074 "A wrapper object implementing __await__ for coroutines.",
1075 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1076 0, /* tp_clear */
1077 0, /* tp_richcompare */
1078 0, /* tp_weaklistoffset */
1079 PyObject_SelfIter, /* tp_iter */
1080 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1081 coro_wrapper_methods, /* tp_methods */
1082 0, /* tp_members */
1083 0, /* tp_getset */
1084 0, /* tp_base */
1085 0, /* tp_dict */
1086 0, /* tp_descr_get */
1087 0, /* tp_descr_set */
1088 0, /* tp_dictoffset */
1089 0, /* tp_init */
1090 0, /* tp_alloc */
1091 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001092 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001093};
1094
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001095static PyObject *
1096compute_cr_origin(int origin_depth)
1097{
1098 PyFrameObject *frame = PyEval_GetFrame();
1099 /* First count how many frames we have */
1100 int frame_count = 0;
1101 for (; frame && frame_count < origin_depth; ++frame_count) {
1102 frame = frame->f_back;
1103 }
1104
1105 /* Now collect them */
1106 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001107 if (cr_origin == NULL) {
1108 return NULL;
1109 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001110 frame = PyEval_GetFrame();
1111 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001112 PyCodeObject *code = frame->f_code;
1113 PyObject *frameinfo = Py_BuildValue("OiO",
1114 code->co_filename,
1115 PyFrame_GetLineNumber(frame),
1116 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001117 if (!frameinfo) {
1118 Py_DECREF(cr_origin);
1119 return NULL;
1120 }
1121 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1122 frame = frame->f_back;
1123 }
1124
1125 return cr_origin;
1126}
1127
Yury Selivanov5376ba92015-06-22 12:19:30 -04001128PyObject *
1129PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1130{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001131 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1132 if (!coro) {
1133 return NULL;
1134 }
1135
Victor Stinner50b48572018-11-01 01:51:40 +01001136 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001137 int origin_depth = tstate->coroutine_origin_tracking_depth;
1138
1139 if (origin_depth == 0) {
1140 ((PyCoroObject *)coro)->cr_origin = NULL;
1141 } else {
1142 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001143 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001144 if (!cr_origin) {
1145 Py_DECREF(coro);
1146 return NULL;
1147 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001148 }
1149
1150 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001151}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001152
1153
Yury Selivanoveb636452016-09-08 22:01:51 -07001154/* ========= Asynchronous Generators ========= */
1155
1156
1157typedef enum {
1158 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1159 AWAITABLE_STATE_ITER, /* being iterated */
1160 AWAITABLE_STATE_CLOSED, /* closed */
1161} AwaitableState;
1162
1163
1164typedef struct {
1165 PyObject_HEAD
1166 PyAsyncGenObject *ags_gen;
1167
1168 /* Can be NULL, when in the __anext__() mode
1169 (equivalent of "asend(None)") */
1170 PyObject *ags_sendval;
1171
1172 AwaitableState ags_state;
1173} PyAsyncGenASend;
1174
1175
1176typedef struct {
1177 PyObject_HEAD
1178 PyAsyncGenObject *agt_gen;
1179
1180 /* Can be NULL, when in the "aclose()" mode
1181 (equivalent of "athrow(GeneratorExit)") */
1182 PyObject *agt_args;
1183
1184 AwaitableState agt_state;
1185} PyAsyncGenAThrow;
1186
1187
1188typedef struct {
1189 PyObject_HEAD
1190 PyObject *agw_val;
1191} _PyAsyncGenWrappedValue;
1192
1193
1194#ifndef _PyAsyncGen_MAXFREELIST
1195#define _PyAsyncGen_MAXFREELIST 80
1196#endif
1197
1198/* Freelists boost performance 6-10%; they also reduce memory
1199 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1200 are short-living objects that are instantiated for every
1201 __anext__ call.
1202*/
1203
1204static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1205static int ag_value_freelist_free = 0;
1206
1207static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1208static int ag_asend_freelist_free = 0;
1209
1210#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001211 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001212
1213#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001214 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001215
1216
1217static int
1218async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1219{
1220 Py_VISIT(gen->ag_finalizer);
1221 return gen_traverse((PyGenObject*)gen, visit, arg);
1222}
1223
1224
1225static PyObject *
1226async_gen_repr(PyAsyncGenObject *o)
1227{
1228 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1229 o->ag_qualname, o);
1230}
1231
1232
1233static int
1234async_gen_init_hooks(PyAsyncGenObject *o)
1235{
1236 PyThreadState *tstate;
1237 PyObject *finalizer;
1238 PyObject *firstiter;
1239
1240 if (o->ag_hooks_inited) {
1241 return 0;
1242 }
1243
1244 o->ag_hooks_inited = 1;
1245
Victor Stinner50b48572018-11-01 01:51:40 +01001246 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001247
1248 finalizer = tstate->async_gen_finalizer;
1249 if (finalizer) {
1250 Py_INCREF(finalizer);
1251 o->ag_finalizer = finalizer;
1252 }
1253
1254 firstiter = tstate->async_gen_firstiter;
1255 if (firstiter) {
1256 PyObject *res;
1257
1258 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001259 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001260 Py_DECREF(firstiter);
1261 if (res == NULL) {
1262 return 1;
1263 }
1264 Py_DECREF(res);
1265 }
1266
1267 return 0;
1268}
1269
1270
1271static PyObject *
1272async_gen_anext(PyAsyncGenObject *o)
1273{
1274 if (async_gen_init_hooks(o)) {
1275 return NULL;
1276 }
1277 return async_gen_asend_new(o, NULL);
1278}
1279
1280
1281static PyObject *
1282async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1283{
1284 if (async_gen_init_hooks(o)) {
1285 return NULL;
1286 }
1287 return async_gen_asend_new(o, arg);
1288}
1289
1290
1291static PyObject *
1292async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1293{
1294 if (async_gen_init_hooks(o)) {
1295 return NULL;
1296 }
1297 return async_gen_athrow_new(o, NULL);
1298}
1299
1300static PyObject *
1301async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1302{
1303 if (async_gen_init_hooks(o)) {
1304 return NULL;
1305 }
1306 return async_gen_athrow_new(o, args);
1307}
1308
1309
1310static PyGetSetDef async_gen_getsetlist[] = {
1311 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1312 PyDoc_STR("name of the async generator")},
1313 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1314 PyDoc_STR("qualified name of the async generator")},
1315 {"ag_await", (getter)coro_get_cr_await, NULL,
1316 PyDoc_STR("object being awaited on, or None")},
1317 {NULL} /* Sentinel */
1318};
1319
1320static PyMemberDef async_gen_memberlist[] = {
1321 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001322 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1323 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001324 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1325 {NULL} /* Sentinel */
1326};
1327
1328PyDoc_STRVAR(async_aclose_doc,
1329"aclose() -> raise GeneratorExit inside generator.");
1330
1331PyDoc_STRVAR(async_asend_doc,
1332"asend(v) -> send 'v' in generator.");
1333
1334PyDoc_STRVAR(async_athrow_doc,
1335"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1336
1337static PyMethodDef async_gen_methods[] = {
1338 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1339 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1340 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001341 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1342 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001343 {NULL, NULL} /* Sentinel */
1344};
1345
1346
1347static PyAsyncMethods async_gen_as_async = {
1348 0, /* am_await */
1349 PyObject_SelfIter, /* am_aiter */
1350 (unaryfunc)async_gen_anext /* am_anext */
1351};
1352
1353
1354PyTypeObject PyAsyncGen_Type = {
1355 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1356 "async_generator", /* tp_name */
1357 sizeof(PyAsyncGenObject), /* tp_basicsize */
1358 0, /* tp_itemsize */
1359 /* methods */
1360 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001361 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001362 0, /* tp_getattr */
1363 0, /* tp_setattr */
1364 &async_gen_as_async, /* tp_as_async */
1365 (reprfunc)async_gen_repr, /* tp_repr */
1366 0, /* tp_as_number */
1367 0, /* tp_as_sequence */
1368 0, /* tp_as_mapping */
1369 0, /* tp_hash */
1370 0, /* tp_call */
1371 0, /* tp_str */
1372 PyObject_GenericGetAttr, /* tp_getattro */
1373 0, /* tp_setattro */
1374 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001375 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001376 0, /* tp_doc */
1377 (traverseproc)async_gen_traverse, /* tp_traverse */
1378 0, /* tp_clear */
1379 0, /* tp_richcompare */
1380 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1381 0, /* tp_iter */
1382 0, /* tp_iternext */
1383 async_gen_methods, /* tp_methods */
1384 async_gen_memberlist, /* tp_members */
1385 async_gen_getsetlist, /* tp_getset */
1386 0, /* tp_base */
1387 0, /* tp_dict */
1388 0, /* tp_descr_get */
1389 0, /* tp_descr_set */
1390 0, /* tp_dictoffset */
1391 0, /* tp_init */
1392 0, /* tp_alloc */
1393 0, /* tp_new */
1394 0, /* tp_free */
1395 0, /* tp_is_gc */
1396 0, /* tp_bases */
1397 0, /* tp_mro */
1398 0, /* tp_cache */
1399 0, /* tp_subclasses */
1400 0, /* tp_weaklist */
1401 0, /* tp_del */
1402 0, /* tp_version_tag */
1403 _PyGen_Finalize, /* tp_finalize */
1404};
1405
1406
1407PyObject *
1408PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1409{
1410 PyAsyncGenObject *o;
1411 o = (PyAsyncGenObject *)gen_new_with_qualname(
1412 &PyAsyncGen_Type, f, name, qualname);
1413 if (o == NULL) {
1414 return NULL;
1415 }
1416 o->ag_finalizer = NULL;
1417 o->ag_closed = 0;
1418 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001419 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001420 return (PyObject*)o;
1421}
1422
1423
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001424void
1425_PyAsyncGen_ClearFreeLists(void)
Yury Selivanoveb636452016-09-08 22:01:51 -07001426{
Yury Selivanoveb636452016-09-08 22:01:51 -07001427 while (ag_value_freelist_free) {
1428 _PyAsyncGenWrappedValue *o;
1429 o = ag_value_freelist[--ag_value_freelist_free];
1430 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001431 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001432 }
1433
1434 while (ag_asend_freelist_free) {
1435 PyAsyncGenASend *o;
1436 o = ag_asend_freelist[--ag_asend_freelist_free];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001437 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001438 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001439 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001440}
1441
1442void
Victor Stinnerbed48172019-08-27 00:12:32 +02001443_PyAsyncGen_Fini(void)
Yury Selivanoveb636452016-09-08 22:01:51 -07001444{
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001445 _PyAsyncGen_ClearFreeLists();
Yury Selivanoveb636452016-09-08 22:01:51 -07001446}
1447
1448
1449static PyObject *
1450async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1451{
1452 if (result == NULL) {
1453 if (!PyErr_Occurred()) {
1454 PyErr_SetNone(PyExc_StopAsyncIteration);
1455 }
1456
1457 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1458 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1459 ) {
1460 gen->ag_closed = 1;
1461 }
1462
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001463 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001464 return NULL;
1465 }
1466
1467 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1468 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001469 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001470 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001471 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001472 return NULL;
1473 }
1474
1475 return result;
1476}
1477
1478
1479/* ---------- Async Generator ASend Awaitable ------------ */
1480
1481
1482static void
1483async_gen_asend_dealloc(PyAsyncGenASend *o)
1484{
Yury Selivanov29310c42016-11-08 19:46:22 -05001485 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001486 Py_CLEAR(o->ags_gen);
1487 Py_CLEAR(o->ags_sendval);
1488 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1489 assert(PyAsyncGenASend_CheckExact(o));
1490 ag_asend_freelist[ag_asend_freelist_free++] = o;
1491 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001492 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001493 }
1494}
1495
Yury Selivanov29310c42016-11-08 19:46:22 -05001496static int
1497async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1498{
1499 Py_VISIT(o->ags_gen);
1500 Py_VISIT(o->ags_sendval);
1501 return 0;
1502}
1503
Yury Selivanoveb636452016-09-08 22:01:51 -07001504
1505static PyObject *
1506async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1507{
1508 PyObject *result;
1509
1510 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001511 PyErr_SetString(
1512 PyExc_RuntimeError,
1513 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001514 return NULL;
1515 }
1516
1517 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001518 if (o->ags_gen->ag_running_async) {
1519 PyErr_SetString(
1520 PyExc_RuntimeError,
1521 "anext(): asynchronous generator is already running");
1522 return NULL;
1523 }
1524
Yury Selivanoveb636452016-09-08 22:01:51 -07001525 if (arg == NULL || arg == Py_None) {
1526 arg = o->ags_sendval;
1527 }
1528 o->ags_state = AWAITABLE_STATE_ITER;
1529 }
1530
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001531 o->ags_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001532 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1533 result = async_gen_unwrap_value(o->ags_gen, result);
1534
1535 if (result == NULL) {
1536 o->ags_state = AWAITABLE_STATE_CLOSED;
1537 }
1538
1539 return result;
1540}
1541
1542
1543static PyObject *
1544async_gen_asend_iternext(PyAsyncGenASend *o)
1545{
1546 return async_gen_asend_send(o, NULL);
1547}
1548
1549
1550static PyObject *
1551async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1552{
1553 PyObject *result;
1554
1555 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001556 PyErr_SetString(
1557 PyExc_RuntimeError,
1558 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001559 return NULL;
1560 }
1561
1562 result = gen_throw((PyGenObject*)o->ags_gen, args);
1563 result = async_gen_unwrap_value(o->ags_gen, result);
1564
1565 if (result == NULL) {
1566 o->ags_state = AWAITABLE_STATE_CLOSED;
1567 }
1568
1569 return result;
1570}
1571
1572
1573static PyObject *
1574async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1575{
1576 o->ags_state = AWAITABLE_STATE_CLOSED;
1577 Py_RETURN_NONE;
1578}
1579
1580
1581static PyMethodDef async_gen_asend_methods[] = {
1582 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1583 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1584 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1585 {NULL, NULL} /* Sentinel */
1586};
1587
1588
1589static PyAsyncMethods async_gen_asend_as_async = {
1590 PyObject_SelfIter, /* am_await */
1591 0, /* am_aiter */
1592 0 /* am_anext */
1593};
1594
1595
1596PyTypeObject _PyAsyncGenASend_Type = {
1597 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1598 "async_generator_asend", /* tp_name */
1599 sizeof(PyAsyncGenASend), /* tp_basicsize */
1600 0, /* tp_itemsize */
1601 /* methods */
1602 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001603 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001604 0, /* tp_getattr */
1605 0, /* tp_setattr */
1606 &async_gen_asend_as_async, /* tp_as_async */
1607 0, /* tp_repr */
1608 0, /* tp_as_number */
1609 0, /* tp_as_sequence */
1610 0, /* tp_as_mapping */
1611 0, /* tp_hash */
1612 0, /* tp_call */
1613 0, /* tp_str */
1614 PyObject_GenericGetAttr, /* tp_getattro */
1615 0, /* tp_setattro */
1616 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001617 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001618 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001619 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001620 0, /* tp_clear */
1621 0, /* tp_richcompare */
1622 0, /* tp_weaklistoffset */
1623 PyObject_SelfIter, /* tp_iter */
1624 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1625 async_gen_asend_methods, /* tp_methods */
1626 0, /* tp_members */
1627 0, /* tp_getset */
1628 0, /* tp_base */
1629 0, /* tp_dict */
1630 0, /* tp_descr_get */
1631 0, /* tp_descr_set */
1632 0, /* tp_dictoffset */
1633 0, /* tp_init */
1634 0, /* tp_alloc */
1635 0, /* tp_new */
1636};
1637
1638
1639static PyObject *
1640async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1641{
1642 PyAsyncGenASend *o;
1643 if (ag_asend_freelist_free) {
1644 ag_asend_freelist_free--;
1645 o = ag_asend_freelist[ag_asend_freelist_free];
1646 _Py_NewReference((PyObject *)o);
1647 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001648 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001649 if (o == NULL) {
1650 return NULL;
1651 }
1652 }
1653
1654 Py_INCREF(gen);
1655 o->ags_gen = gen;
1656
1657 Py_XINCREF(sendval);
1658 o->ags_sendval = sendval;
1659
1660 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001661
1662 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001663 return (PyObject*)o;
1664}
1665
1666
1667/* ---------- Async Generator Value Wrapper ------------ */
1668
1669
1670static void
1671async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1672{
Yury Selivanov29310c42016-11-08 19:46:22 -05001673 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001674 Py_CLEAR(o->agw_val);
1675 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1676 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1677 ag_value_freelist[ag_value_freelist_free++] = o;
1678 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001679 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001680 }
1681}
1682
1683
Yury Selivanov29310c42016-11-08 19:46:22 -05001684static int
1685async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1686 visitproc visit, void *arg)
1687{
1688 Py_VISIT(o->agw_val);
1689 return 0;
1690}
1691
1692
Yury Selivanoveb636452016-09-08 22:01:51 -07001693PyTypeObject _PyAsyncGenWrappedValue_Type = {
1694 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1695 "async_generator_wrapped_value", /* tp_name */
1696 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1697 0, /* tp_itemsize */
1698 /* methods */
1699 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001700 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001701 0, /* tp_getattr */
1702 0, /* tp_setattr */
1703 0, /* tp_as_async */
1704 0, /* tp_repr */
1705 0, /* tp_as_number */
1706 0, /* tp_as_sequence */
1707 0, /* tp_as_mapping */
1708 0, /* tp_hash */
1709 0, /* tp_call */
1710 0, /* tp_str */
1711 PyObject_GenericGetAttr, /* tp_getattro */
1712 0, /* tp_setattro */
1713 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001714 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001715 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001716 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001717 0, /* tp_clear */
1718 0, /* tp_richcompare */
1719 0, /* tp_weaklistoffset */
1720 0, /* tp_iter */
1721 0, /* tp_iternext */
1722 0, /* tp_methods */
1723 0, /* tp_members */
1724 0, /* tp_getset */
1725 0, /* tp_base */
1726 0, /* tp_dict */
1727 0, /* tp_descr_get */
1728 0, /* tp_descr_set */
1729 0, /* tp_dictoffset */
1730 0, /* tp_init */
1731 0, /* tp_alloc */
1732 0, /* tp_new */
1733};
1734
1735
1736PyObject *
1737_PyAsyncGenValueWrapperNew(PyObject *val)
1738{
1739 _PyAsyncGenWrappedValue *o;
1740 assert(val);
1741
1742 if (ag_value_freelist_free) {
1743 ag_value_freelist_free--;
1744 o = ag_value_freelist[ag_value_freelist_free];
1745 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1746 _Py_NewReference((PyObject*)o);
1747 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001748 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1749 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001750 if (o == NULL) {
1751 return NULL;
1752 }
1753 }
1754 o->agw_val = val;
1755 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001756 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001757 return (PyObject*)o;
1758}
1759
1760
1761/* ---------- Async Generator AThrow awaitable ------------ */
1762
1763
1764static void
1765async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1766{
Yury Selivanov29310c42016-11-08 19:46:22 -05001767 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001768 Py_CLEAR(o->agt_gen);
1769 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001770 PyObject_GC_Del(o);
1771}
1772
1773
1774static int
1775async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1776{
1777 Py_VISIT(o->agt_gen);
1778 Py_VISIT(o->agt_args);
1779 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001780}
1781
1782
1783static PyObject *
1784async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1785{
1786 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1787 PyFrameObject *f = gen->gi_frame;
1788 PyObject *retval;
1789
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001790 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001791 PyErr_SetString(
1792 PyExc_RuntimeError,
1793 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001794 return NULL;
1795 }
1796
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001797 if (f == NULL || f->f_stacktop == NULL) {
1798 o->agt_state = AWAITABLE_STATE_CLOSED;
1799 PyErr_SetNone(PyExc_StopIteration);
1800 return NULL;
1801 }
1802
Yury Selivanoveb636452016-09-08 22:01:51 -07001803 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001804 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001805 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001806 if (o->agt_args == NULL) {
1807 PyErr_SetString(
1808 PyExc_RuntimeError,
1809 "aclose(): asynchronous generator is already running");
1810 }
1811 else {
1812 PyErr_SetString(
1813 PyExc_RuntimeError,
1814 "athrow(): asynchronous generator is already running");
1815 }
1816 return NULL;
1817 }
1818
Yury Selivanoveb636452016-09-08 22:01:51 -07001819 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001820 o->agt_state = AWAITABLE_STATE_CLOSED;
1821 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001822 return NULL;
1823 }
1824
1825 if (arg != Py_None) {
1826 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1827 return NULL;
1828 }
1829
1830 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001831 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001832
1833 if (o->agt_args == NULL) {
1834 /* aclose() mode */
1835 o->agt_gen->ag_closed = 1;
1836
1837 retval = _gen_throw((PyGenObject *)gen,
1838 0, /* Do not close generator when
1839 PyExc_GeneratorExit is passed */
1840 PyExc_GeneratorExit, NULL, NULL);
1841
1842 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1843 Py_DECREF(retval);
1844 goto yield_close;
1845 }
1846 } else {
1847 PyObject *typ;
1848 PyObject *tb = NULL;
1849 PyObject *val = NULL;
1850
1851 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1852 &typ, &val, &tb)) {
1853 return NULL;
1854 }
1855
1856 retval = _gen_throw((PyGenObject *)gen,
1857 0, /* Do not close generator when
1858 PyExc_GeneratorExit is passed */
1859 typ, val, tb);
1860 retval = async_gen_unwrap_value(o->agt_gen, retval);
1861 }
1862 if (retval == NULL) {
1863 goto check_error;
1864 }
1865 return retval;
1866 }
1867
1868 assert(o->agt_state == AWAITABLE_STATE_ITER);
1869
1870 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1871 if (o->agt_args) {
1872 return async_gen_unwrap_value(o->agt_gen, retval);
1873 } else {
1874 /* aclose() mode */
1875 if (retval) {
1876 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1877 Py_DECREF(retval);
1878 goto yield_close;
1879 }
1880 else {
1881 return retval;
1882 }
1883 }
1884 else {
1885 goto check_error;
1886 }
1887 }
1888
1889yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001890 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001891 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001892 PyErr_SetString(
1893 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1894 return NULL;
1895
1896check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001897 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001898 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001899 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1900 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1901 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001902 if (o->agt_args == NULL) {
1903 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001904 StopAsyncIteration or GeneratorExit; just raise
1905 StopIteration, signalling that this 'aclose()' await
1906 is done.
1907 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001908 PyErr_Clear();
1909 PyErr_SetNone(PyExc_StopIteration);
1910 }
1911 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001912 return NULL;
1913}
1914
1915
1916static PyObject *
1917async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1918{
1919 PyObject *retval;
1920
Yury Selivanoveb636452016-09-08 22:01:51 -07001921 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001922 PyErr_SetString(
1923 PyExc_RuntimeError,
1924 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001925 return NULL;
1926 }
1927
1928 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1929 if (o->agt_args) {
1930 return async_gen_unwrap_value(o->agt_gen, retval);
1931 } else {
1932 /* aclose() mode */
1933 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001934 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001935 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001936 Py_DECREF(retval);
1937 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1938 return NULL;
1939 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08001940 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1941 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1942 {
1943 /* when aclose() is called we don't want to propagate
1944 StopAsyncIteration or GeneratorExit; just raise
1945 StopIteration, signalling that this 'aclose()' await
1946 is done.
1947 */
1948 PyErr_Clear();
1949 PyErr_SetNone(PyExc_StopIteration);
1950 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001951 return retval;
1952 }
1953}
1954
1955
1956static PyObject *
1957async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1958{
1959 return async_gen_athrow_send(o, Py_None);
1960}
1961
1962
1963static PyObject *
1964async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1965{
1966 o->agt_state = AWAITABLE_STATE_CLOSED;
1967 Py_RETURN_NONE;
1968}
1969
1970
1971static PyMethodDef async_gen_athrow_methods[] = {
1972 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1973 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1974 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1975 {NULL, NULL} /* Sentinel */
1976};
1977
1978
1979static PyAsyncMethods async_gen_athrow_as_async = {
1980 PyObject_SelfIter, /* am_await */
1981 0, /* am_aiter */
1982 0 /* am_anext */
1983};
1984
1985
1986PyTypeObject _PyAsyncGenAThrow_Type = {
1987 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1988 "async_generator_athrow", /* tp_name */
1989 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1990 0, /* tp_itemsize */
1991 /* methods */
1992 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001993 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001994 0, /* tp_getattr */
1995 0, /* tp_setattr */
1996 &async_gen_athrow_as_async, /* tp_as_async */
1997 0, /* tp_repr */
1998 0, /* tp_as_number */
1999 0, /* tp_as_sequence */
2000 0, /* tp_as_mapping */
2001 0, /* tp_hash */
2002 0, /* tp_call */
2003 0, /* tp_str */
2004 PyObject_GenericGetAttr, /* tp_getattro */
2005 0, /* tp_setattro */
2006 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002007 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002008 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002009 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002010 0, /* tp_clear */
2011 0, /* tp_richcompare */
2012 0, /* tp_weaklistoffset */
2013 PyObject_SelfIter, /* tp_iter */
2014 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2015 async_gen_athrow_methods, /* tp_methods */
2016 0, /* tp_members */
2017 0, /* tp_getset */
2018 0, /* tp_base */
2019 0, /* tp_dict */
2020 0, /* tp_descr_get */
2021 0, /* tp_descr_set */
2022 0, /* tp_dictoffset */
2023 0, /* tp_init */
2024 0, /* tp_alloc */
2025 0, /* tp_new */
2026};
2027
2028
2029static PyObject *
2030async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2031{
2032 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002033 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002034 if (o == NULL) {
2035 return NULL;
2036 }
2037 o->agt_gen = gen;
2038 o->agt_args = args;
2039 o->agt_state = AWAITABLE_STATE_INIT;
2040 Py_INCREF(gen);
2041 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002042 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002043 return (PyObject*)o;
2044}