blob: 5b253edfdcd0f634ac9e242bd2b462e53b4c70ca [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"
Victor Stinner4a21e572020-04-15 02:35:41 +02006#include "pycore_pystate.h" // _PyThreadState_GET()
Martin v. Löwise440e472004-06-01 15:22:42 +00007#include "frameobject.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02008#include "structmember.h" // PyMemberDef
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +000010
Yury Selivanoveb636452016-09-08 22:01:51 -070011static PyObject *gen_close(PyGenObject *, PyObject *);
12static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
13static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
14
Andy Lester7386a702020-02-13 22:42:56 -060015static const char *NON_INIT_CORO_MSG = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -070016 "just-started coroutine";
17
Andy Lester7386a702020-02-13 22:42:56 -060018static const char *ASYNC_GEN_IGNORED_EXIT_MSG =
Yury Selivanoveb636452016-09-08 22:01:51 -070019 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100020
Mark Shannonae3087c2017-10-22 22:41:51 +010021static inline int
22exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
23{
24 Py_VISIT(exc_state->exc_type);
25 Py_VISIT(exc_state->exc_value);
26 Py_VISIT(exc_state->exc_traceback);
27 return 0;
28}
29
Martin v. Löwise440e472004-06-01 15:22:42 +000030static int
31gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
32{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 Py_VISIT((PyObject *)gen->gi_frame);
34 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020035 Py_VISIT(gen->gi_name);
36 Py_VISIT(gen->gi_qualname);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080037 /* No need to visit cr_origin, because it's just tuples/str/int, so can't
38 participate in a reference cycle. */
Mark Shannonae3087c2017-10-22 22:41:51 +010039 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000040}
41
Antoine Pitrou58720d62013-08-05 23:26:40 +020042void
43_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020044{
45 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070046 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020047 PyObject *error_type, *error_value, *error_traceback;
48
Yury Selivanov2a2270d2018-01-29 14:31:47 -050049 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) {
Antoine Pitrou796564c2013-07-30 19:59:21 +020050 /* Generator isn't paused, so no need to close */
51 return;
Yury Selivanov2a2270d2018-01-29 14:31:47 -050052 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020053
Yury Selivanoveb636452016-09-08 22:01:51 -070054 if (PyAsyncGen_CheckExact(self)) {
55 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
56 PyObject *finalizer = agen->ag_finalizer;
57 if (finalizer && !agen->ag_closed) {
58 /* Save the current exception, if any. */
59 PyErr_Fetch(&error_type, &error_value, &error_traceback);
60
Petr Viktorinffd97532020-02-11 17:46:57 +010061 res = PyObject_CallOneArg(finalizer, self);
Yury Selivanoveb636452016-09-08 22:01:51 -070062
63 if (res == NULL) {
64 PyErr_WriteUnraisable(self);
65 } else {
66 Py_DECREF(res);
67 }
68 /* Restore the saved exception. */
69 PyErr_Restore(error_type, error_value, error_traceback);
70 return;
71 }
72 }
73
Antoine Pitrou796564c2013-07-30 19:59:21 +020074 /* Save the current exception, if any. */
75 PyErr_Fetch(&error_type, &error_value, &error_traceback);
76
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070077 /* If `gen` is a coroutine, and if it was never awaited on,
78 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070079 if (gen->gi_code != NULL &&
80 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
Yury Selivanov2a2270d2018-01-29 14:31:47 -050081 gen->gi_frame->f_lasti == -1)
82 {
83 _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070084 }
85 else {
86 res = gen_close(gen, NULL);
87 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020088
Benjamin Petersonb88db872016-09-07 08:46:59 -070089 if (res == NULL) {
Yury Selivanov2a2270d2018-01-29 14:31:47 -050090 if (PyErr_Occurred()) {
Benjamin Petersonb88db872016-09-07 08:46:59 -070091 PyErr_WriteUnraisable(self);
Yury Selivanov2a2270d2018-01-29 14:31:47 -050092 }
Benjamin Petersonb88db872016-09-07 08:46:59 -070093 }
94 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020095 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070096 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020097
98 /* Restore the saved exception. */
99 PyErr_Restore(error_type, error_value, error_traceback);
100}
101
Mark Shannonae3087c2017-10-22 22:41:51 +0100102static inline void
103exc_state_clear(_PyErr_StackItem *exc_state)
104{
105 PyObject *t, *v, *tb;
106 t = exc_state->exc_type;
107 v = exc_state->exc_value;
108 tb = exc_state->exc_traceback;
109 exc_state->exc_type = NULL;
110 exc_state->exc_value = NULL;
111 exc_state->exc_traceback = NULL;
112 Py_XDECREF(t);
113 Py_XDECREF(v);
114 Py_XDECREF(tb);
115}
116
Antoine Pitrou796564c2013-07-30 19:59:21 +0200117static void
Martin v. Löwise440e472004-06-01 15:22:42 +0000118gen_dealloc(PyGenObject *gen)
119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 if (gen->gi_weakreflist != NULL)
125 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000126
Antoine Pitrou93963562013-05-14 20:37:52 +0200127 _PyObject_GC_TRACK(self);
128
Antoine Pitrou796564c2013-07-30 19:59:21 +0200129 if (PyObject_CallFinalizerFromDealloc(self))
130 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200131
132 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700133 if (PyAsyncGen_CheckExact(gen)) {
134 /* We have to handle this case for asynchronous generators
135 right here, because this code has to be between UNTRACK
136 and GC_Del. */
137 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
138 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700139 if (gen->gi_frame != NULL) {
140 gen->gi_frame->f_gen = NULL;
141 Py_CLEAR(gen->gi_frame);
142 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800143 if (((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE) {
144 Py_CLEAR(((PyCoroObject *)gen)->cr_origin);
145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200147 Py_CLEAR(gen->gi_name);
148 Py_CLEAR(gen->gi_qualname);
Mark Shannonae3087c2017-10-22 22:41:51 +0100149 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000151}
152
153static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500154gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000155{
Victor Stinner50b48572018-11-01 01:51:40 +0100156 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200158 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000159
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500160 if (gen->gi_running) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200161 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700162 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400163 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700164 }
165 else if (PyAsyncGen_CheckExact(gen)) {
166 msg = "async generator already executing";
167 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400168 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500169 return NULL;
170 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200171 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500172 if (PyCoro_CheckExact(gen) && !closing) {
173 /* `gen` is an exhausted coroutine: raise an error,
174 except when called from gen_close(), which should
175 always be a silent method. */
176 PyErr_SetString(
177 PyExc_RuntimeError,
178 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700179 }
180 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500181 /* `gen` is an exhausted generator:
182 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700183 if (PyAsyncGen_CheckExact(gen)) {
184 PyErr_SetNone(PyExc_StopAsyncIteration);
185 }
186 else {
187 PyErr_SetNone(PyExc_StopIteration);
188 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 return NULL;
191 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000192
Antoine Pitrou93963562013-05-14 20:37:52 +0200193 if (f->f_lasti == -1) {
194 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200195 const char *msg = "can't send non-None value to a "
196 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700197 if (PyCoro_CheckExact(gen)) {
198 msg = NON_INIT_CORO_MSG;
199 }
200 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400201 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700202 "just-started async generator";
203 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400204 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200205 return NULL;
206 }
207 } else {
208 /* Push arg onto the frame's value stack */
209 result = arg ? arg : Py_None;
210 Py_INCREF(result);
211 *(f->f_stacktop++) = result;
212 }
213
214 /* Generators always return to their most recent caller, not
215 * necessarily their creator. */
216 Py_XINCREF(tstate->frame);
217 assert(f->f_back == NULL);
218 f->f_back = tstate->frame;
219
220 gen->gi_running = 1;
Mark Shannonae3087c2017-10-22 22:41:51 +0100221 gen->gi_exc_state.previous_item = tstate->exc_info;
222 tstate->exc_info = &gen->gi_exc_state;
Victor Stinnerb9e68122019-11-14 12:20:46 +0100223 result = _PyEval_EvalFrame(tstate, f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100224 tstate->exc_info = gen->gi_exc_state.previous_item;
225 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200226 gen->gi_running = 0;
227
228 /* Don't keep the reference to f_back any longer than necessary. It
229 * may keep a chain of frames alive or it could create a reference
230 * cycle. */
231 assert(f->f_back == tstate->frame);
232 Py_CLEAR(f->f_back);
233
234 /* If the generator just returned (as opposed to yielding), signal
235 * that the generator is exhausted. */
236 if (result && f->f_stacktop == NULL) {
237 if (result == Py_None) {
238 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700239 if (PyAsyncGen_CheckExact(gen)) {
240 PyErr_SetNone(PyExc_StopAsyncIteration);
241 }
242 else {
243 PyErr_SetNone(PyExc_StopIteration);
244 }
245 }
246 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700247 /* Async generators cannot return anything but None */
248 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200249 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200250 }
251 Py_CLEAR(result);
252 }
Yury Selivanov68333392015-05-22 11:16:47 -0400253 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500254 const char *msg = "generator raised StopIteration";
255 if (PyCoro_CheckExact(gen)) {
256 msg = "coroutine raised StopIteration";
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400257 }
Dong-hee Nad905df72020-02-14 02:37:17 +0900258 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500259 msg = "async generator raised StopIteration";
Yury Selivanov68333392015-05-22 11:16:47 -0400260 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500261 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
262
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400263 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500264 else if (!result && PyAsyncGen_CheckExact(gen) &&
Yury Selivanoveb636452016-09-08 22:01:51 -0700265 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
266 {
267 /* code in `gen` raised a StopAsyncIteration error:
268 raise a RuntimeError.
269 */
270 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300271 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700272 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200273
274 if (!result || f->f_stacktop == NULL) {
275 /* generator can't be rerun, so release the frame */
276 /* first clean reference cycle through stored exception traceback */
Mark Shannonae3087c2017-10-22 22:41:51 +0100277 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200278 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200279 gen->gi_frame = NULL;
280 Py_DECREF(f);
281 }
282
283 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000284}
285
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000286PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000287"send(arg) -> send 'arg' into generator,\n\
288return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000289
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500290PyObject *
291_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000292{
Yury Selivanov77c96812016-02-13 17:59:05 -0500293 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000294}
295
296PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400297"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000298
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000299/*
300 * This helper function is used by gen_close and gen_throw to
301 * close a subiterator being delegated to by yield-from.
302 */
303
Antoine Pitrou93963562013-05-14 20:37:52 +0200304static int
305gen_close_iter(PyObject *yf)
306{
307 PyObject *retval = NULL;
308 _Py_IDENTIFIER(close);
309
Yury Selivanoveb636452016-09-08 22:01:51 -0700310 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200311 retval = gen_close((PyGenObject *)yf, NULL);
312 if (retval == NULL)
313 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700314 }
315 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200316 PyObject *meth;
317 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
318 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700319 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200320 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700321 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200322 Py_DECREF(meth);
323 if (retval == NULL)
324 return -1;
325 }
326 }
327 Py_XDECREF(retval);
328 return 0;
329}
330
Yury Selivanovc724bae2016-03-02 11:30:46 -0500331PyObject *
332_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500333{
Antoine Pitrou93963562013-05-14 20:37:52 +0200334 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500335 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200336
337 if (f && f->f_stacktop) {
338 PyObject *bytecode = f->f_code->co_code;
339 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
340
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100341 if (f->f_lasti < 0) {
342 /* Return immediately if the frame didn't start yet. YIELD_FROM
343 always come after LOAD_CONST: a code object should not start
344 with YIELD_FROM */
345 assert(code[0] != YIELD_FROM);
346 return NULL;
347 }
348
Serhiy Storchakaab874002016-09-11 13:48:15 +0300349 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200350 return NULL;
351 yf = f->f_stacktop[-1];
352 Py_INCREF(yf);
353 }
354
355 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500356}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000357
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000358static PyObject *
359gen_close(PyGenObject *gen, PyObject *args)
360{
Antoine Pitrou93963562013-05-14 20:37:52 +0200361 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500362 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200363 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000364
Antoine Pitrou93963562013-05-14 20:37:52 +0200365 if (yf) {
366 gen->gi_running = 1;
367 err = gen_close_iter(yf);
368 gen->gi_running = 0;
369 Py_DECREF(yf);
370 }
371 if (err == 0)
372 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500373 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200374 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200375 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700376 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400377 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700378 } else if (PyAsyncGen_CheckExact(gen)) {
379 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
380 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200381 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400382 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 return NULL;
384 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200385 if (PyErr_ExceptionMatches(PyExc_StopIteration)
386 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
387 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200388 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200389 }
390 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000391}
392
Antoine Pitrou93963562013-05-14 20:37:52 +0200393
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000394PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000395"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
396return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000397
398static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700399_gen_throw(PyGenObject *gen, int close_on_genexit,
400 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000401{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500402 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000403 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000404
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000405 if (yf) {
406 PyObject *ret;
407 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700408 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
409 close_on_genexit
410 ) {
411 /* Asynchronous generators *should not* be closed right away.
412 We have to allow some awaits to work it through, hence the
413 `close_on_genexit` parameter here.
414 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500415 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200416 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500417 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000418 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000419 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500420 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000421 goto throw_here;
422 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700423 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
424 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500425 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700426 /* Close the generator that we are currently iterating with
427 'yield from' or awaiting on with 'await'. */
428 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
429 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500430 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000431 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700432 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200433 PyObject *meth;
434 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
435 Py_DECREF(yf);
436 return NULL;
437 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000439 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000440 goto throw_here;
441 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500442 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700443 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500444 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000445 Py_DECREF(meth);
446 }
447 Py_DECREF(yf);
448 if (!ret) {
449 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500450 /* Pop subiterator from stack */
451 ret = *(--gen->gi_frame->f_stacktop);
452 assert(ret == yf);
453 Py_DECREF(ret);
454 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100455 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300456 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000457 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500458 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000459 Py_DECREF(val);
460 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500461 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000462 }
463 }
464 return ret;
465 }
466
467throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 /* First, check the traceback argument, replacing None with
469 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400470 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400472 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 else if (tb != NULL && !PyTraceBack_Check(tb)) {
474 PyErr_SetString(PyExc_TypeError,
475 "throw() third argument must be a traceback object");
476 return NULL;
477 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 Py_INCREF(typ);
480 Py_XINCREF(val);
481 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000482
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400483 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 else if (PyExceptionInstance_Check(typ)) {
487 /* Raising an instance. The value should be a dummy. */
488 if (val && val != Py_None) {
489 PyErr_SetString(PyExc_TypeError,
490 "instance exception may not have a separate value");
491 goto failed_throw;
492 }
493 else {
494 /* Normalize to raise <class>, <instance> */
495 Py_XDECREF(val);
496 val = typ;
497 typ = PyExceptionInstance_Class(typ);
498 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200499
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400500 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200501 /* Returns NULL if there's no traceback */
502 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 }
504 }
505 else {
506 /* Not something you can raise. throw() fails. */
507 PyErr_Format(PyExc_TypeError,
508 "exceptions must be classes or instances "
509 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000510 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 goto failed_throw;
512 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 PyErr_Restore(typ, val, tb);
Victor Stinnerb0be6b32020-05-05 17:07:41 +0200515
516 _PyErr_StackItem *gi_exc_state = &gen->gi_exc_state;
517 if (gi_exc_state->exc_type != NULL && gi_exc_state->exc_type != Py_None) {
518 Py_INCREF(gi_exc_state->exc_type);
519 Py_XINCREF(gi_exc_state->exc_value);
520 Py_XINCREF(gi_exc_state->exc_traceback);
521 _PyErr_ChainExceptions(gi_exc_state->exc_type,
522 gi_exc_state->exc_value,
523 gi_exc_state->exc_traceback);
Chris Jerdonek02047262020-05-01 18:14:19 -0700524 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500525 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000526
527failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* Didn't use our arguments, so restore their original refcounts */
529 Py_DECREF(typ);
530 Py_XDECREF(val);
531 Py_XDECREF(tb);
532 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000533}
534
535
536static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700537gen_throw(PyGenObject *gen, PyObject *args)
538{
539 PyObject *typ;
540 PyObject *tb = NULL;
541 PyObject *val = NULL;
542
543 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
544 return NULL;
545 }
546
547 return _gen_throw(gen, 1, typ, val, tb);
548}
549
550
551static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000552gen_iternext(PyGenObject *gen)
553{
Yury Selivanov77c96812016-02-13 17:59:05 -0500554 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000555}
556
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000557/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200558 * Set StopIteration with specified value. Value can be arbitrary object
559 * or NULL.
560 *
561 * Returns 0 if StopIteration is set and -1 if any other exception is set.
562 */
563int
564_PyGen_SetStopIterationValue(PyObject *value)
565{
566 PyObject *e;
567
568 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400569 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200570 {
571 /* Delay exception instantiation if we can */
572 PyErr_SetObject(PyExc_StopIteration, value);
573 return 0;
574 }
575 /* Construct an exception instance manually with
Petr Viktorinffd97532020-02-11 17:46:57 +0100576 * PyObject_CallOneArg and pass it to PyErr_SetObject.
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200577 *
578 * We do this to handle a situation when "value" is a tuple, in which
579 * case PyErr_SetObject would set the value of StopIteration to
580 * the first element of the tuple.
581 *
582 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
583 */
Petr Viktorinffd97532020-02-11 17:46:57 +0100584 e = PyObject_CallOneArg(PyExc_StopIteration, value);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200585 if (e == NULL) {
586 return -1;
587 }
588 PyErr_SetObject(PyExc_StopIteration, e);
589 Py_DECREF(e);
590 return 0;
591}
592
593/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000594 * If StopIteration exception is set, fetches its 'value'
595 * attribute if any, otherwise sets pvalue to None.
596 *
597 * Returns 0 if no exception or StopIteration is set.
598 * If any other exception is set, returns -1 and leaves
599 * pvalue unchanged.
600 */
601
602int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200603_PyGen_FetchStopIterationValue(PyObject **pvalue)
604{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000605 PyObject *et, *ev, *tb;
606 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500607
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000608 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
609 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200610 if (ev) {
611 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300612 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200613 value = ((PyStopIterationObject *)ev)->value;
614 Py_INCREF(value);
615 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200616 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
617 /* Avoid normalisation and take ev as value.
618 *
619 * Normalization is required if the value is a tuple, in
620 * that case the value of StopIteration would be set to
621 * the first element of the tuple.
622 *
623 * (See _PyErr_CreateException code for details.)
624 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200625 value = ev;
626 } else {
627 /* normalisation required */
628 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300629 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200630 PyErr_Restore(et, ev, tb);
631 return -1;
632 }
633 value = ((PyStopIterationObject *)ev)->value;
634 Py_INCREF(value);
635 Py_DECREF(ev);
636 }
637 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000638 Py_XDECREF(et);
639 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000640 } else if (PyErr_Occurred()) {
641 return -1;
642 }
643 if (value == NULL) {
644 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100645 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000646 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000647 *pvalue = value;
648 return 0;
649}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000650
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000651static PyObject *
652gen_repr(PyGenObject *gen)
653{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400654 return PyUnicode_FromFormat("<generator object %S at %p>",
655 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000656}
657
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000658static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200659gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored))
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000660{
Victor Stinner40ee3012014-06-16 15:59:28 +0200661 Py_INCREF(op->gi_name);
662 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000663}
664
Victor Stinner40ee3012014-06-16 15:59:28 +0200665static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200666gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200667{
Victor Stinner40ee3012014-06-16 15:59:28 +0200668 /* Not legal to del gen.gi_name or to set it to anything
669 * other than a string object. */
670 if (value == NULL || !PyUnicode_Check(value)) {
671 PyErr_SetString(PyExc_TypeError,
672 "__name__ must be set to a string object");
673 return -1;
674 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200675 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300676 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200677 return 0;
678}
679
680static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200681gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200682{
683 Py_INCREF(op->gi_qualname);
684 return op->gi_qualname;
685}
686
687static int
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200688gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored))
Victor Stinner40ee3012014-06-16 15:59:28 +0200689{
Victor Stinner40ee3012014-06-16 15:59:28 +0200690 /* Not legal to del gen.__qualname__ or to set it to anything
691 * other than a string object. */
692 if (value == NULL || !PyUnicode_Check(value)) {
693 PyErr_SetString(PyExc_TypeError,
694 "__qualname__ must be set to a string object");
695 return -1;
696 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200697 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300698 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200699 return 0;
700}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000701
Yury Selivanove13f8f32015-07-03 00:23:30 -0400702static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200703gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400704{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500705 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400706 if (yf == NULL)
707 Py_RETURN_NONE;
708 return yf;
709}
710
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000711static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200712 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
713 PyDoc_STR("name of the generator")},
714 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
715 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400716 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
717 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200718 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000719};
720
Martin v. Löwise440e472004-06-01 15:22:42 +0000721static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200722 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
723 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
724 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000726};
727
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000728static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500729 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
731 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
732 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000733};
734
Martin v. Löwise440e472004-06-01 15:22:42 +0000735PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyVarObject_HEAD_INIT(&PyType_Type, 0)
737 "generator", /* tp_name */
738 sizeof(PyGenObject), /* tp_basicsize */
739 0, /* tp_itemsize */
740 /* methods */
741 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200742 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 0, /* tp_getattr */
744 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400745 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 (reprfunc)gen_repr, /* tp_repr */
747 0, /* tp_as_number */
748 0, /* tp_as_sequence */
749 0, /* tp_as_mapping */
750 0, /* tp_hash */
751 0, /* tp_call */
752 0, /* tp_str */
753 PyObject_GenericGetAttr, /* tp_getattro */
754 0, /* tp_setattro */
755 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200756 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 0, /* tp_doc */
758 (traverseproc)gen_traverse, /* tp_traverse */
759 0, /* tp_clear */
760 0, /* tp_richcompare */
761 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400762 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 (iternextfunc)gen_iternext, /* tp_iternext */
764 gen_methods, /* tp_methods */
765 gen_memberlist, /* tp_members */
766 gen_getsetlist, /* tp_getset */
767 0, /* tp_base */
768 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 0, /* tp_descr_get */
771 0, /* tp_descr_set */
772 0, /* tp_dictoffset */
773 0, /* tp_init */
774 0, /* tp_alloc */
775 0, /* tp_new */
776 0, /* tp_free */
777 0, /* tp_is_gc */
778 0, /* tp_bases */
779 0, /* tp_mro */
780 0, /* tp_cache */
781 0, /* tp_subclasses */
782 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200783 0, /* tp_del */
784 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200785 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000786};
787
Yury Selivanov5376ba92015-06-22 12:19:30 -0400788static PyObject *
789gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
790 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000791{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400792 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (gen == NULL) {
794 Py_DECREF(f);
795 return NULL;
796 }
797 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200798 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 Py_INCREF(f->f_code);
800 gen->gi_code = (PyObject *)(f->f_code);
801 gen->gi_running = 0;
802 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100803 gen->gi_exc_state.exc_type = NULL;
804 gen->gi_exc_state.exc_value = NULL;
805 gen->gi_exc_state.exc_traceback = NULL;
806 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200807 if (name != NULL)
808 gen->gi_name = name;
809 else
810 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
811 Py_INCREF(gen->gi_name);
812 if (qualname != NULL)
813 gen->gi_qualname = qualname;
814 else
815 gen->gi_qualname = gen->gi_name;
816 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 _PyObject_GC_TRACK(gen);
818 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000819}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820
Victor Stinner40ee3012014-06-16 15:59:28 +0200821PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400822PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
823{
824 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
825}
826
827PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200828PyGen_New(PyFrameObject *f)
829{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400830 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200831}
832
Yury Selivanov5376ba92015-06-22 12:19:30 -0400833/* Coroutine Object */
834
835typedef struct {
836 PyObject_HEAD
837 PyCoroObject *cw_coroutine;
838} PyCoroWrapper;
839
840static int
841gen_is_coroutine(PyObject *o)
842{
843 if (PyGen_CheckExact(o)) {
844 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
845 if (code->co_flags & CO_ITERABLE_COROUTINE) {
846 return 1;
847 }
848 }
849 return 0;
850}
851
Yury Selivanov75445082015-05-11 22:57:16 -0400852/*
853 * This helper function returns an awaitable for `o`:
854 * - `o` if `o` is a coroutine-object;
855 * - `type(o)->tp_as_async->am_await(o)`
856 *
857 * Raises a TypeError if it's not possible to return
858 * an awaitable and returns NULL.
859 */
860PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400861_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400862{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400863 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400864 PyTypeObject *ot;
865
Yury Selivanov5376ba92015-06-22 12:19:30 -0400866 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
867 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400868 Py_INCREF(o);
869 return o;
870 }
871
872 ot = Py_TYPE(o);
873 if (ot->tp_as_async != NULL) {
874 getter = ot->tp_as_async->am_await;
875 }
876 if (getter != NULL) {
877 PyObject *res = (*getter)(o);
878 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400879 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
880 /* __await__ must return an *iterator*, not
881 a coroutine or another awaitable (see PEP 492) */
882 PyErr_SetString(PyExc_TypeError,
883 "__await__() returned a coroutine");
884 Py_CLEAR(res);
885 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400886 PyErr_Format(PyExc_TypeError,
887 "__await__() returned non-iterator "
888 "of type '%.100s'",
889 Py_TYPE(res)->tp_name);
890 Py_CLEAR(res);
891 }
Yury Selivanov75445082015-05-11 22:57:16 -0400892 }
893 return res;
894 }
895
896 PyErr_Format(PyExc_TypeError,
897 "object %.100s can't be used in 'await' expression",
898 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400899 return NULL;
900}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400901
902static PyObject *
903coro_repr(PyCoroObject *coro)
904{
905 return PyUnicode_FromFormat("<coroutine object %S at %p>",
906 coro->cr_qualname, coro);
907}
908
909static PyObject *
910coro_await(PyCoroObject *coro)
911{
912 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
913 if (cw == NULL) {
914 return NULL;
915 }
916 Py_INCREF(coro);
917 cw->cw_coroutine = coro;
918 _PyObject_GC_TRACK(cw);
919 return (PyObject *)cw;
920}
921
Yury Selivanove13f8f32015-07-03 00:23:30 -0400922static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200923coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored))
Yury Selivanove13f8f32015-07-03 00:23:30 -0400924{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500925 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400926 if (yf == NULL)
927 Py_RETURN_NONE;
928 return yf;
929}
930
Yury Selivanov5376ba92015-06-22 12:19:30 -0400931static PyGetSetDef coro_getsetlist[] = {
932 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
933 PyDoc_STR("name of the coroutine")},
934 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
935 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400936 {"cr_await", (getter)coro_get_cr_await, NULL,
937 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400938 {NULL} /* Sentinel */
939};
940
941static PyMemberDef coro_memberlist[] = {
942 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
943 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
944 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800945 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400946 {NULL} /* Sentinel */
947};
948
949PyDoc_STRVAR(coro_send_doc,
950"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400951return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400952
953PyDoc_STRVAR(coro_throw_doc,
954"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400955return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400956
957PyDoc_STRVAR(coro_close_doc,
958"close() -> raise GeneratorExit inside coroutine.");
959
960static PyMethodDef coro_methods[] = {
961 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
962 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
963 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
964 {NULL, NULL} /* Sentinel */
965};
966
967static PyAsyncMethods coro_as_async = {
968 (unaryfunc)coro_await, /* am_await */
969 0, /* am_aiter */
970 0 /* am_anext */
971};
972
973PyTypeObject PyCoro_Type = {
974 PyVarObject_HEAD_INIT(&PyType_Type, 0)
975 "coroutine", /* tp_name */
976 sizeof(PyCoroObject), /* tp_basicsize */
977 0, /* tp_itemsize */
978 /* methods */
979 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200980 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400981 0, /* tp_getattr */
982 0, /* tp_setattr */
983 &coro_as_async, /* tp_as_async */
984 (reprfunc)coro_repr, /* tp_repr */
985 0, /* tp_as_number */
986 0, /* tp_as_sequence */
987 0, /* tp_as_mapping */
988 0, /* tp_hash */
989 0, /* tp_call */
990 0, /* tp_str */
991 PyObject_GenericGetAttr, /* tp_getattro */
992 0, /* tp_setattro */
993 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +0200994 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400995 0, /* tp_doc */
996 (traverseproc)gen_traverse, /* tp_traverse */
997 0, /* tp_clear */
998 0, /* tp_richcompare */
999 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1000 0, /* tp_iter */
1001 0, /* tp_iternext */
1002 coro_methods, /* tp_methods */
1003 coro_memberlist, /* tp_members */
1004 coro_getsetlist, /* tp_getset */
1005 0, /* tp_base */
1006 0, /* tp_dict */
1007 0, /* tp_descr_get */
1008 0, /* tp_descr_set */
1009 0, /* tp_dictoffset */
1010 0, /* tp_init */
1011 0, /* tp_alloc */
1012 0, /* tp_new */
1013 0, /* tp_free */
1014 0, /* tp_is_gc */
1015 0, /* tp_bases */
1016 0, /* tp_mro */
1017 0, /* tp_cache */
1018 0, /* tp_subclasses */
1019 0, /* tp_weaklist */
1020 0, /* tp_del */
1021 0, /* tp_version_tag */
1022 _PyGen_Finalize, /* tp_finalize */
1023};
1024
1025static void
1026coro_wrapper_dealloc(PyCoroWrapper *cw)
1027{
1028 _PyObject_GC_UNTRACK((PyObject *)cw);
1029 Py_CLEAR(cw->cw_coroutine);
1030 PyObject_GC_Del(cw);
1031}
1032
1033static PyObject *
1034coro_wrapper_iternext(PyCoroWrapper *cw)
1035{
Yury Selivanov77c96812016-02-13 17:59:05 -05001036 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001037}
1038
1039static PyObject *
1040coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1041{
Yury Selivanov77c96812016-02-13 17:59:05 -05001042 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001043}
1044
1045static PyObject *
1046coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1047{
1048 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1049}
1050
1051static PyObject *
1052coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1053{
1054 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1055}
1056
1057static int
1058coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1059{
1060 Py_VISIT((PyObject *)cw->cw_coroutine);
1061 return 0;
1062}
1063
1064static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001065 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1066 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1067 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001068 {NULL, NULL} /* Sentinel */
1069};
1070
1071PyTypeObject _PyCoroWrapper_Type = {
1072 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1073 "coroutine_wrapper",
1074 sizeof(PyCoroWrapper), /* tp_basicsize */
1075 0, /* tp_itemsize */
1076 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001077 0, /* tp_vectorcall_offset */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001078 0, /* tp_getattr */
1079 0, /* tp_setattr */
1080 0, /* tp_as_async */
1081 0, /* tp_repr */
1082 0, /* tp_as_number */
1083 0, /* tp_as_sequence */
1084 0, /* tp_as_mapping */
1085 0, /* tp_hash */
1086 0, /* tp_call */
1087 0, /* tp_str */
1088 PyObject_GenericGetAttr, /* tp_getattro */
1089 0, /* tp_setattro */
1090 0, /* tp_as_buffer */
1091 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1092 "A wrapper object implementing __await__ for coroutines.",
1093 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1094 0, /* tp_clear */
1095 0, /* tp_richcompare */
1096 0, /* tp_weaklistoffset */
1097 PyObject_SelfIter, /* tp_iter */
1098 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1099 coro_wrapper_methods, /* tp_methods */
1100 0, /* tp_members */
1101 0, /* tp_getset */
1102 0, /* tp_base */
1103 0, /* tp_dict */
1104 0, /* tp_descr_get */
1105 0, /* tp_descr_set */
1106 0, /* tp_dictoffset */
1107 0, /* tp_init */
1108 0, /* tp_alloc */
1109 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001110 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001111};
1112
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001113static PyObject *
1114compute_cr_origin(int origin_depth)
1115{
1116 PyFrameObject *frame = PyEval_GetFrame();
1117 /* First count how many frames we have */
1118 int frame_count = 0;
1119 for (; frame && frame_count < origin_depth; ++frame_count) {
1120 frame = frame->f_back;
1121 }
1122
1123 /* Now collect them */
1124 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001125 if (cr_origin == NULL) {
1126 return NULL;
1127 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001128 frame = PyEval_GetFrame();
1129 for (int i = 0; i < frame_count; ++i) {
Victor Stinner6d86a232020-04-29 00:56:58 +02001130 PyCodeObject *code = frame->f_code;
1131 PyObject *frameinfo = Py_BuildValue("OiO",
1132 code->co_filename,
1133 PyFrame_GetLineNumber(frame),
1134 code->co_name);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001135 if (!frameinfo) {
1136 Py_DECREF(cr_origin);
1137 return NULL;
1138 }
1139 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1140 frame = frame->f_back;
1141 }
1142
1143 return cr_origin;
1144}
1145
Yury Selivanov5376ba92015-06-22 12:19:30 -04001146PyObject *
1147PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1148{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001149 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1150 if (!coro) {
1151 return NULL;
1152 }
1153
Victor Stinner50b48572018-11-01 01:51:40 +01001154 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001155 int origin_depth = tstate->coroutine_origin_tracking_depth;
1156
1157 if (origin_depth == 0) {
1158 ((PyCoroObject *)coro)->cr_origin = NULL;
1159 } else {
1160 PyObject *cr_origin = compute_cr_origin(origin_depth);
Zackery Spytz062a57b2018-11-18 09:45:57 -07001161 ((PyCoroObject *)coro)->cr_origin = cr_origin;
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001162 if (!cr_origin) {
1163 Py_DECREF(coro);
1164 return NULL;
1165 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001166 }
1167
1168 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001169}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001170
1171
Yury Selivanoveb636452016-09-08 22:01:51 -07001172/* ========= Asynchronous Generators ========= */
1173
1174
1175typedef enum {
1176 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1177 AWAITABLE_STATE_ITER, /* being iterated */
1178 AWAITABLE_STATE_CLOSED, /* closed */
1179} AwaitableState;
1180
1181
1182typedef struct {
1183 PyObject_HEAD
1184 PyAsyncGenObject *ags_gen;
1185
1186 /* Can be NULL, when in the __anext__() mode
1187 (equivalent of "asend(None)") */
1188 PyObject *ags_sendval;
1189
1190 AwaitableState ags_state;
1191} PyAsyncGenASend;
1192
1193
1194typedef struct {
1195 PyObject_HEAD
1196 PyAsyncGenObject *agt_gen;
1197
1198 /* Can be NULL, when in the "aclose()" mode
1199 (equivalent of "athrow(GeneratorExit)") */
1200 PyObject *agt_args;
1201
1202 AwaitableState agt_state;
1203} PyAsyncGenAThrow;
1204
1205
1206typedef struct {
1207 PyObject_HEAD
1208 PyObject *agw_val;
1209} _PyAsyncGenWrappedValue;
1210
1211
1212#ifndef _PyAsyncGen_MAXFREELIST
1213#define _PyAsyncGen_MAXFREELIST 80
1214#endif
1215
1216/* Freelists boost performance 6-10%; they also reduce memory
1217 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1218 are short-living objects that are instantiated for every
1219 __anext__ call.
1220*/
1221
1222static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1223static int ag_value_freelist_free = 0;
1224
1225static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1226static int ag_asend_freelist_free = 0;
1227
1228#define _PyAsyncGenWrappedValue_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001229 Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001230
1231#define PyAsyncGenASend_CheckExact(o) \
Andy Lesterdffe4c02020-03-04 07:15:20 -06001232 Py_IS_TYPE(o, &_PyAsyncGenASend_Type)
Yury Selivanoveb636452016-09-08 22:01:51 -07001233
1234
1235static int
1236async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1237{
1238 Py_VISIT(gen->ag_finalizer);
1239 return gen_traverse((PyGenObject*)gen, visit, arg);
1240}
1241
1242
1243static PyObject *
1244async_gen_repr(PyAsyncGenObject *o)
1245{
1246 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1247 o->ag_qualname, o);
1248}
1249
1250
1251static int
1252async_gen_init_hooks(PyAsyncGenObject *o)
1253{
1254 PyThreadState *tstate;
1255 PyObject *finalizer;
1256 PyObject *firstiter;
1257
1258 if (o->ag_hooks_inited) {
1259 return 0;
1260 }
1261
1262 o->ag_hooks_inited = 1;
1263
Victor Stinner50b48572018-11-01 01:51:40 +01001264 tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001265
1266 finalizer = tstate->async_gen_finalizer;
1267 if (finalizer) {
1268 Py_INCREF(finalizer);
1269 o->ag_finalizer = finalizer;
1270 }
1271
1272 firstiter = tstate->async_gen_firstiter;
1273 if (firstiter) {
1274 PyObject *res;
1275
1276 Py_INCREF(firstiter);
Petr Viktorinffd97532020-02-11 17:46:57 +01001277 res = PyObject_CallOneArg(firstiter, (PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001278 Py_DECREF(firstiter);
1279 if (res == NULL) {
1280 return 1;
1281 }
1282 Py_DECREF(res);
1283 }
1284
1285 return 0;
1286}
1287
1288
1289static PyObject *
1290async_gen_anext(PyAsyncGenObject *o)
1291{
1292 if (async_gen_init_hooks(o)) {
1293 return NULL;
1294 }
1295 return async_gen_asend_new(o, NULL);
1296}
1297
1298
1299static PyObject *
1300async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1301{
1302 if (async_gen_init_hooks(o)) {
1303 return NULL;
1304 }
1305 return async_gen_asend_new(o, arg);
1306}
1307
1308
1309static PyObject *
1310async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1311{
1312 if (async_gen_init_hooks(o)) {
1313 return NULL;
1314 }
1315 return async_gen_athrow_new(o, NULL);
1316}
1317
1318static PyObject *
1319async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1320{
1321 if (async_gen_init_hooks(o)) {
1322 return NULL;
1323 }
1324 return async_gen_athrow_new(o, args);
1325}
1326
1327
1328static PyGetSetDef async_gen_getsetlist[] = {
1329 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1330 PyDoc_STR("name of the async generator")},
1331 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1332 PyDoc_STR("qualified name of the async generator")},
1333 {"ag_await", (getter)coro_get_cr_await, NULL,
1334 PyDoc_STR("object being awaited on, or None")},
1335 {NULL} /* Sentinel */
1336};
1337
1338static PyMemberDef async_gen_memberlist[] = {
1339 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001340 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1341 READONLY},
Yury Selivanoveb636452016-09-08 22:01:51 -07001342 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1343 {NULL} /* Sentinel */
1344};
1345
1346PyDoc_STRVAR(async_aclose_doc,
1347"aclose() -> raise GeneratorExit inside generator.");
1348
1349PyDoc_STRVAR(async_asend_doc,
1350"asend(v) -> send 'v' in generator.");
1351
1352PyDoc_STRVAR(async_athrow_doc,
1353"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1354
1355static PyMethodDef async_gen_methods[] = {
1356 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1357 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1358 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
Ethan Smith7c4185d2020-04-09 21:25:53 -07001359 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1360 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Yury Selivanoveb636452016-09-08 22:01:51 -07001361 {NULL, NULL} /* Sentinel */
1362};
1363
1364
1365static PyAsyncMethods async_gen_as_async = {
1366 0, /* am_await */
1367 PyObject_SelfIter, /* am_aiter */
1368 (unaryfunc)async_gen_anext /* am_anext */
1369};
1370
1371
1372PyTypeObject PyAsyncGen_Type = {
1373 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1374 "async_generator", /* tp_name */
1375 sizeof(PyAsyncGenObject), /* tp_basicsize */
1376 0, /* tp_itemsize */
1377 /* methods */
1378 (destructor)gen_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001379 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001380 0, /* tp_getattr */
1381 0, /* tp_setattr */
1382 &async_gen_as_async, /* tp_as_async */
1383 (reprfunc)async_gen_repr, /* tp_repr */
1384 0, /* tp_as_number */
1385 0, /* tp_as_sequence */
1386 0, /* tp_as_mapping */
1387 0, /* tp_hash */
1388 0, /* tp_call */
1389 0, /* tp_str */
1390 PyObject_GenericGetAttr, /* tp_getattro */
1391 0, /* tp_setattro */
1392 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +02001393 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001394 0, /* tp_doc */
1395 (traverseproc)async_gen_traverse, /* tp_traverse */
1396 0, /* tp_clear */
1397 0, /* tp_richcompare */
1398 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1399 0, /* tp_iter */
1400 0, /* tp_iternext */
1401 async_gen_methods, /* tp_methods */
1402 async_gen_memberlist, /* tp_members */
1403 async_gen_getsetlist, /* tp_getset */
1404 0, /* tp_base */
1405 0, /* tp_dict */
1406 0, /* tp_descr_get */
1407 0, /* tp_descr_set */
1408 0, /* tp_dictoffset */
1409 0, /* tp_init */
1410 0, /* tp_alloc */
1411 0, /* tp_new */
1412 0, /* tp_free */
1413 0, /* tp_is_gc */
1414 0, /* tp_bases */
1415 0, /* tp_mro */
1416 0, /* tp_cache */
1417 0, /* tp_subclasses */
1418 0, /* tp_weaklist */
1419 0, /* tp_del */
1420 0, /* tp_version_tag */
1421 _PyGen_Finalize, /* tp_finalize */
1422};
1423
1424
1425PyObject *
1426PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1427{
1428 PyAsyncGenObject *o;
1429 o = (PyAsyncGenObject *)gen_new_with_qualname(
1430 &PyAsyncGen_Type, f, name, qualname);
1431 if (o == NULL) {
1432 return NULL;
1433 }
1434 o->ag_finalizer = NULL;
1435 o->ag_closed = 0;
1436 o->ag_hooks_inited = 0;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001437 o->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001438 return (PyObject*)o;
1439}
1440
1441
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001442void
1443_PyAsyncGen_ClearFreeLists(void)
Yury Selivanoveb636452016-09-08 22:01:51 -07001444{
Yury Selivanoveb636452016-09-08 22:01:51 -07001445 while (ag_value_freelist_free) {
1446 _PyAsyncGenWrappedValue *o;
1447 o = ag_value_freelist[--ag_value_freelist_free];
1448 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001449 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001450 }
1451
1452 while (ag_asend_freelist_free) {
1453 PyAsyncGenASend *o;
1454 o = ag_asend_freelist[--ag_asend_freelist_free];
Andy Lesterdffe4c02020-03-04 07:15:20 -06001455 assert(Py_IS_TYPE(o, &_PyAsyncGenASend_Type));
Yury Selivanov29310c42016-11-08 19:46:22 -05001456 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001457 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001458}
1459
1460void
Victor Stinnerbed48172019-08-27 00:12:32 +02001461_PyAsyncGen_Fini(void)
Yury Selivanoveb636452016-09-08 22:01:51 -07001462{
Victor Stinnerae00a5a2020-04-29 02:29:20 +02001463 _PyAsyncGen_ClearFreeLists();
Yury Selivanoveb636452016-09-08 22:01:51 -07001464}
1465
1466
1467static PyObject *
1468async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1469{
1470 if (result == NULL) {
1471 if (!PyErr_Occurred()) {
1472 PyErr_SetNone(PyExc_StopAsyncIteration);
1473 }
1474
1475 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1476 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1477 ) {
1478 gen->ag_closed = 1;
1479 }
1480
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001481 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001482 return NULL;
1483 }
1484
1485 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1486 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001487 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001488 Py_DECREF(result);
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001489 gen->ag_running_async = 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001490 return NULL;
1491 }
1492
1493 return result;
1494}
1495
1496
1497/* ---------- Async Generator ASend Awaitable ------------ */
1498
1499
1500static void
1501async_gen_asend_dealloc(PyAsyncGenASend *o)
1502{
Yury Selivanov29310c42016-11-08 19:46:22 -05001503 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001504 Py_CLEAR(o->ags_gen);
1505 Py_CLEAR(o->ags_sendval);
1506 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1507 assert(PyAsyncGenASend_CheckExact(o));
1508 ag_asend_freelist[ag_asend_freelist_free++] = o;
1509 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001510 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001511 }
1512}
1513
Yury Selivanov29310c42016-11-08 19:46:22 -05001514static int
1515async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1516{
1517 Py_VISIT(o->ags_gen);
1518 Py_VISIT(o->ags_sendval);
1519 return 0;
1520}
1521
Yury Selivanoveb636452016-09-08 22:01:51 -07001522
1523static PyObject *
1524async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1525{
1526 PyObject *result;
1527
1528 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001529 PyErr_SetString(
1530 PyExc_RuntimeError,
1531 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001532 return NULL;
1533 }
1534
1535 if (o->ags_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001536 if (o->ags_gen->ag_running_async) {
1537 PyErr_SetString(
1538 PyExc_RuntimeError,
1539 "anext(): asynchronous generator is already running");
1540 return NULL;
1541 }
1542
Yury Selivanoveb636452016-09-08 22:01:51 -07001543 if (arg == NULL || arg == Py_None) {
1544 arg = o->ags_sendval;
1545 }
1546 o->ags_state = AWAITABLE_STATE_ITER;
1547 }
1548
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001549 o->ags_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001550 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1551 result = async_gen_unwrap_value(o->ags_gen, result);
1552
1553 if (result == NULL) {
1554 o->ags_state = AWAITABLE_STATE_CLOSED;
1555 }
1556
1557 return result;
1558}
1559
1560
1561static PyObject *
1562async_gen_asend_iternext(PyAsyncGenASend *o)
1563{
1564 return async_gen_asend_send(o, NULL);
1565}
1566
1567
1568static PyObject *
1569async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1570{
1571 PyObject *result;
1572
1573 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001574 PyErr_SetString(
1575 PyExc_RuntimeError,
1576 "cannot reuse already awaited __anext__()/asend()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001577 return NULL;
1578 }
1579
1580 result = gen_throw((PyGenObject*)o->ags_gen, args);
1581 result = async_gen_unwrap_value(o->ags_gen, result);
1582
1583 if (result == NULL) {
1584 o->ags_state = AWAITABLE_STATE_CLOSED;
1585 }
1586
1587 return result;
1588}
1589
1590
1591static PyObject *
1592async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1593{
1594 o->ags_state = AWAITABLE_STATE_CLOSED;
1595 Py_RETURN_NONE;
1596}
1597
1598
1599static PyMethodDef async_gen_asend_methods[] = {
1600 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1601 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1602 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1603 {NULL, NULL} /* Sentinel */
1604};
1605
1606
1607static PyAsyncMethods async_gen_asend_as_async = {
1608 PyObject_SelfIter, /* am_await */
1609 0, /* am_aiter */
1610 0 /* am_anext */
1611};
1612
1613
1614PyTypeObject _PyAsyncGenASend_Type = {
1615 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1616 "async_generator_asend", /* tp_name */
1617 sizeof(PyAsyncGenASend), /* tp_basicsize */
1618 0, /* tp_itemsize */
1619 /* methods */
1620 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001621 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001622 0, /* tp_getattr */
1623 0, /* tp_setattr */
1624 &async_gen_asend_as_async, /* tp_as_async */
1625 0, /* tp_repr */
1626 0, /* tp_as_number */
1627 0, /* tp_as_sequence */
1628 0, /* tp_as_mapping */
1629 0, /* tp_hash */
1630 0, /* tp_call */
1631 0, /* tp_str */
1632 PyObject_GenericGetAttr, /* tp_getattro */
1633 0, /* tp_setattro */
1634 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001635 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001636 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001637 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001638 0, /* tp_clear */
1639 0, /* tp_richcompare */
1640 0, /* tp_weaklistoffset */
1641 PyObject_SelfIter, /* tp_iter */
1642 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1643 async_gen_asend_methods, /* tp_methods */
1644 0, /* tp_members */
1645 0, /* tp_getset */
1646 0, /* tp_base */
1647 0, /* tp_dict */
1648 0, /* tp_descr_get */
1649 0, /* tp_descr_set */
1650 0, /* tp_dictoffset */
1651 0, /* tp_init */
1652 0, /* tp_alloc */
1653 0, /* tp_new */
1654};
1655
1656
1657static PyObject *
1658async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1659{
1660 PyAsyncGenASend *o;
1661 if (ag_asend_freelist_free) {
1662 ag_asend_freelist_free--;
1663 o = ag_asend_freelist[ag_asend_freelist_free];
1664 _Py_NewReference((PyObject *)o);
1665 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001666 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001667 if (o == NULL) {
1668 return NULL;
1669 }
1670 }
1671
1672 Py_INCREF(gen);
1673 o->ags_gen = gen;
1674
1675 Py_XINCREF(sendval);
1676 o->ags_sendval = sendval;
1677
1678 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001679
1680 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001681 return (PyObject*)o;
1682}
1683
1684
1685/* ---------- Async Generator Value Wrapper ------------ */
1686
1687
1688static void
1689async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1690{
Yury Selivanov29310c42016-11-08 19:46:22 -05001691 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001692 Py_CLEAR(o->agw_val);
1693 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1694 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1695 ag_value_freelist[ag_value_freelist_free++] = o;
1696 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001697 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001698 }
1699}
1700
1701
Yury Selivanov29310c42016-11-08 19:46:22 -05001702static int
1703async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1704 visitproc visit, void *arg)
1705{
1706 Py_VISIT(o->agw_val);
1707 return 0;
1708}
1709
1710
Yury Selivanoveb636452016-09-08 22:01:51 -07001711PyTypeObject _PyAsyncGenWrappedValue_Type = {
1712 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1713 "async_generator_wrapped_value", /* tp_name */
1714 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1715 0, /* tp_itemsize */
1716 /* methods */
1717 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001718 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07001719 0, /* tp_getattr */
1720 0, /* tp_setattr */
1721 0, /* tp_as_async */
1722 0, /* tp_repr */
1723 0, /* tp_as_number */
1724 0, /* tp_as_sequence */
1725 0, /* tp_as_mapping */
1726 0, /* tp_hash */
1727 0, /* tp_call */
1728 0, /* tp_str */
1729 PyObject_GenericGetAttr, /* tp_getattro */
1730 0, /* tp_setattro */
1731 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001732 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001733 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001734 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001735 0, /* tp_clear */
1736 0, /* tp_richcompare */
1737 0, /* tp_weaklistoffset */
1738 0, /* tp_iter */
1739 0, /* tp_iternext */
1740 0, /* tp_methods */
1741 0, /* tp_members */
1742 0, /* tp_getset */
1743 0, /* tp_base */
1744 0, /* tp_dict */
1745 0, /* tp_descr_get */
1746 0, /* tp_descr_set */
1747 0, /* tp_dictoffset */
1748 0, /* tp_init */
1749 0, /* tp_alloc */
1750 0, /* tp_new */
1751};
1752
1753
1754PyObject *
1755_PyAsyncGenValueWrapperNew(PyObject *val)
1756{
1757 _PyAsyncGenWrappedValue *o;
1758 assert(val);
1759
1760 if (ag_value_freelist_free) {
1761 ag_value_freelist_free--;
1762 o = ag_value_freelist[ag_value_freelist_free];
1763 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1764 _Py_NewReference((PyObject*)o);
1765 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001766 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1767 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001768 if (o == NULL) {
1769 return NULL;
1770 }
1771 }
1772 o->agw_val = val;
1773 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001774 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001775 return (PyObject*)o;
1776}
1777
1778
1779/* ---------- Async Generator AThrow awaitable ------------ */
1780
1781
1782static void
1783async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1784{
Yury Selivanov29310c42016-11-08 19:46:22 -05001785 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001786 Py_CLEAR(o->agt_gen);
1787 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001788 PyObject_GC_Del(o);
1789}
1790
1791
1792static int
1793async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1794{
1795 Py_VISIT(o->agt_gen);
1796 Py_VISIT(o->agt_args);
1797 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001798}
1799
1800
1801static PyObject *
1802async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1803{
1804 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1805 PyFrameObject *f = gen->gi_frame;
1806 PyObject *retval;
1807
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001808 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001809 PyErr_SetString(
1810 PyExc_RuntimeError,
1811 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001812 return NULL;
1813 }
1814
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001815 if (f == NULL || f->f_stacktop == NULL) {
1816 o->agt_state = AWAITABLE_STATE_CLOSED;
1817 PyErr_SetNone(PyExc_StopIteration);
1818 return NULL;
1819 }
1820
Yury Selivanoveb636452016-09-08 22:01:51 -07001821 if (o->agt_state == AWAITABLE_STATE_INIT) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001822 if (o->agt_gen->ag_running_async) {
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001823 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001824 if (o->agt_args == NULL) {
1825 PyErr_SetString(
1826 PyExc_RuntimeError,
1827 "aclose(): asynchronous generator is already running");
1828 }
1829 else {
1830 PyErr_SetString(
1831 PyExc_RuntimeError,
1832 "athrow(): asynchronous generator is already running");
1833 }
1834 return NULL;
1835 }
1836
Yury Selivanoveb636452016-09-08 22:01:51 -07001837 if (o->agt_gen->ag_closed) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001838 o->agt_state = AWAITABLE_STATE_CLOSED;
1839 PyErr_SetNone(PyExc_StopAsyncIteration);
Yury Selivanoveb636452016-09-08 22:01:51 -07001840 return NULL;
1841 }
1842
1843 if (arg != Py_None) {
1844 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1845 return NULL;
1846 }
1847
1848 o->agt_state = AWAITABLE_STATE_ITER;
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001849 o->agt_gen->ag_running_async = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -07001850
1851 if (o->agt_args == NULL) {
1852 /* aclose() mode */
1853 o->agt_gen->ag_closed = 1;
1854
1855 retval = _gen_throw((PyGenObject *)gen,
1856 0, /* Do not close generator when
1857 PyExc_GeneratorExit is passed */
1858 PyExc_GeneratorExit, NULL, NULL);
1859
1860 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1861 Py_DECREF(retval);
1862 goto yield_close;
1863 }
1864 } else {
1865 PyObject *typ;
1866 PyObject *tb = NULL;
1867 PyObject *val = NULL;
1868
1869 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1870 &typ, &val, &tb)) {
1871 return NULL;
1872 }
1873
1874 retval = _gen_throw((PyGenObject *)gen,
1875 0, /* Do not close generator when
1876 PyExc_GeneratorExit is passed */
1877 typ, val, tb);
1878 retval = async_gen_unwrap_value(o->agt_gen, retval);
1879 }
1880 if (retval == NULL) {
1881 goto check_error;
1882 }
1883 return retval;
1884 }
1885
1886 assert(o->agt_state == AWAITABLE_STATE_ITER);
1887
1888 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1889 if (o->agt_args) {
1890 return async_gen_unwrap_value(o->agt_gen, retval);
1891 } else {
1892 /* aclose() mode */
1893 if (retval) {
1894 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1895 Py_DECREF(retval);
1896 goto yield_close;
1897 }
1898 else {
1899 return retval;
1900 }
1901 }
1902 else {
1903 goto check_error;
1904 }
1905 }
1906
1907yield_close:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001908 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001909 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001910 PyErr_SetString(
1911 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1912 return NULL;
1913
1914check_error:
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001915 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001916 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanov52698c72018-06-07 20:31:26 -04001917 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1918 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1919 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001920 if (o->agt_args == NULL) {
1921 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001922 StopAsyncIteration or GeneratorExit; just raise
1923 StopIteration, signalling that this 'aclose()' await
1924 is done.
1925 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001926 PyErr_Clear();
1927 PyErr_SetNone(PyExc_StopIteration);
1928 }
1929 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001930 return NULL;
1931}
1932
1933
1934static PyObject *
1935async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1936{
1937 PyObject *retval;
1938
Yury Selivanoveb636452016-09-08 22:01:51 -07001939 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
Andrew Svetlova96e06d2020-01-21 00:49:30 +02001940 PyErr_SetString(
1941 PyExc_RuntimeError,
1942 "cannot reuse already awaited aclose()/athrow()");
Yury Selivanoveb636452016-09-08 22:01:51 -07001943 return NULL;
1944 }
1945
1946 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1947 if (o->agt_args) {
1948 return async_gen_unwrap_value(o->agt_gen, retval);
1949 } else {
1950 /* aclose() mode */
1951 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
Yury Selivanovfc4a0442019-09-29 22:59:11 -07001952 o->agt_gen->ag_running_async = 0;
Nathaniel J. Smith925dc7f2020-02-13 00:15:38 -08001953 o->agt_state = AWAITABLE_STATE_CLOSED;
Yury Selivanoveb636452016-09-08 22:01:51 -07001954 Py_DECREF(retval);
1955 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1956 return NULL;
1957 }
Vincent Michel8e0de2a2019-11-19 05:53:52 -08001958 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1959 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1960 {
1961 /* when aclose() is called we don't want to propagate
1962 StopAsyncIteration or GeneratorExit; just raise
1963 StopIteration, signalling that this 'aclose()' await
1964 is done.
1965 */
1966 PyErr_Clear();
1967 PyErr_SetNone(PyExc_StopIteration);
1968 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001969 return retval;
1970 }
1971}
1972
1973
1974static PyObject *
1975async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1976{
1977 return async_gen_athrow_send(o, Py_None);
1978}
1979
1980
1981static PyObject *
1982async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1983{
1984 o->agt_state = AWAITABLE_STATE_CLOSED;
1985 Py_RETURN_NONE;
1986}
1987
1988
1989static PyMethodDef async_gen_athrow_methods[] = {
1990 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1991 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1992 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1993 {NULL, NULL} /* Sentinel */
1994};
1995
1996
1997static PyAsyncMethods async_gen_athrow_as_async = {
1998 PyObject_SelfIter, /* am_await */
1999 0, /* am_aiter */
2000 0 /* am_anext */
2001};
2002
2003
2004PyTypeObject _PyAsyncGenAThrow_Type = {
2005 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2006 "async_generator_athrow", /* tp_name */
2007 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
2008 0, /* tp_itemsize */
2009 /* methods */
2010 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002011 0, /* tp_vectorcall_offset */
Yury Selivanoveb636452016-09-08 22:01:51 -07002012 0, /* tp_getattr */
2013 0, /* tp_setattr */
2014 &async_gen_athrow_as_async, /* tp_as_async */
2015 0, /* tp_repr */
2016 0, /* tp_as_number */
2017 0, /* tp_as_sequence */
2018 0, /* tp_as_mapping */
2019 0, /* tp_hash */
2020 0, /* tp_call */
2021 0, /* tp_str */
2022 PyObject_GenericGetAttr, /* tp_getattro */
2023 0, /* tp_setattro */
2024 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05002025 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07002026 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05002027 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07002028 0, /* tp_clear */
2029 0, /* tp_richcompare */
2030 0, /* tp_weaklistoffset */
2031 PyObject_SelfIter, /* tp_iter */
2032 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
2033 async_gen_athrow_methods, /* tp_methods */
2034 0, /* tp_members */
2035 0, /* tp_getset */
2036 0, /* tp_base */
2037 0, /* tp_dict */
2038 0, /* tp_descr_get */
2039 0, /* tp_descr_set */
2040 0, /* tp_dictoffset */
2041 0, /* tp_init */
2042 0, /* tp_alloc */
2043 0, /* tp_new */
2044};
2045
2046
2047static PyObject *
2048async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2049{
2050 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002051 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002052 if (o == NULL) {
2053 return NULL;
2054 }
2055 o->agt_gen = gen;
2056 o->agt_args = args;
2057 o->agt_state = AWAITABLE_STATE_INIT;
2058 Py_INCREF(gen);
2059 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002060 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002061 return (PyObject*)o;
2062}