blob: 885b3f2eca72ae1ee9ab9546aaab91adfd8c3ec3 [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01004#include "pycore_state.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00005#include "frameobject.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00006#include "structmember.h"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00008
Yury Selivanoveb636452016-09-08 22:01:51 -07009static PyObject *gen_close(PyGenObject *, PyObject *);
10static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
11static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
12
13static char *NON_INIT_CORO_MSG = "can't send non-None value to a "
14 "just-started coroutine";
15
16static char *ASYNC_GEN_IGNORED_EXIT_MSG =
17 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100018
Mark Shannonae3087c2017-10-22 22:41:51 +010019static inline int
20exc_state_traverse(_PyErr_StackItem *exc_state, visitproc visit, void *arg)
21{
22 Py_VISIT(exc_state->exc_type);
23 Py_VISIT(exc_state->exc_value);
24 Py_VISIT(exc_state->exc_traceback);
25 return 0;
26}
27
Martin v. Löwise440e472004-06-01 15:22:42 +000028static int
29gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
30{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 Py_VISIT((PyObject *)gen->gi_frame);
32 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020033 Py_VISIT(gen->gi_name);
34 Py_VISIT(gen->gi_qualname);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080035 /* No need to visit cr_origin, because it's just tuples/str/int, so can't
36 participate in a reference cycle. */
Mark Shannonae3087c2017-10-22 22:41:51 +010037 return exc_state_traverse(&gen->gi_exc_state, visit, arg);
Martin v. Löwise440e472004-06-01 15:22:42 +000038}
39
Antoine Pitrou58720d62013-08-05 23:26:40 +020040void
41_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020042{
43 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070044 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020045 PyObject *error_type, *error_value, *error_traceback;
46
Yury Selivanov2a2270d2018-01-29 14:31:47 -050047 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) {
Antoine Pitrou796564c2013-07-30 19:59:21 +020048 /* Generator isn't paused, so no need to close */
49 return;
Yury Selivanov2a2270d2018-01-29 14:31:47 -050050 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020051
Yury Selivanoveb636452016-09-08 22:01:51 -070052 if (PyAsyncGen_CheckExact(self)) {
53 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
54 PyObject *finalizer = agen->ag_finalizer;
55 if (finalizer && !agen->ag_closed) {
56 /* Save the current exception, if any. */
57 PyErr_Fetch(&error_type, &error_value, &error_traceback);
58
Victor Stinnerde4ae3d2016-12-04 22:59:09 +010059 res = PyObject_CallFunctionObjArgs(finalizer, self, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -070060
61 if (res == NULL) {
62 PyErr_WriteUnraisable(self);
63 } else {
64 Py_DECREF(res);
65 }
66 /* Restore the saved exception. */
67 PyErr_Restore(error_type, error_value, error_traceback);
68 return;
69 }
70 }
71
Antoine Pitrou796564c2013-07-30 19:59:21 +020072 /* Save the current exception, if any. */
73 PyErr_Fetch(&error_type, &error_value, &error_traceback);
74
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070075 /* If `gen` is a coroutine, and if it was never awaited on,
76 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070077 if (gen->gi_code != NULL &&
78 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
Yury Selivanov2a2270d2018-01-29 14:31:47 -050079 gen->gi_frame->f_lasti == -1)
80 {
81 _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070082 }
83 else {
84 res = gen_close(gen, NULL);
85 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020086
Benjamin Petersonb88db872016-09-07 08:46:59 -070087 if (res == NULL) {
Yury Selivanov2a2270d2018-01-29 14:31:47 -050088 if (PyErr_Occurred()) {
Benjamin Petersonb88db872016-09-07 08:46:59 -070089 PyErr_WriteUnraisable(self);
Yury Selivanov2a2270d2018-01-29 14:31:47 -050090 }
Benjamin Petersonb88db872016-09-07 08:46:59 -070091 }
92 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020093 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070094 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020095
96 /* Restore the saved exception. */
97 PyErr_Restore(error_type, error_value, error_traceback);
98}
99
Mark Shannonae3087c2017-10-22 22:41:51 +0100100static inline void
101exc_state_clear(_PyErr_StackItem *exc_state)
102{
103 PyObject *t, *v, *tb;
104 t = exc_state->exc_type;
105 v = exc_state->exc_value;
106 tb = exc_state->exc_traceback;
107 exc_state->exc_type = NULL;
108 exc_state->exc_value = NULL;
109 exc_state->exc_traceback = NULL;
110 Py_XDECREF(t);
111 Py_XDECREF(v);
112 Py_XDECREF(tb);
113}
114
Antoine Pitrou796564c2013-07-30 19:59:21 +0200115static void
Martin v. Löwise440e472004-06-01 15:22:42 +0000116gen_dealloc(PyGenObject *gen)
117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 if (gen->gi_weakreflist != NULL)
123 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000124
Antoine Pitrou93963562013-05-14 20:37:52 +0200125 _PyObject_GC_TRACK(self);
126
Antoine Pitrou796564c2013-07-30 19:59:21 +0200127 if (PyObject_CallFinalizerFromDealloc(self))
128 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200129
130 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700131 if (PyAsyncGen_CheckExact(gen)) {
132 /* We have to handle this case for asynchronous generators
133 right here, because this code has to be between UNTRACK
134 and GC_Del. */
135 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
136 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700137 if (gen->gi_frame != NULL) {
138 gen->gi_frame->f_gen = NULL;
139 Py_CLEAR(gen->gi_frame);
140 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800141 if (((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE) {
142 Py_CLEAR(((PyCoroObject *)gen)->cr_origin);
143 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200145 Py_CLEAR(gen->gi_name);
146 Py_CLEAR(gen->gi_qualname);
Mark Shannonae3087c2017-10-22 22:41:51 +0100147 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000149}
150
151static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500152gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000153{
Antoine Pitrou93963562013-05-14 20:37:52 +0200154 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200156 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000157
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500158 if (gen->gi_running) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200159 const char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700160 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400161 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700162 }
163 else if (PyAsyncGen_CheckExact(gen)) {
164 msg = "async generator already executing";
165 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400166 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500167 return NULL;
168 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200169 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500170 if (PyCoro_CheckExact(gen) && !closing) {
171 /* `gen` is an exhausted coroutine: raise an error,
172 except when called from gen_close(), which should
173 always be a silent method. */
174 PyErr_SetString(
175 PyExc_RuntimeError,
176 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700177 }
178 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500179 /* `gen` is an exhausted generator:
180 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700181 if (PyAsyncGen_CheckExact(gen)) {
182 PyErr_SetNone(PyExc_StopAsyncIteration);
183 }
184 else {
185 PyErr_SetNone(PyExc_StopIteration);
186 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500187 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 return NULL;
189 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000190
Antoine Pitrou93963562013-05-14 20:37:52 +0200191 if (f->f_lasti == -1) {
192 if (arg && arg != Py_None) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200193 const char *msg = "can't send non-None value to a "
194 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700195 if (PyCoro_CheckExact(gen)) {
196 msg = NON_INIT_CORO_MSG;
197 }
198 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400199 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700200 "just-started async generator";
201 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400202 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200203 return NULL;
204 }
205 } else {
206 /* Push arg onto the frame's value stack */
207 result = arg ? arg : Py_None;
208 Py_INCREF(result);
209 *(f->f_stacktop++) = result;
210 }
211
212 /* Generators always return to their most recent caller, not
213 * necessarily their creator. */
214 Py_XINCREF(tstate->frame);
215 assert(f->f_back == NULL);
216 f->f_back = tstate->frame;
217
218 gen->gi_running = 1;
Mark Shannonae3087c2017-10-22 22:41:51 +0100219 gen->gi_exc_state.previous_item = tstate->exc_info;
220 tstate->exc_info = &gen->gi_exc_state;
Victor Stinner59a73272016-12-09 18:51:13 +0100221 result = PyEval_EvalFrameEx(f, exc);
Mark Shannonae3087c2017-10-22 22:41:51 +0100222 tstate->exc_info = gen->gi_exc_state.previous_item;
223 gen->gi_exc_state.previous_item = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200224 gen->gi_running = 0;
225
226 /* Don't keep the reference to f_back any longer than necessary. It
227 * may keep a chain of frames alive or it could create a reference
228 * cycle. */
229 assert(f->f_back == tstate->frame);
230 Py_CLEAR(f->f_back);
231
232 /* If the generator just returned (as opposed to yielding), signal
233 * that the generator is exhausted. */
234 if (result && f->f_stacktop == NULL) {
235 if (result == Py_None) {
236 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700237 if (PyAsyncGen_CheckExact(gen)) {
238 PyErr_SetNone(PyExc_StopAsyncIteration);
239 }
240 else {
241 PyErr_SetNone(PyExc_StopIteration);
242 }
243 }
244 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700245 /* Async generators cannot return anything but None */
246 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200247 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200248 }
249 Py_CLEAR(result);
250 }
Yury Selivanov68333392015-05-22 11:16:47 -0400251 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500252 const char *msg = "generator raised StopIteration";
253 if (PyCoro_CheckExact(gen)) {
254 msg = "coroutine raised StopIteration";
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400255 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500256 else if PyAsyncGen_CheckExact(gen) {
257 msg = "async generator raised StopIteration";
Yury Selivanov68333392015-05-22 11:16:47 -0400258 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500259 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
260
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400261 }
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500262 else if (!result && PyAsyncGen_CheckExact(gen) &&
Yury Selivanoveb636452016-09-08 22:01:51 -0700263 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
264 {
265 /* code in `gen` raised a StopAsyncIteration error:
266 raise a RuntimeError.
267 */
268 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300269 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700270 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200271
272 if (!result || f->f_stacktop == NULL) {
273 /* generator can't be rerun, so release the frame */
274 /* first clean reference cycle through stored exception traceback */
Mark Shannonae3087c2017-10-22 22:41:51 +0100275 exc_state_clear(&gen->gi_exc_state);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200276 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200277 gen->gi_frame = NULL;
278 Py_DECREF(f);
279 }
280
281 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000282}
283
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000284PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000285"send(arg) -> send 'arg' into generator,\n\
286return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000287
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500288PyObject *
289_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000290{
Yury Selivanov77c96812016-02-13 17:59:05 -0500291 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000292}
293
294PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400295"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000296
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000297/*
298 * This helper function is used by gen_close and gen_throw to
299 * close a subiterator being delegated to by yield-from.
300 */
301
Antoine Pitrou93963562013-05-14 20:37:52 +0200302static int
303gen_close_iter(PyObject *yf)
304{
305 PyObject *retval = NULL;
306 _Py_IDENTIFIER(close);
307
Yury Selivanoveb636452016-09-08 22:01:51 -0700308 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200309 retval = gen_close((PyGenObject *)yf, NULL);
310 if (retval == NULL)
311 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700312 }
313 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200314 PyObject *meth;
315 if (_PyObject_LookupAttrId(yf, &PyId_close, &meth) < 0) {
316 PyErr_WriteUnraisable(yf);
Yury Selivanoveb636452016-09-08 22:01:51 -0700317 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200318 if (meth) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700319 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200320 Py_DECREF(meth);
321 if (retval == NULL)
322 return -1;
323 }
324 }
325 Py_XDECREF(retval);
326 return 0;
327}
328
Yury Selivanovc724bae2016-03-02 11:30:46 -0500329PyObject *
330_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500331{
Antoine Pitrou93963562013-05-14 20:37:52 +0200332 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500333 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200334
335 if (f && f->f_stacktop) {
336 PyObject *bytecode = f->f_code->co_code;
337 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
338
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100339 if (f->f_lasti < 0) {
340 /* Return immediately if the frame didn't start yet. YIELD_FROM
341 always come after LOAD_CONST: a code object should not start
342 with YIELD_FROM */
343 assert(code[0] != YIELD_FROM);
344 return NULL;
345 }
346
Serhiy Storchakaab874002016-09-11 13:48:15 +0300347 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200348 return NULL;
349 yf = f->f_stacktop[-1];
350 Py_INCREF(yf);
351 }
352
353 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500354}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000355
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000356static PyObject *
357gen_close(PyGenObject *gen, PyObject *args)
358{
Antoine Pitrou93963562013-05-14 20:37:52 +0200359 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500360 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200361 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000362
Antoine Pitrou93963562013-05-14 20:37:52 +0200363 if (yf) {
364 gen->gi_running = 1;
365 err = gen_close_iter(yf);
366 gen->gi_running = 0;
367 Py_DECREF(yf);
368 }
369 if (err == 0)
370 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500371 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200372 if (retval) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200373 const char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700374 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400375 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700376 } else if (PyAsyncGen_CheckExact(gen)) {
377 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
378 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200379 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400380 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 return NULL;
382 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200383 if (PyErr_ExceptionMatches(PyExc_StopIteration)
384 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
385 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200386 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200387 }
388 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000389}
390
Antoine Pitrou93963562013-05-14 20:37:52 +0200391
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000392PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000393"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
394return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000395
396static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700397_gen_throw(PyGenObject *gen, int close_on_genexit,
398 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000399{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500400 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000401 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000402
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000403 if (yf) {
404 PyObject *ret;
405 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700406 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
407 close_on_genexit
408 ) {
409 /* Asynchronous generators *should not* be closed right away.
410 We have to allow some awaits to work it through, hence the
411 `close_on_genexit` parameter here.
412 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500413 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200414 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500415 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000416 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000417 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500418 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000419 goto throw_here;
420 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700421 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
422 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500423 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700424 /* Close the generator that we are currently iterating with
425 'yield from' or awaiting on with 'await'. */
426 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
427 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500428 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000429 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700430 /* `yf` is an iterator or a coroutine-like object. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200431 PyObject *meth;
432 if (_PyObject_LookupAttrId(yf, &PyId_throw, &meth) < 0) {
433 Py_DECREF(yf);
434 return NULL;
435 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000436 if (meth == NULL) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000437 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 goto throw_here;
439 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500440 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700441 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500442 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000443 Py_DECREF(meth);
444 }
445 Py_DECREF(yf);
446 if (!ret) {
447 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500448 /* Pop subiterator from stack */
449 ret = *(--gen->gi_frame->f_stacktop);
450 assert(ret == yf);
451 Py_DECREF(ret);
452 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100453 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300454 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000455 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500456 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000457 Py_DECREF(val);
458 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500459 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000460 }
461 }
462 return ret;
463 }
464
465throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 /* First, check the traceback argument, replacing None with
467 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400468 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400470 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 else if (tb != NULL && !PyTraceBack_Check(tb)) {
472 PyErr_SetString(PyExc_TypeError,
473 "throw() third argument must be a traceback object");
474 return NULL;
475 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 Py_INCREF(typ);
478 Py_XINCREF(val);
479 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000480
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400481 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 else if (PyExceptionInstance_Check(typ)) {
485 /* Raising an instance. The value should be a dummy. */
486 if (val && val != Py_None) {
487 PyErr_SetString(PyExc_TypeError,
488 "instance exception may not have a separate value");
489 goto failed_throw;
490 }
491 else {
492 /* Normalize to raise <class>, <instance> */
493 Py_XDECREF(val);
494 val = typ;
495 typ = PyExceptionInstance_Class(typ);
496 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200497
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400498 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200499 /* Returns NULL if there's no traceback */
500 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 }
502 }
503 else {
504 /* Not something you can raise. throw() fails. */
505 PyErr_Format(PyExc_TypeError,
506 "exceptions must be classes or instances "
507 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000508 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 goto failed_throw;
510 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500513 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000514
515failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* Didn't use our arguments, so restore their original refcounts */
517 Py_DECREF(typ);
518 Py_XDECREF(val);
519 Py_XDECREF(tb);
520 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000521}
522
523
524static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700525gen_throw(PyGenObject *gen, PyObject *args)
526{
527 PyObject *typ;
528 PyObject *tb = NULL;
529 PyObject *val = NULL;
530
531 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
532 return NULL;
533 }
534
535 return _gen_throw(gen, 1, typ, val, tb);
536}
537
538
539static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000540gen_iternext(PyGenObject *gen)
541{
Yury Selivanov77c96812016-02-13 17:59:05 -0500542 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000543}
544
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000545/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200546 * Set StopIteration with specified value. Value can be arbitrary object
547 * or NULL.
548 *
549 * Returns 0 if StopIteration is set and -1 if any other exception is set.
550 */
551int
552_PyGen_SetStopIterationValue(PyObject *value)
553{
554 PyObject *e;
555
556 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400557 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200558 {
559 /* Delay exception instantiation if we can */
560 PyErr_SetObject(PyExc_StopIteration, value);
561 return 0;
562 }
563 /* Construct an exception instance manually with
564 * PyObject_CallFunctionObjArgs and pass it to PyErr_SetObject.
565 *
566 * We do this to handle a situation when "value" is a tuple, in which
567 * case PyErr_SetObject would set the value of StopIteration to
568 * the first element of the tuple.
569 *
570 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
571 */
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100572 e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, value, NULL);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200573 if (e == NULL) {
574 return -1;
575 }
576 PyErr_SetObject(PyExc_StopIteration, e);
577 Py_DECREF(e);
578 return 0;
579}
580
581/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000582 * If StopIteration exception is set, fetches its 'value'
583 * attribute if any, otherwise sets pvalue to None.
584 *
585 * Returns 0 if no exception or StopIteration is set.
586 * If any other exception is set, returns -1 and leaves
587 * pvalue unchanged.
588 */
589
590int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200591_PyGen_FetchStopIterationValue(PyObject **pvalue)
592{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000593 PyObject *et, *ev, *tb;
594 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500595
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000596 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
597 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200598 if (ev) {
599 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300600 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200601 value = ((PyStopIterationObject *)ev)->value;
602 Py_INCREF(value);
603 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200604 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
605 /* Avoid normalisation and take ev as value.
606 *
607 * Normalization is required if the value is a tuple, in
608 * that case the value of StopIteration would be set to
609 * the first element of the tuple.
610 *
611 * (See _PyErr_CreateException code for details.)
612 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200613 value = ev;
614 } else {
615 /* normalisation required */
616 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300617 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200618 PyErr_Restore(et, ev, tb);
619 return -1;
620 }
621 value = ((PyStopIterationObject *)ev)->value;
622 Py_INCREF(value);
623 Py_DECREF(ev);
624 }
625 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000626 Py_XDECREF(et);
627 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000628 } else if (PyErr_Occurred()) {
629 return -1;
630 }
631 if (value == NULL) {
632 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100633 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000634 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000635 *pvalue = value;
636 return 0;
637}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000638
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000639static PyObject *
640gen_repr(PyGenObject *gen)
641{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400642 return PyUnicode_FromFormat("<generator object %S at %p>",
643 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000644}
645
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000646static PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200647gen_get_name(PyGenObject *op)
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000648{
Victor Stinner40ee3012014-06-16 15:59:28 +0200649 Py_INCREF(op->gi_name);
650 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000651}
652
Victor Stinner40ee3012014-06-16 15:59:28 +0200653static int
654gen_set_name(PyGenObject *op, PyObject *value)
655{
Victor Stinner40ee3012014-06-16 15:59:28 +0200656 /* Not legal to del gen.gi_name or to set it to anything
657 * other than a string object. */
658 if (value == NULL || !PyUnicode_Check(value)) {
659 PyErr_SetString(PyExc_TypeError,
660 "__name__ must be set to a string object");
661 return -1;
662 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200663 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300664 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200665 return 0;
666}
667
668static PyObject *
669gen_get_qualname(PyGenObject *op)
670{
671 Py_INCREF(op->gi_qualname);
672 return op->gi_qualname;
673}
674
675static int
676gen_set_qualname(PyGenObject *op, PyObject *value)
677{
Victor Stinner40ee3012014-06-16 15:59:28 +0200678 /* Not legal to del gen.__qualname__ or to set it to anything
679 * other than a string object. */
680 if (value == NULL || !PyUnicode_Check(value)) {
681 PyErr_SetString(PyExc_TypeError,
682 "__qualname__ must be set to a string object");
683 return -1;
684 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200685 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300686 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200687 return 0;
688}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000689
Yury Selivanove13f8f32015-07-03 00:23:30 -0400690static PyObject *
691gen_getyieldfrom(PyGenObject *gen)
692{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500693 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400694 if (yf == NULL)
695 Py_RETURN_NONE;
696 return yf;
697}
698
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000699static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200700 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
701 PyDoc_STR("name of the generator")},
702 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
703 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400704 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
705 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200706 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000707};
708
Martin v. Löwise440e472004-06-01 15:22:42 +0000709static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200710 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
711 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
712 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000714};
715
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000716static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500717 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
719 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
720 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000721};
722
Martin v. Löwise440e472004-06-01 15:22:42 +0000723PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyVarObject_HEAD_INIT(&PyType_Type, 0)
725 "generator", /* tp_name */
726 sizeof(PyGenObject), /* tp_basicsize */
727 0, /* tp_itemsize */
728 /* methods */
729 (destructor)gen_dealloc, /* tp_dealloc */
730 0, /* tp_print */
731 0, /* tp_getattr */
732 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400733 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 (reprfunc)gen_repr, /* tp_repr */
735 0, /* tp_as_number */
736 0, /* tp_as_sequence */
737 0, /* tp_as_mapping */
738 0, /* tp_hash */
739 0, /* tp_call */
740 0, /* tp_str */
741 PyObject_GenericGetAttr, /* tp_getattro */
742 0, /* tp_setattro */
743 0, /* tp_as_buffer */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200744 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
745 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 0, /* tp_doc */
747 (traverseproc)gen_traverse, /* tp_traverse */
748 0, /* tp_clear */
749 0, /* tp_richcompare */
750 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400751 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 (iternextfunc)gen_iternext, /* tp_iternext */
753 gen_methods, /* tp_methods */
754 gen_memberlist, /* tp_members */
755 gen_getsetlist, /* tp_getset */
756 0, /* tp_base */
757 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 0, /* tp_descr_get */
760 0, /* tp_descr_set */
761 0, /* tp_dictoffset */
762 0, /* tp_init */
763 0, /* tp_alloc */
764 0, /* tp_new */
765 0, /* tp_free */
766 0, /* tp_is_gc */
767 0, /* tp_bases */
768 0, /* tp_mro */
769 0, /* tp_cache */
770 0, /* tp_subclasses */
771 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200772 0, /* tp_del */
773 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200774 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000775};
776
Yury Selivanov5376ba92015-06-22 12:19:30 -0400777static PyObject *
778gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
779 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000780{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400781 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (gen == NULL) {
783 Py_DECREF(f);
784 return NULL;
785 }
786 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200787 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 Py_INCREF(f->f_code);
789 gen->gi_code = (PyObject *)(f->f_code);
790 gen->gi_running = 0;
791 gen->gi_weakreflist = NULL;
Mark Shannonae3087c2017-10-22 22:41:51 +0100792 gen->gi_exc_state.exc_type = NULL;
793 gen->gi_exc_state.exc_value = NULL;
794 gen->gi_exc_state.exc_traceback = NULL;
795 gen->gi_exc_state.previous_item = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200796 if (name != NULL)
797 gen->gi_name = name;
798 else
799 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
800 Py_INCREF(gen->gi_name);
801 if (qualname != NULL)
802 gen->gi_qualname = qualname;
803 else
804 gen->gi_qualname = gen->gi_name;
805 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 _PyObject_GC_TRACK(gen);
807 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000808}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809
Victor Stinner40ee3012014-06-16 15:59:28 +0200810PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400811PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
812{
813 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
814}
815
816PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200817PyGen_New(PyFrameObject *f)
818{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400819 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200820}
821
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000822int
823PyGen_NeedsFinalizing(PyGenObject *gen)
824{
Antoine Pitrou93963562013-05-14 20:37:52 +0200825 PyFrameObject *f = gen->gi_frame;
826
827 if (f == NULL || f->f_stacktop == NULL)
828 return 0; /* no frame or empty blockstack == no finalization */
829
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200830 /* Any (exception-handling) block type requires cleanup. */
831 if (f->f_iblock > 0)
832 return 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200833
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200834 /* No blocks, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836}
Yury Selivanov75445082015-05-11 22:57:16 -0400837
Yury Selivanov5376ba92015-06-22 12:19:30 -0400838/* Coroutine Object */
839
840typedef struct {
841 PyObject_HEAD
842 PyCoroObject *cw_coroutine;
843} PyCoroWrapper;
844
845static int
846gen_is_coroutine(PyObject *o)
847{
848 if (PyGen_CheckExact(o)) {
849 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
850 if (code->co_flags & CO_ITERABLE_COROUTINE) {
851 return 1;
852 }
853 }
854 return 0;
855}
856
Yury Selivanov75445082015-05-11 22:57:16 -0400857/*
858 * This helper function returns an awaitable for `o`:
859 * - `o` if `o` is a coroutine-object;
860 * - `type(o)->tp_as_async->am_await(o)`
861 *
862 * Raises a TypeError if it's not possible to return
863 * an awaitable and returns NULL.
864 */
865PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400866_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400867{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400868 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400869 PyTypeObject *ot;
870
Yury Selivanov5376ba92015-06-22 12:19:30 -0400871 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
872 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400873 Py_INCREF(o);
874 return o;
875 }
876
877 ot = Py_TYPE(o);
878 if (ot->tp_as_async != NULL) {
879 getter = ot->tp_as_async->am_await;
880 }
881 if (getter != NULL) {
882 PyObject *res = (*getter)(o);
883 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400884 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
885 /* __await__ must return an *iterator*, not
886 a coroutine or another awaitable (see PEP 492) */
887 PyErr_SetString(PyExc_TypeError,
888 "__await__() returned a coroutine");
889 Py_CLEAR(res);
890 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400891 PyErr_Format(PyExc_TypeError,
892 "__await__() returned non-iterator "
893 "of type '%.100s'",
894 Py_TYPE(res)->tp_name);
895 Py_CLEAR(res);
896 }
Yury Selivanov75445082015-05-11 22:57:16 -0400897 }
898 return res;
899 }
900
901 PyErr_Format(PyExc_TypeError,
902 "object %.100s can't be used in 'await' expression",
903 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400904 return NULL;
905}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400906
907static PyObject *
908coro_repr(PyCoroObject *coro)
909{
910 return PyUnicode_FromFormat("<coroutine object %S at %p>",
911 coro->cr_qualname, coro);
912}
913
914static PyObject *
915coro_await(PyCoroObject *coro)
916{
917 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
918 if (cw == NULL) {
919 return NULL;
920 }
921 Py_INCREF(coro);
922 cw->cw_coroutine = coro;
923 _PyObject_GC_TRACK(cw);
924 return (PyObject *)cw;
925}
926
Yury Selivanove13f8f32015-07-03 00:23:30 -0400927static PyObject *
928coro_get_cr_await(PyCoroObject *coro)
929{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500930 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400931 if (yf == NULL)
932 Py_RETURN_NONE;
933 return yf;
934}
935
Yury Selivanov5376ba92015-06-22 12:19:30 -0400936static PyGetSetDef coro_getsetlist[] = {
937 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
938 PyDoc_STR("name of the coroutine")},
939 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
940 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400941 {"cr_await", (getter)coro_get_cr_await, NULL,
942 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400943 {NULL} /* Sentinel */
944};
945
946static PyMemberDef coro_memberlist[] = {
947 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
948 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
949 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800950 {"cr_origin", T_OBJECT, offsetof(PyCoroObject, cr_origin), READONLY},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400951 {NULL} /* Sentinel */
952};
953
954PyDoc_STRVAR(coro_send_doc,
955"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400956return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400957
958PyDoc_STRVAR(coro_throw_doc,
959"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400960return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400961
962PyDoc_STRVAR(coro_close_doc,
963"close() -> raise GeneratorExit inside coroutine.");
964
965static PyMethodDef coro_methods[] = {
966 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
967 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
968 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
969 {NULL, NULL} /* Sentinel */
970};
971
972static PyAsyncMethods coro_as_async = {
973 (unaryfunc)coro_await, /* am_await */
974 0, /* am_aiter */
975 0 /* am_anext */
976};
977
978PyTypeObject PyCoro_Type = {
979 PyVarObject_HEAD_INIT(&PyType_Type, 0)
980 "coroutine", /* tp_name */
981 sizeof(PyCoroObject), /* tp_basicsize */
982 0, /* tp_itemsize */
983 /* methods */
984 (destructor)gen_dealloc, /* tp_dealloc */
985 0, /* tp_print */
986 0, /* tp_getattr */
987 0, /* tp_setattr */
988 &coro_as_async, /* tp_as_async */
989 (reprfunc)coro_repr, /* tp_repr */
990 0, /* tp_as_number */
991 0, /* tp_as_sequence */
992 0, /* tp_as_mapping */
993 0, /* tp_hash */
994 0, /* tp_call */
995 0, /* tp_str */
996 PyObject_GenericGetAttr, /* tp_getattro */
997 0, /* tp_setattro */
998 0, /* tp_as_buffer */
999 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1000 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1001 0, /* tp_doc */
1002 (traverseproc)gen_traverse, /* tp_traverse */
1003 0, /* tp_clear */
1004 0, /* tp_richcompare */
1005 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1006 0, /* tp_iter */
1007 0, /* tp_iternext */
1008 coro_methods, /* tp_methods */
1009 coro_memberlist, /* tp_members */
1010 coro_getsetlist, /* tp_getset */
1011 0, /* tp_base */
1012 0, /* tp_dict */
1013 0, /* tp_descr_get */
1014 0, /* tp_descr_set */
1015 0, /* tp_dictoffset */
1016 0, /* tp_init */
1017 0, /* tp_alloc */
1018 0, /* tp_new */
1019 0, /* tp_free */
1020 0, /* tp_is_gc */
1021 0, /* tp_bases */
1022 0, /* tp_mro */
1023 0, /* tp_cache */
1024 0, /* tp_subclasses */
1025 0, /* tp_weaklist */
1026 0, /* tp_del */
1027 0, /* tp_version_tag */
1028 _PyGen_Finalize, /* tp_finalize */
1029};
1030
1031static void
1032coro_wrapper_dealloc(PyCoroWrapper *cw)
1033{
1034 _PyObject_GC_UNTRACK((PyObject *)cw);
1035 Py_CLEAR(cw->cw_coroutine);
1036 PyObject_GC_Del(cw);
1037}
1038
1039static PyObject *
1040coro_wrapper_iternext(PyCoroWrapper *cw)
1041{
Yury Selivanov77c96812016-02-13 17:59:05 -05001042 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001043}
1044
1045static PyObject *
1046coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1047{
Yury Selivanov77c96812016-02-13 17:59:05 -05001048 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001049}
1050
1051static PyObject *
1052coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1053{
1054 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1055}
1056
1057static PyObject *
1058coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1059{
1060 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1061}
1062
1063static int
1064coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1065{
1066 Py_VISIT((PyObject *)cw->cw_coroutine);
1067 return 0;
1068}
1069
1070static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001071 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1072 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1073 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001074 {NULL, NULL} /* Sentinel */
1075};
1076
1077PyTypeObject _PyCoroWrapper_Type = {
1078 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1079 "coroutine_wrapper",
1080 sizeof(PyCoroWrapper), /* tp_basicsize */
1081 0, /* tp_itemsize */
1082 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
1083 0, /* tp_print */
1084 0, /* tp_getattr */
1085 0, /* tp_setattr */
1086 0, /* tp_as_async */
1087 0, /* tp_repr */
1088 0, /* tp_as_number */
1089 0, /* tp_as_sequence */
1090 0, /* tp_as_mapping */
1091 0, /* tp_hash */
1092 0, /* tp_call */
1093 0, /* tp_str */
1094 PyObject_GenericGetAttr, /* tp_getattro */
1095 0, /* tp_setattro */
1096 0, /* tp_as_buffer */
1097 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1098 "A wrapper object implementing __await__ for coroutines.",
1099 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1100 0, /* tp_clear */
1101 0, /* tp_richcompare */
1102 0, /* tp_weaklistoffset */
1103 PyObject_SelfIter, /* tp_iter */
1104 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1105 coro_wrapper_methods, /* tp_methods */
1106 0, /* tp_members */
1107 0, /* tp_getset */
1108 0, /* tp_base */
1109 0, /* tp_dict */
1110 0, /* tp_descr_get */
1111 0, /* tp_descr_set */
1112 0, /* tp_dictoffset */
1113 0, /* tp_init */
1114 0, /* tp_alloc */
1115 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001116 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001117};
1118
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001119static PyObject *
1120compute_cr_origin(int origin_depth)
1121{
1122 PyFrameObject *frame = PyEval_GetFrame();
1123 /* First count how many frames we have */
1124 int frame_count = 0;
1125 for (; frame && frame_count < origin_depth; ++frame_count) {
1126 frame = frame->f_back;
1127 }
1128
1129 /* Now collect them */
1130 PyObject *cr_origin = PyTuple_New(frame_count);
Alexey Izbyshev8fdd3312018-08-25 10:15:23 +03001131 if (cr_origin == NULL) {
1132 return NULL;
1133 }
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001134 frame = PyEval_GetFrame();
1135 for (int i = 0; i < frame_count; ++i) {
1136 PyObject *frameinfo = Py_BuildValue(
1137 "OiO",
1138 frame->f_code->co_filename,
1139 PyFrame_GetLineNumber(frame),
1140 frame->f_code->co_name);
1141 if (!frameinfo) {
1142 Py_DECREF(cr_origin);
1143 return NULL;
1144 }
1145 PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1146 frame = frame->f_back;
1147 }
1148
1149 return cr_origin;
1150}
1151
Yury Selivanov5376ba92015-06-22 12:19:30 -04001152PyObject *
1153PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1154{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001155 PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1156 if (!coro) {
1157 return NULL;
1158 }
1159
1160 PyThreadState *tstate = PyThreadState_GET();
1161 int origin_depth = tstate->coroutine_origin_tracking_depth;
1162
1163 if (origin_depth == 0) {
1164 ((PyCoroObject *)coro)->cr_origin = NULL;
1165 } else {
1166 PyObject *cr_origin = compute_cr_origin(origin_depth);
1167 if (!cr_origin) {
1168 Py_DECREF(coro);
1169 return NULL;
1170 }
1171 ((PyCoroObject *)coro)->cr_origin = cr_origin;
1172 }
1173
1174 return coro;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001175}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001176
1177
Yury Selivanoveb636452016-09-08 22:01:51 -07001178/* ========= Asynchronous Generators ========= */
1179
1180
1181typedef enum {
1182 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1183 AWAITABLE_STATE_ITER, /* being iterated */
1184 AWAITABLE_STATE_CLOSED, /* closed */
1185} AwaitableState;
1186
1187
1188typedef struct {
1189 PyObject_HEAD
1190 PyAsyncGenObject *ags_gen;
1191
1192 /* Can be NULL, when in the __anext__() mode
1193 (equivalent of "asend(None)") */
1194 PyObject *ags_sendval;
1195
1196 AwaitableState ags_state;
1197} PyAsyncGenASend;
1198
1199
1200typedef struct {
1201 PyObject_HEAD
1202 PyAsyncGenObject *agt_gen;
1203
1204 /* Can be NULL, when in the "aclose()" mode
1205 (equivalent of "athrow(GeneratorExit)") */
1206 PyObject *agt_args;
1207
1208 AwaitableState agt_state;
1209} PyAsyncGenAThrow;
1210
1211
1212typedef struct {
1213 PyObject_HEAD
1214 PyObject *agw_val;
1215} _PyAsyncGenWrappedValue;
1216
1217
1218#ifndef _PyAsyncGen_MAXFREELIST
1219#define _PyAsyncGen_MAXFREELIST 80
1220#endif
1221
1222/* Freelists boost performance 6-10%; they also reduce memory
1223 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1224 are short-living objects that are instantiated for every
1225 __anext__ call.
1226*/
1227
1228static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1229static int ag_value_freelist_free = 0;
1230
1231static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1232static int ag_asend_freelist_free = 0;
1233
1234#define _PyAsyncGenWrappedValue_CheckExact(o) \
1235 (Py_TYPE(o) == &_PyAsyncGenWrappedValue_Type)
1236
1237#define PyAsyncGenASend_CheckExact(o) \
1238 (Py_TYPE(o) == &_PyAsyncGenASend_Type)
1239
1240
1241static int
1242async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1243{
1244 Py_VISIT(gen->ag_finalizer);
1245 return gen_traverse((PyGenObject*)gen, visit, arg);
1246}
1247
1248
1249static PyObject *
1250async_gen_repr(PyAsyncGenObject *o)
1251{
1252 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1253 o->ag_qualname, o);
1254}
1255
1256
1257static int
1258async_gen_init_hooks(PyAsyncGenObject *o)
1259{
1260 PyThreadState *tstate;
1261 PyObject *finalizer;
1262 PyObject *firstiter;
1263
1264 if (o->ag_hooks_inited) {
1265 return 0;
1266 }
1267
1268 o->ag_hooks_inited = 1;
1269
1270 tstate = PyThreadState_GET();
1271
1272 finalizer = tstate->async_gen_finalizer;
1273 if (finalizer) {
1274 Py_INCREF(finalizer);
1275 o->ag_finalizer = finalizer;
1276 }
1277
1278 firstiter = tstate->async_gen_firstiter;
1279 if (firstiter) {
1280 PyObject *res;
1281
1282 Py_INCREF(firstiter);
Victor Stinner7bfb42d2016-12-05 17:04:32 +01001283 res = PyObject_CallFunctionObjArgs(firstiter, o, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -07001284 Py_DECREF(firstiter);
1285 if (res == NULL) {
1286 return 1;
1287 }
1288 Py_DECREF(res);
1289 }
1290
1291 return 0;
1292}
1293
1294
1295static PyObject *
1296async_gen_anext(PyAsyncGenObject *o)
1297{
1298 if (async_gen_init_hooks(o)) {
1299 return NULL;
1300 }
1301 return async_gen_asend_new(o, NULL);
1302}
1303
1304
1305static PyObject *
1306async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1307{
1308 if (async_gen_init_hooks(o)) {
1309 return NULL;
1310 }
1311 return async_gen_asend_new(o, arg);
1312}
1313
1314
1315static PyObject *
1316async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1317{
1318 if (async_gen_init_hooks(o)) {
1319 return NULL;
1320 }
1321 return async_gen_athrow_new(o, NULL);
1322}
1323
1324static PyObject *
1325async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1326{
1327 if (async_gen_init_hooks(o)) {
1328 return NULL;
1329 }
1330 return async_gen_athrow_new(o, args);
1331}
1332
1333
1334static PyGetSetDef async_gen_getsetlist[] = {
1335 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1336 PyDoc_STR("name of the async generator")},
1337 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1338 PyDoc_STR("qualified name of the async generator")},
1339 {"ag_await", (getter)coro_get_cr_await, NULL,
1340 PyDoc_STR("object being awaited on, or None")},
1341 {NULL} /* Sentinel */
1342};
1343
1344static PyMemberDef async_gen_memberlist[] = {
1345 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
1346 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running), READONLY},
1347 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1348 {NULL} /* Sentinel */
1349};
1350
1351PyDoc_STRVAR(async_aclose_doc,
1352"aclose() -> raise GeneratorExit inside generator.");
1353
1354PyDoc_STRVAR(async_asend_doc,
1355"asend(v) -> send 'v' in generator.");
1356
1357PyDoc_STRVAR(async_athrow_doc,
1358"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1359
1360static PyMethodDef async_gen_methods[] = {
1361 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1362 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1363 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
1364 {NULL, NULL} /* Sentinel */
1365};
1366
1367
1368static PyAsyncMethods async_gen_as_async = {
1369 0, /* am_await */
1370 PyObject_SelfIter, /* am_aiter */
1371 (unaryfunc)async_gen_anext /* am_anext */
1372};
1373
1374
1375PyTypeObject PyAsyncGen_Type = {
1376 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1377 "async_generator", /* tp_name */
1378 sizeof(PyAsyncGenObject), /* tp_basicsize */
1379 0, /* tp_itemsize */
1380 /* methods */
1381 (destructor)gen_dealloc, /* tp_dealloc */
1382 0, /* tp_print */
1383 0, /* tp_getattr */
1384 0, /* tp_setattr */
1385 &async_gen_as_async, /* tp_as_async */
1386 (reprfunc)async_gen_repr, /* tp_repr */
1387 0, /* tp_as_number */
1388 0, /* tp_as_sequence */
1389 0, /* tp_as_mapping */
1390 0, /* tp_hash */
1391 0, /* tp_call */
1392 0, /* tp_str */
1393 PyObject_GenericGetAttr, /* tp_getattro */
1394 0, /* tp_setattro */
1395 0, /* tp_as_buffer */
1396 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1397 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1398 0, /* tp_doc */
1399 (traverseproc)async_gen_traverse, /* tp_traverse */
1400 0, /* tp_clear */
1401 0, /* tp_richcompare */
1402 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1403 0, /* tp_iter */
1404 0, /* tp_iternext */
1405 async_gen_methods, /* tp_methods */
1406 async_gen_memberlist, /* tp_members */
1407 async_gen_getsetlist, /* tp_getset */
1408 0, /* tp_base */
1409 0, /* tp_dict */
1410 0, /* tp_descr_get */
1411 0, /* tp_descr_set */
1412 0, /* tp_dictoffset */
1413 0, /* tp_init */
1414 0, /* tp_alloc */
1415 0, /* tp_new */
1416 0, /* tp_free */
1417 0, /* tp_is_gc */
1418 0, /* tp_bases */
1419 0, /* tp_mro */
1420 0, /* tp_cache */
1421 0, /* tp_subclasses */
1422 0, /* tp_weaklist */
1423 0, /* tp_del */
1424 0, /* tp_version_tag */
1425 _PyGen_Finalize, /* tp_finalize */
1426};
1427
1428
1429PyObject *
1430PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1431{
1432 PyAsyncGenObject *o;
1433 o = (PyAsyncGenObject *)gen_new_with_qualname(
1434 &PyAsyncGen_Type, f, name, qualname);
1435 if (o == NULL) {
1436 return NULL;
1437 }
1438 o->ag_finalizer = NULL;
1439 o->ag_closed = 0;
1440 o->ag_hooks_inited = 0;
1441 return (PyObject*)o;
1442}
1443
1444
1445int
1446PyAsyncGen_ClearFreeLists(void)
1447{
1448 int ret = ag_value_freelist_free + ag_asend_freelist_free;
1449
1450 while (ag_value_freelist_free) {
1451 _PyAsyncGenWrappedValue *o;
1452 o = ag_value_freelist[--ag_value_freelist_free];
1453 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001454 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001455 }
1456
1457 while (ag_asend_freelist_free) {
1458 PyAsyncGenASend *o;
1459 o = ag_asend_freelist[--ag_asend_freelist_free];
1460 assert(Py_TYPE(o) == &_PyAsyncGenASend_Type);
Yury Selivanov29310c42016-11-08 19:46:22 -05001461 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001462 }
1463
1464 return ret;
1465}
1466
1467void
1468PyAsyncGen_Fini(void)
1469{
1470 PyAsyncGen_ClearFreeLists();
1471}
1472
1473
1474static PyObject *
1475async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1476{
1477 if (result == NULL) {
1478 if (!PyErr_Occurred()) {
1479 PyErr_SetNone(PyExc_StopAsyncIteration);
1480 }
1481
1482 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1483 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1484 ) {
1485 gen->ag_closed = 1;
1486 }
1487
1488 return NULL;
1489 }
1490
1491 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1492 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001493 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001494 Py_DECREF(result);
Yury Selivanoveb636452016-09-08 22:01:51 -07001495 return NULL;
1496 }
1497
1498 return result;
1499}
1500
1501
1502/* ---------- Async Generator ASend Awaitable ------------ */
1503
1504
1505static void
1506async_gen_asend_dealloc(PyAsyncGenASend *o)
1507{
Yury Selivanov29310c42016-11-08 19:46:22 -05001508 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001509 Py_CLEAR(o->ags_gen);
1510 Py_CLEAR(o->ags_sendval);
1511 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1512 assert(PyAsyncGenASend_CheckExact(o));
1513 ag_asend_freelist[ag_asend_freelist_free++] = o;
1514 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001515 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001516 }
1517}
1518
Yury Selivanov29310c42016-11-08 19:46:22 -05001519static int
1520async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1521{
1522 Py_VISIT(o->ags_gen);
1523 Py_VISIT(o->ags_sendval);
1524 return 0;
1525}
1526
Yury Selivanoveb636452016-09-08 22:01:51 -07001527
1528static PyObject *
1529async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1530{
1531 PyObject *result;
1532
1533 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1534 PyErr_SetNone(PyExc_StopIteration);
1535 return NULL;
1536 }
1537
1538 if (o->ags_state == AWAITABLE_STATE_INIT) {
1539 if (arg == NULL || arg == Py_None) {
1540 arg = o->ags_sendval;
1541 }
1542 o->ags_state = AWAITABLE_STATE_ITER;
1543 }
1544
1545 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1546 result = async_gen_unwrap_value(o->ags_gen, result);
1547
1548 if (result == NULL) {
1549 o->ags_state = AWAITABLE_STATE_CLOSED;
1550 }
1551
1552 return result;
1553}
1554
1555
1556static PyObject *
1557async_gen_asend_iternext(PyAsyncGenASend *o)
1558{
1559 return async_gen_asend_send(o, NULL);
1560}
1561
1562
1563static PyObject *
1564async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1565{
1566 PyObject *result;
1567
1568 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1569 PyErr_SetNone(PyExc_StopIteration);
1570 return NULL;
1571 }
1572
1573 result = gen_throw((PyGenObject*)o->ags_gen, args);
1574 result = async_gen_unwrap_value(o->ags_gen, result);
1575
1576 if (result == NULL) {
1577 o->ags_state = AWAITABLE_STATE_CLOSED;
1578 }
1579
1580 return result;
1581}
1582
1583
1584static PyObject *
1585async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1586{
1587 o->ags_state = AWAITABLE_STATE_CLOSED;
1588 Py_RETURN_NONE;
1589}
1590
1591
1592static PyMethodDef async_gen_asend_methods[] = {
1593 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1594 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1595 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1596 {NULL, NULL} /* Sentinel */
1597};
1598
1599
1600static PyAsyncMethods async_gen_asend_as_async = {
1601 PyObject_SelfIter, /* am_await */
1602 0, /* am_aiter */
1603 0 /* am_anext */
1604};
1605
1606
1607PyTypeObject _PyAsyncGenASend_Type = {
1608 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1609 "async_generator_asend", /* tp_name */
1610 sizeof(PyAsyncGenASend), /* tp_basicsize */
1611 0, /* tp_itemsize */
1612 /* methods */
1613 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
1614 0, /* tp_print */
1615 0, /* tp_getattr */
1616 0, /* tp_setattr */
1617 &async_gen_asend_as_async, /* tp_as_async */
1618 0, /* tp_repr */
1619 0, /* tp_as_number */
1620 0, /* tp_as_sequence */
1621 0, /* tp_as_mapping */
1622 0, /* tp_hash */
1623 0, /* tp_call */
1624 0, /* tp_str */
1625 PyObject_GenericGetAttr, /* tp_getattro */
1626 0, /* tp_setattro */
1627 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001629 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001630 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001631 0, /* tp_clear */
1632 0, /* tp_richcompare */
1633 0, /* tp_weaklistoffset */
1634 PyObject_SelfIter, /* tp_iter */
1635 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1636 async_gen_asend_methods, /* tp_methods */
1637 0, /* tp_members */
1638 0, /* tp_getset */
1639 0, /* tp_base */
1640 0, /* tp_dict */
1641 0, /* tp_descr_get */
1642 0, /* tp_descr_set */
1643 0, /* tp_dictoffset */
1644 0, /* tp_init */
1645 0, /* tp_alloc */
1646 0, /* tp_new */
1647};
1648
1649
1650static PyObject *
1651async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1652{
1653 PyAsyncGenASend *o;
1654 if (ag_asend_freelist_free) {
1655 ag_asend_freelist_free--;
1656 o = ag_asend_freelist[ag_asend_freelist_free];
1657 _Py_NewReference((PyObject *)o);
1658 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001659 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001660 if (o == NULL) {
1661 return NULL;
1662 }
1663 }
1664
1665 Py_INCREF(gen);
1666 o->ags_gen = gen;
1667
1668 Py_XINCREF(sendval);
1669 o->ags_sendval = sendval;
1670
1671 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001672
1673 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001674 return (PyObject*)o;
1675}
1676
1677
1678/* ---------- Async Generator Value Wrapper ------------ */
1679
1680
1681static void
1682async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1683{
Yury Selivanov29310c42016-11-08 19:46:22 -05001684 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001685 Py_CLEAR(o->agw_val);
1686 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1687 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1688 ag_value_freelist[ag_value_freelist_free++] = o;
1689 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001690 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001691 }
1692}
1693
1694
Yury Selivanov29310c42016-11-08 19:46:22 -05001695static int
1696async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1697 visitproc visit, void *arg)
1698{
1699 Py_VISIT(o->agw_val);
1700 return 0;
1701}
1702
1703
Yury Selivanoveb636452016-09-08 22:01:51 -07001704PyTypeObject _PyAsyncGenWrappedValue_Type = {
1705 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1706 "async_generator_wrapped_value", /* tp_name */
1707 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1708 0, /* tp_itemsize */
1709 /* methods */
1710 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
1711 0, /* tp_print */
1712 0, /* tp_getattr */
1713 0, /* tp_setattr */
1714 0, /* tp_as_async */
1715 0, /* tp_repr */
1716 0, /* tp_as_number */
1717 0, /* tp_as_sequence */
1718 0, /* tp_as_mapping */
1719 0, /* tp_hash */
1720 0, /* tp_call */
1721 0, /* tp_str */
1722 PyObject_GenericGetAttr, /* tp_getattro */
1723 0, /* tp_setattro */
1724 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001725 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001726 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001727 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001728 0, /* tp_clear */
1729 0, /* tp_richcompare */
1730 0, /* tp_weaklistoffset */
1731 0, /* tp_iter */
1732 0, /* tp_iternext */
1733 0, /* tp_methods */
1734 0, /* tp_members */
1735 0, /* tp_getset */
1736 0, /* tp_base */
1737 0, /* tp_dict */
1738 0, /* tp_descr_get */
1739 0, /* tp_descr_set */
1740 0, /* tp_dictoffset */
1741 0, /* tp_init */
1742 0, /* tp_alloc */
1743 0, /* tp_new */
1744};
1745
1746
1747PyObject *
1748_PyAsyncGenValueWrapperNew(PyObject *val)
1749{
1750 _PyAsyncGenWrappedValue *o;
1751 assert(val);
1752
1753 if (ag_value_freelist_free) {
1754 ag_value_freelist_free--;
1755 o = ag_value_freelist[ag_value_freelist_free];
1756 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1757 _Py_NewReference((PyObject*)o);
1758 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001759 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1760 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001761 if (o == NULL) {
1762 return NULL;
1763 }
1764 }
1765 o->agw_val = val;
1766 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001767 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001768 return (PyObject*)o;
1769}
1770
1771
1772/* ---------- Async Generator AThrow awaitable ------------ */
1773
1774
1775static void
1776async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1777{
Yury Selivanov29310c42016-11-08 19:46:22 -05001778 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001779 Py_CLEAR(o->agt_gen);
1780 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001781 PyObject_GC_Del(o);
1782}
1783
1784
1785static int
1786async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1787{
1788 Py_VISIT(o->agt_gen);
1789 Py_VISIT(o->agt_args);
1790 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001791}
1792
1793
1794static PyObject *
1795async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1796{
1797 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1798 PyFrameObject *f = gen->gi_frame;
1799 PyObject *retval;
1800
1801 if (f == NULL || f->f_stacktop == NULL ||
1802 o->agt_state == AWAITABLE_STATE_CLOSED) {
1803 PyErr_SetNone(PyExc_StopIteration);
1804 return NULL;
1805 }
1806
1807 if (o->agt_state == AWAITABLE_STATE_INIT) {
1808 if (o->agt_gen->ag_closed) {
1809 PyErr_SetNone(PyExc_StopIteration);
1810 return NULL;
1811 }
1812
1813 if (arg != Py_None) {
1814 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1815 return NULL;
1816 }
1817
1818 o->agt_state = AWAITABLE_STATE_ITER;
1819
1820 if (o->agt_args == NULL) {
1821 /* aclose() mode */
1822 o->agt_gen->ag_closed = 1;
1823
1824 retval = _gen_throw((PyGenObject *)gen,
1825 0, /* Do not close generator when
1826 PyExc_GeneratorExit is passed */
1827 PyExc_GeneratorExit, NULL, NULL);
1828
1829 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1830 Py_DECREF(retval);
1831 goto yield_close;
1832 }
1833 } else {
1834 PyObject *typ;
1835 PyObject *tb = NULL;
1836 PyObject *val = NULL;
1837
1838 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1839 &typ, &val, &tb)) {
1840 return NULL;
1841 }
1842
1843 retval = _gen_throw((PyGenObject *)gen,
1844 0, /* Do not close generator when
1845 PyExc_GeneratorExit is passed */
1846 typ, val, tb);
1847 retval = async_gen_unwrap_value(o->agt_gen, retval);
1848 }
1849 if (retval == NULL) {
1850 goto check_error;
1851 }
1852 return retval;
1853 }
1854
1855 assert(o->agt_state == AWAITABLE_STATE_ITER);
1856
1857 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1858 if (o->agt_args) {
1859 return async_gen_unwrap_value(o->agt_gen, retval);
1860 } else {
1861 /* aclose() mode */
1862 if (retval) {
1863 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1864 Py_DECREF(retval);
1865 goto yield_close;
1866 }
1867 else {
1868 return retval;
1869 }
1870 }
1871 else {
1872 goto check_error;
1873 }
1874 }
1875
1876yield_close:
1877 PyErr_SetString(
1878 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1879 return NULL;
1880
1881check_error:
Yury Selivanov52698c72018-06-07 20:31:26 -04001882 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
1883 PyErr_ExceptionMatches(PyExc_GeneratorExit))
1884 {
Yury Selivanov41782e42016-11-16 18:16:17 -05001885 o->agt_state = AWAITABLE_STATE_CLOSED;
1886 if (o->agt_args == NULL) {
1887 /* when aclose() is called we don't want to propagate
Yury Selivanov52698c72018-06-07 20:31:26 -04001888 StopAsyncIteration or GeneratorExit; just raise
1889 StopIteration, signalling that this 'aclose()' await
1890 is done.
1891 */
Yury Selivanov41782e42016-11-16 18:16:17 -05001892 PyErr_Clear();
1893 PyErr_SetNone(PyExc_StopIteration);
1894 }
1895 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001896 return NULL;
1897}
1898
1899
1900static PyObject *
1901async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1902{
1903 PyObject *retval;
1904
1905 if (o->agt_state == AWAITABLE_STATE_INIT) {
1906 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1907 return NULL;
1908 }
1909
1910 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
1911 PyErr_SetNone(PyExc_StopIteration);
1912 return NULL;
1913 }
1914
1915 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1916 if (o->agt_args) {
1917 return async_gen_unwrap_value(o->agt_gen, retval);
1918 } else {
1919 /* aclose() mode */
1920 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1921 Py_DECREF(retval);
1922 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1923 return NULL;
1924 }
1925 return retval;
1926 }
1927}
1928
1929
1930static PyObject *
1931async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1932{
1933 return async_gen_athrow_send(o, Py_None);
1934}
1935
1936
1937static PyObject *
1938async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1939{
1940 o->agt_state = AWAITABLE_STATE_CLOSED;
1941 Py_RETURN_NONE;
1942}
1943
1944
1945static PyMethodDef async_gen_athrow_methods[] = {
1946 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1947 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1948 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1949 {NULL, NULL} /* Sentinel */
1950};
1951
1952
1953static PyAsyncMethods async_gen_athrow_as_async = {
1954 PyObject_SelfIter, /* am_await */
1955 0, /* am_aiter */
1956 0 /* am_anext */
1957};
1958
1959
1960PyTypeObject _PyAsyncGenAThrow_Type = {
1961 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1962 "async_generator_athrow", /* tp_name */
1963 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1964 0, /* tp_itemsize */
1965 /* methods */
1966 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
1967 0, /* tp_print */
1968 0, /* tp_getattr */
1969 0, /* tp_setattr */
1970 &async_gen_athrow_as_async, /* tp_as_async */
1971 0, /* tp_repr */
1972 0, /* tp_as_number */
1973 0, /* tp_as_sequence */
1974 0, /* tp_as_mapping */
1975 0, /* tp_hash */
1976 0, /* tp_call */
1977 0, /* tp_str */
1978 PyObject_GenericGetAttr, /* tp_getattro */
1979 0, /* tp_setattro */
1980 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001981 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001982 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001983 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001984 0, /* tp_clear */
1985 0, /* tp_richcompare */
1986 0, /* tp_weaklistoffset */
1987 PyObject_SelfIter, /* tp_iter */
1988 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
1989 async_gen_athrow_methods, /* tp_methods */
1990 0, /* tp_members */
1991 0, /* tp_getset */
1992 0, /* tp_base */
1993 0, /* tp_dict */
1994 0, /* tp_descr_get */
1995 0, /* tp_descr_set */
1996 0, /* tp_dictoffset */
1997 0, /* tp_init */
1998 0, /* tp_alloc */
1999 0, /* tp_new */
2000};
2001
2002
2003static PyObject *
2004async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2005{
2006 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05002007 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07002008 if (o == NULL) {
2009 return NULL;
2010 }
2011 o->agt_gen = gen;
2012 o->agt_args = args;
2013 o->agt_state = AWAITABLE_STATE_INIT;
2014 Py_INCREF(gen);
2015 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05002016 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07002017 return (PyObject*)o;
2018}