blob: 7bcf016c34cb3abf6e1cd5d1af28ad6a199a02ca [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
4#include "frameobject.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00005#include "structmember.h"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006#include "opcode.h"
Martin v. Löwise440e472004-06-01 15:22:42 +00007
Yury Selivanoveb636452016-09-08 22:01:51 -07008static PyObject *gen_close(PyGenObject *, PyObject *);
9static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *);
10static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
11
12static char *NON_INIT_CORO_MSG = "can't send non-None value to a "
13 "just-started coroutine";
14
15static char *ASYNC_GEN_IGNORED_EXIT_MSG =
16 "async generator ignored GeneratorExit";
Nick Coghlan1f7ce622012-01-13 21:43:40 +100017
Martin v. Löwise440e472004-06-01 15:22:42 +000018static int
19gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
20{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 Py_VISIT((PyObject *)gen->gi_frame);
22 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020023 Py_VISIT(gen->gi_name);
24 Py_VISIT(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000026}
27
Antoine Pitrou58720d62013-08-05 23:26:40 +020028void
29_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020030{
31 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070032 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020033 PyObject *error_type, *error_value, *error_traceback;
34
35 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
36 /* Generator isn't paused, so no need to close */
37 return;
38
Yury Selivanoveb636452016-09-08 22:01:51 -070039 if (PyAsyncGen_CheckExact(self)) {
40 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
41 PyObject *finalizer = agen->ag_finalizer;
42 if (finalizer && !agen->ag_closed) {
43 /* Save the current exception, if any. */
44 PyErr_Fetch(&error_type, &error_value, &error_traceback);
45
46 res = PyObject_CallFunctionObjArgs(finalizer, self, NULL);
47
48 if (res == NULL) {
49 PyErr_WriteUnraisable(self);
50 } else {
51 Py_DECREF(res);
52 }
53 /* Restore the saved exception. */
54 PyErr_Restore(error_type, error_value, error_traceback);
55 return;
56 }
57 }
58
Antoine Pitrou796564c2013-07-30 19:59:21 +020059 /* Save the current exception, if any. */
60 PyErr_Fetch(&error_type, &error_value, &error_traceback);
61
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070062 /* If `gen` is a coroutine, and if it was never awaited on,
63 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070064 if (gen->gi_code != NULL &&
65 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
66 gen->gi_frame->f_lasti == -1) {
67 if (!error_value) {
68 PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
69 "coroutine '%.50S' was never awaited",
70 gen->gi_qualname);
71 }
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070072 }
73 else {
74 res = gen_close(gen, NULL);
75 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020076
Benjamin Petersonb88db872016-09-07 08:46:59 -070077 if (res == NULL) {
78 if (PyErr_Occurred())
79 PyErr_WriteUnraisable(self);
80 }
81 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020082 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070083 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020084
85 /* Restore the saved exception. */
86 PyErr_Restore(error_type, error_value, error_traceback);
87}
88
89static void
Martin v. Löwise440e472004-06-01 15:22:42 +000090gen_dealloc(PyGenObject *gen)
91{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 if (gen->gi_weakreflist != NULL)
97 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000098
Antoine Pitrou93963562013-05-14 20:37:52 +020099 _PyObject_GC_TRACK(self);
100
Antoine Pitrou796564c2013-07-30 19:59:21 +0200101 if (PyObject_CallFinalizerFromDealloc(self))
102 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200103
104 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700105 if (PyAsyncGen_CheckExact(gen)) {
106 /* We have to handle this case for asynchronous generators
107 right here, because this code has to be between UNTRACK
108 and GC_Del. */
109 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
110 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700111 if (gen->gi_frame != NULL) {
112 gen->gi_frame->f_gen = NULL;
113 Py_CLEAR(gen->gi_frame);
114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200116 Py_CLEAR(gen->gi_name);
117 Py_CLEAR(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000119}
120
121static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500122gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000123{
Antoine Pitrou93963562013-05-14 20:37:52 +0200124 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200126 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000127
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500128 if (gen->gi_running) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400129 char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700130 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400131 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700132 }
133 else if (PyAsyncGen_CheckExact(gen)) {
134 msg = "async generator already executing";
135 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400136 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500137 return NULL;
138 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200139 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500140 if (PyCoro_CheckExact(gen) && !closing) {
141 /* `gen` is an exhausted coroutine: raise an error,
142 except when called from gen_close(), which should
143 always be a silent method. */
144 PyErr_SetString(
145 PyExc_RuntimeError,
146 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700147 }
148 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500149 /* `gen` is an exhausted generator:
150 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700151 if (PyAsyncGen_CheckExact(gen)) {
152 PyErr_SetNone(PyExc_StopAsyncIteration);
153 }
154 else {
155 PyErr_SetNone(PyExc_StopIteration);
156 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500157 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 return NULL;
159 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000160
Antoine Pitrou93963562013-05-14 20:37:52 +0200161 if (f->f_lasti == -1) {
162 if (arg && arg != Py_None) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400163 char *msg = "can't send non-None value to a "
164 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700165 if (PyCoro_CheckExact(gen)) {
166 msg = NON_INIT_CORO_MSG;
167 }
168 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400169 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700170 "just-started async generator";
171 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400172 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200173 return NULL;
174 }
175 } else {
176 /* Push arg onto the frame's value stack */
177 result = arg ? arg : Py_None;
178 Py_INCREF(result);
179 *(f->f_stacktop++) = result;
180 }
181
182 /* Generators always return to their most recent caller, not
183 * necessarily their creator. */
184 Py_XINCREF(tstate->frame);
185 assert(f->f_back == NULL);
186 f->f_back = tstate->frame;
187
188 gen->gi_running = 1;
189 result = PyEval_EvalFrameEx(f, exc);
190 gen->gi_running = 0;
191
192 /* Don't keep the reference to f_back any longer than necessary. It
193 * may keep a chain of frames alive or it could create a reference
194 * cycle. */
195 assert(f->f_back == tstate->frame);
196 Py_CLEAR(f->f_back);
197
198 /* If the generator just returned (as opposed to yielding), signal
199 * that the generator is exhausted. */
200 if (result && f->f_stacktop == NULL) {
201 if (result == Py_None) {
202 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700203 if (PyAsyncGen_CheckExact(gen)) {
204 PyErr_SetNone(PyExc_StopAsyncIteration);
205 }
206 else {
207 PyErr_SetNone(PyExc_StopIteration);
208 }
209 }
210 else {
Antoine Pitrou93963562013-05-14 20:37:52 +0200211 PyObject *e = PyObject_CallFunctionObjArgs(
212 PyExc_StopIteration, result, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -0700213
214 /* Async generators cannot return anything but None */
215 assert(!PyAsyncGen_CheckExact(gen));
216
Antoine Pitrou93963562013-05-14 20:37:52 +0200217 if (e != NULL) {
218 PyErr_SetObject(PyExc_StopIteration, e);
219 Py_DECREF(e);
220 }
221 }
222 Py_CLEAR(result);
223 }
Yury Selivanov68333392015-05-22 11:16:47 -0400224 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400225 /* Check for __future__ generator_stop and conditionally turn
226 * a leaking StopIteration into RuntimeError (with its cause
227 * set appropriately). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700228
229 const int check_stop_iter_error_flags = CO_FUTURE_GENERATOR_STOP |
230 CO_COROUTINE |
231 CO_ITERABLE_COROUTINE |
232 CO_ASYNC_GENERATOR;
233
234 if (gen->gi_code != NULL &&
235 ((PyCodeObject *)gen->gi_code)->co_flags &
236 check_stop_iter_error_flags)
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400237 {
Yury Selivanoveb636452016-09-08 22:01:51 -0700238 /* `gen` is either:
239 * a generator with CO_FUTURE_GENERATOR_STOP flag;
240 * a coroutine;
241 * a generator with CO_ITERABLE_COROUTINE flag
242 (decorated with types.coroutine decorator);
243 * an async generator.
244 */
245 const char *msg = "generator raised StopIteration";
246 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400247 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700248 }
249 else if PyAsyncGen_CheckExact(gen) {
250 msg = "async generator raised StopIteration";
251 }
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300252 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400253 }
Yury Selivanov68333392015-05-22 11:16:47 -0400254 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700255 /* `gen` is an ordinary generator without
256 CO_FUTURE_GENERATOR_STOP flag.
257 */
258
Yury Selivanov68333392015-05-22 11:16:47 -0400259 PyObject *exc, *val, *tb;
260
261 /* Pop the exception before issuing a warning. */
262 PyErr_Fetch(&exc, &val, &tb);
263
Martin Panter7e3a91a2016-02-10 04:40:48 +0000264 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Yury Selivanov68333392015-05-22 11:16:47 -0400265 "generator '%.50S' raised StopIteration",
266 gen->gi_qualname)) {
267 /* Warning was converted to an error. */
268 Py_XDECREF(exc);
269 Py_XDECREF(val);
270 Py_XDECREF(tb);
271 }
272 else {
273 PyErr_Restore(exc, val, tb);
274 }
275 }
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400276 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700277 else if (PyAsyncGen_CheckExact(gen) && !result &&
278 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
279 {
280 /* code in `gen` raised a StopAsyncIteration error:
281 raise a RuntimeError.
282 */
283 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300284 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700285 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200286
287 if (!result || f->f_stacktop == NULL) {
288 /* generator can't be rerun, so release the frame */
289 /* first clean reference cycle through stored exception traceback */
290 PyObject *t, *v, *tb;
291 t = f->f_exc_type;
292 v = f->f_exc_value;
293 tb = f->f_exc_traceback;
294 f->f_exc_type = NULL;
295 f->f_exc_value = NULL;
296 f->f_exc_traceback = NULL;
297 Py_XDECREF(t);
298 Py_XDECREF(v);
299 Py_XDECREF(tb);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200300 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200301 gen->gi_frame = NULL;
302 Py_DECREF(f);
303 }
304
305 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000306}
307
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000308PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000309"send(arg) -> send 'arg' into generator,\n\
310return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000311
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500312PyObject *
313_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000314{
Yury Selivanov77c96812016-02-13 17:59:05 -0500315 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000316}
317
318PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400319"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000320
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000321/*
322 * This helper function is used by gen_close and gen_throw to
323 * close a subiterator being delegated to by yield-from.
324 */
325
Antoine Pitrou93963562013-05-14 20:37:52 +0200326static int
327gen_close_iter(PyObject *yf)
328{
329 PyObject *retval = NULL;
330 _Py_IDENTIFIER(close);
331
Yury Selivanoveb636452016-09-08 22:01:51 -0700332 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200333 retval = gen_close((PyGenObject *)yf, NULL);
334 if (retval == NULL)
335 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700336 }
337 else {
Antoine Pitrou93963562013-05-14 20:37:52 +0200338 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
339 if (meth == NULL) {
340 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
341 PyErr_WriteUnraisable(yf);
342 PyErr_Clear();
Yury Selivanoveb636452016-09-08 22:01:51 -0700343 }
344 else {
Victor Stinner3466bde2016-09-05 18:16:01 -0700345 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200346 Py_DECREF(meth);
347 if (retval == NULL)
348 return -1;
349 }
350 }
351 Py_XDECREF(retval);
352 return 0;
353}
354
Yury Selivanovc724bae2016-03-02 11:30:46 -0500355PyObject *
356_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500357{
Antoine Pitrou93963562013-05-14 20:37:52 +0200358 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500359 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200360
361 if (f && f->f_stacktop) {
362 PyObject *bytecode = f->f_code->co_code;
363 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
364
Serhiy Storchakaab874002016-09-11 13:48:15 +0300365 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200366 return NULL;
367 yf = f->f_stacktop[-1];
368 Py_INCREF(yf);
369 }
370
371 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500372}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000373
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000374static PyObject *
375gen_close(PyGenObject *gen, PyObject *args)
376{
Antoine Pitrou93963562013-05-14 20:37:52 +0200377 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500378 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200379 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000380
Antoine Pitrou93963562013-05-14 20:37:52 +0200381 if (yf) {
382 gen->gi_running = 1;
383 err = gen_close_iter(yf);
384 gen->gi_running = 0;
385 Py_DECREF(yf);
386 }
387 if (err == 0)
388 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500389 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200390 if (retval) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400391 char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700392 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400393 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700394 } else if (PyAsyncGen_CheckExact(gen)) {
395 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
396 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200397 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400398 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 return NULL;
400 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200401 if (PyErr_ExceptionMatches(PyExc_StopIteration)
402 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
403 PyErr_Clear(); /* ignore these errors */
404 Py_INCREF(Py_None);
405 return Py_None;
406 }
407 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000408}
409
Antoine Pitrou93963562013-05-14 20:37:52 +0200410
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000411PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000412"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
413return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000414
415static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700416_gen_throw(PyGenObject *gen, int close_on_genexit,
417 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000418{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500419 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000420 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000421
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000422 if (yf) {
423 PyObject *ret;
424 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700425 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
426 close_on_genexit
427 ) {
428 /* Asynchronous generators *should not* be closed right away.
429 We have to allow some awaits to work it through, hence the
430 `close_on_genexit` parameter here.
431 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500432 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200433 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500434 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000435 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000436 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500437 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 goto throw_here;
439 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700440 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
441 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500442 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700443 /* Close the generator that we are currently iterating with
444 'yield from' or awaiting on with 'await'. */
445 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
446 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500447 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000448 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700449 /* `yf` is an iterator or a coroutine-like object. */
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000450 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000451 if (meth == NULL) {
452 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
453 Py_DECREF(yf);
454 return NULL;
455 }
456 PyErr_Clear();
457 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000458 goto throw_here;
459 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500460 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700461 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500462 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000463 Py_DECREF(meth);
464 }
465 Py_DECREF(yf);
466 if (!ret) {
467 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500468 /* Pop subiterator from stack */
469 ret = *(--gen->gi_frame->f_stacktop);
470 assert(ret == yf);
471 Py_DECREF(ret);
472 /* Termination repetition of YIELD_FROM */
Serhiy Storchakaab874002016-09-11 13:48:15 +0300473 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000474 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500475 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000476 Py_DECREF(val);
477 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500478 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000479 }
480 }
481 return ret;
482 }
483
484throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* First, check the traceback argument, replacing None with
486 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400487 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400489 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 else if (tb != NULL && !PyTraceBack_Check(tb)) {
491 PyErr_SetString(PyExc_TypeError,
492 "throw() third argument must be a traceback object");
493 return NULL;
494 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 Py_INCREF(typ);
497 Py_XINCREF(val);
498 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000499
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400500 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 else if (PyExceptionInstance_Check(typ)) {
504 /* Raising an instance. The value should be a dummy. */
505 if (val && val != Py_None) {
506 PyErr_SetString(PyExc_TypeError,
507 "instance exception may not have a separate value");
508 goto failed_throw;
509 }
510 else {
511 /* Normalize to raise <class>, <instance> */
512 Py_XDECREF(val);
513 val = typ;
514 typ = PyExceptionInstance_Class(typ);
515 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200516
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400517 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200518 /* Returns NULL if there's no traceback */
519 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 }
521 }
522 else {
523 /* Not something you can raise. throw() fails. */
524 PyErr_Format(PyExc_TypeError,
525 "exceptions must be classes or instances "
526 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000527 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 goto failed_throw;
529 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500532 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000533
534failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 /* Didn't use our arguments, so restore their original refcounts */
536 Py_DECREF(typ);
537 Py_XDECREF(val);
538 Py_XDECREF(tb);
539 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000540}
541
542
543static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700544gen_throw(PyGenObject *gen, PyObject *args)
545{
546 PyObject *typ;
547 PyObject *tb = NULL;
548 PyObject *val = NULL;
549
550 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
551 return NULL;
552 }
553
554 return _gen_throw(gen, 1, typ, val, tb);
555}
556
557
558static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000559gen_iternext(PyGenObject *gen)
560{
Yury Selivanov77c96812016-02-13 17:59:05 -0500561 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000562}
563
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000564/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000565 * If StopIteration exception is set, fetches its 'value'
566 * attribute if any, otherwise sets pvalue to None.
567 *
568 * Returns 0 if no exception or StopIteration is set.
569 * If any other exception is set, returns -1 and leaves
570 * pvalue unchanged.
571 */
572
573int
Nick Coghlanc40bc092012-06-17 15:15:49 +1000574_PyGen_FetchStopIterationValue(PyObject **pvalue) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000575 PyObject *et, *ev, *tb;
576 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500577
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000578 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
579 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200580 if (ev) {
581 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300582 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200583 value = ((PyStopIterationObject *)ev)->value;
584 Py_INCREF(value);
585 Py_DECREF(ev);
586 } else if (et == PyExc_StopIteration) {
587 /* avoid normalisation and take ev as value */
588 value = ev;
589 } else {
590 /* normalisation required */
591 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300592 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200593 PyErr_Restore(et, ev, tb);
594 return -1;
595 }
596 value = ((PyStopIterationObject *)ev)->value;
597 Py_INCREF(value);
598 Py_DECREF(ev);
599 }
600 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000601 Py_XDECREF(et);
602 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000603 } else if (PyErr_Occurred()) {
604 return -1;
605 }
606 if (value == NULL) {
607 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100608 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000609 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000610 *pvalue = value;
611 return 0;
612}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000613
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000614static PyObject *
615gen_repr(PyGenObject *gen)
616{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400617 return PyUnicode_FromFormat("<generator object %S at %p>",
618 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000619}
620
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000621static PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200622gen_get_name(PyGenObject *op)
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000623{
Victor Stinner40ee3012014-06-16 15:59:28 +0200624 Py_INCREF(op->gi_name);
625 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000626}
627
Victor Stinner40ee3012014-06-16 15:59:28 +0200628static int
629gen_set_name(PyGenObject *op, PyObject *value)
630{
Victor Stinner40ee3012014-06-16 15:59:28 +0200631 /* Not legal to del gen.gi_name or to set it to anything
632 * other than a string object. */
633 if (value == NULL || !PyUnicode_Check(value)) {
634 PyErr_SetString(PyExc_TypeError,
635 "__name__ must be set to a string object");
636 return -1;
637 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200638 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300639 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200640 return 0;
641}
642
643static PyObject *
644gen_get_qualname(PyGenObject *op)
645{
646 Py_INCREF(op->gi_qualname);
647 return op->gi_qualname;
648}
649
650static int
651gen_set_qualname(PyGenObject *op, PyObject *value)
652{
Victor Stinner40ee3012014-06-16 15:59:28 +0200653 /* Not legal to del gen.__qualname__ or to set it to anything
654 * other than a string object. */
655 if (value == NULL || !PyUnicode_Check(value)) {
656 PyErr_SetString(PyExc_TypeError,
657 "__qualname__ must be set to a string object");
658 return -1;
659 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200660 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300661 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200662 return 0;
663}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000664
Yury Selivanove13f8f32015-07-03 00:23:30 -0400665static PyObject *
666gen_getyieldfrom(PyGenObject *gen)
667{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500668 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400669 if (yf == NULL)
670 Py_RETURN_NONE;
671 return yf;
672}
673
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000674static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200675 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
676 PyDoc_STR("name of the generator")},
677 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
678 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400679 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
680 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200681 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000682};
683
Martin v. Löwise440e472004-06-01 15:22:42 +0000684static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200685 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
686 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
687 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000689};
690
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000691static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500692 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
694 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
695 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000696};
697
Martin v. Löwise440e472004-06-01 15:22:42 +0000698PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyVarObject_HEAD_INIT(&PyType_Type, 0)
700 "generator", /* tp_name */
701 sizeof(PyGenObject), /* tp_basicsize */
702 0, /* tp_itemsize */
703 /* methods */
704 (destructor)gen_dealloc, /* tp_dealloc */
705 0, /* tp_print */
706 0, /* tp_getattr */
707 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400708 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 (reprfunc)gen_repr, /* tp_repr */
710 0, /* tp_as_number */
711 0, /* tp_as_sequence */
712 0, /* tp_as_mapping */
713 0, /* tp_hash */
714 0, /* tp_call */
715 0, /* tp_str */
716 PyObject_GenericGetAttr, /* tp_getattro */
717 0, /* tp_setattro */
718 0, /* tp_as_buffer */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200719 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
720 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 0, /* tp_doc */
722 (traverseproc)gen_traverse, /* tp_traverse */
723 0, /* tp_clear */
724 0, /* tp_richcompare */
725 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400726 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 (iternextfunc)gen_iternext, /* tp_iternext */
728 gen_methods, /* tp_methods */
729 gen_memberlist, /* tp_members */
730 gen_getsetlist, /* tp_getset */
731 0, /* tp_base */
732 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 0, /* tp_descr_get */
735 0, /* tp_descr_set */
736 0, /* tp_dictoffset */
737 0, /* tp_init */
738 0, /* tp_alloc */
739 0, /* tp_new */
740 0, /* tp_free */
741 0, /* tp_is_gc */
742 0, /* tp_bases */
743 0, /* tp_mro */
744 0, /* tp_cache */
745 0, /* tp_subclasses */
746 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200747 0, /* tp_del */
748 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200749 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000750};
751
Yury Selivanov5376ba92015-06-22 12:19:30 -0400752static PyObject *
753gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
754 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000755{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400756 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (gen == NULL) {
758 Py_DECREF(f);
759 return NULL;
760 }
761 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200762 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 Py_INCREF(f->f_code);
764 gen->gi_code = (PyObject *)(f->f_code);
765 gen->gi_running = 0;
766 gen->gi_weakreflist = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200767 if (name != NULL)
768 gen->gi_name = name;
769 else
770 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
771 Py_INCREF(gen->gi_name);
772 if (qualname != NULL)
773 gen->gi_qualname = qualname;
774 else
775 gen->gi_qualname = gen->gi_name;
776 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 _PyObject_GC_TRACK(gen);
778 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000779}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000780
Victor Stinner40ee3012014-06-16 15:59:28 +0200781PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400782PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
783{
784 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
785}
786
787PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200788PyGen_New(PyFrameObject *f)
789{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400790 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200791}
792
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000793int
794PyGen_NeedsFinalizing(PyGenObject *gen)
795{
Antoine Pitrou93963562013-05-14 20:37:52 +0200796 int i;
797 PyFrameObject *f = gen->gi_frame;
798
799 if (f == NULL || f->f_stacktop == NULL)
800 return 0; /* no frame or empty blockstack == no finalization */
801
802 /* Any block type besides a loop requires cleanup. */
803 for (i = 0; i < f->f_iblock; i++)
804 if (f->f_blockstack[i].b_type != SETUP_LOOP)
805 return 1;
806
807 /* No blocks except loops, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809}
Yury Selivanov75445082015-05-11 22:57:16 -0400810
Yury Selivanov5376ba92015-06-22 12:19:30 -0400811/* Coroutine Object */
812
813typedef struct {
814 PyObject_HEAD
815 PyCoroObject *cw_coroutine;
816} PyCoroWrapper;
817
818static int
819gen_is_coroutine(PyObject *o)
820{
821 if (PyGen_CheckExact(o)) {
822 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
823 if (code->co_flags & CO_ITERABLE_COROUTINE) {
824 return 1;
825 }
826 }
827 return 0;
828}
829
Yury Selivanov75445082015-05-11 22:57:16 -0400830/*
831 * This helper function returns an awaitable for `o`:
832 * - `o` if `o` is a coroutine-object;
833 * - `type(o)->tp_as_async->am_await(o)`
834 *
835 * Raises a TypeError if it's not possible to return
836 * an awaitable and returns NULL.
837 */
838PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400839_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400840{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400841 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400842 PyTypeObject *ot;
843
Yury Selivanov5376ba92015-06-22 12:19:30 -0400844 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
845 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400846 Py_INCREF(o);
847 return o;
848 }
849
850 ot = Py_TYPE(o);
851 if (ot->tp_as_async != NULL) {
852 getter = ot->tp_as_async->am_await;
853 }
854 if (getter != NULL) {
855 PyObject *res = (*getter)(o);
856 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400857 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
858 /* __await__ must return an *iterator*, not
859 a coroutine or another awaitable (see PEP 492) */
860 PyErr_SetString(PyExc_TypeError,
861 "__await__() returned a coroutine");
862 Py_CLEAR(res);
863 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400864 PyErr_Format(PyExc_TypeError,
865 "__await__() returned non-iterator "
866 "of type '%.100s'",
867 Py_TYPE(res)->tp_name);
868 Py_CLEAR(res);
869 }
Yury Selivanov75445082015-05-11 22:57:16 -0400870 }
871 return res;
872 }
873
874 PyErr_Format(PyExc_TypeError,
875 "object %.100s can't be used in 'await' expression",
876 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400877 return NULL;
878}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400879
880static PyObject *
881coro_repr(PyCoroObject *coro)
882{
883 return PyUnicode_FromFormat("<coroutine object %S at %p>",
884 coro->cr_qualname, coro);
885}
886
887static PyObject *
888coro_await(PyCoroObject *coro)
889{
890 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
891 if (cw == NULL) {
892 return NULL;
893 }
894 Py_INCREF(coro);
895 cw->cw_coroutine = coro;
896 _PyObject_GC_TRACK(cw);
897 return (PyObject *)cw;
898}
899
Yury Selivanove13f8f32015-07-03 00:23:30 -0400900static PyObject *
901coro_get_cr_await(PyCoroObject *coro)
902{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500903 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400904 if (yf == NULL)
905 Py_RETURN_NONE;
906 return yf;
907}
908
Yury Selivanov5376ba92015-06-22 12:19:30 -0400909static PyGetSetDef coro_getsetlist[] = {
910 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
911 PyDoc_STR("name of the coroutine")},
912 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
913 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400914 {"cr_await", (getter)coro_get_cr_await, NULL,
915 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400916 {NULL} /* Sentinel */
917};
918
919static PyMemberDef coro_memberlist[] = {
920 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
921 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
922 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
923 {NULL} /* Sentinel */
924};
925
926PyDoc_STRVAR(coro_send_doc,
927"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400928return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400929
930PyDoc_STRVAR(coro_throw_doc,
931"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400932return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400933
934PyDoc_STRVAR(coro_close_doc,
935"close() -> raise GeneratorExit inside coroutine.");
936
937static PyMethodDef coro_methods[] = {
938 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
939 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
940 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
941 {NULL, NULL} /* Sentinel */
942};
943
944static PyAsyncMethods coro_as_async = {
945 (unaryfunc)coro_await, /* am_await */
946 0, /* am_aiter */
947 0 /* am_anext */
948};
949
950PyTypeObject PyCoro_Type = {
951 PyVarObject_HEAD_INIT(&PyType_Type, 0)
952 "coroutine", /* tp_name */
953 sizeof(PyCoroObject), /* tp_basicsize */
954 0, /* tp_itemsize */
955 /* methods */
956 (destructor)gen_dealloc, /* tp_dealloc */
957 0, /* tp_print */
958 0, /* tp_getattr */
959 0, /* tp_setattr */
960 &coro_as_async, /* tp_as_async */
961 (reprfunc)coro_repr, /* tp_repr */
962 0, /* tp_as_number */
963 0, /* tp_as_sequence */
964 0, /* tp_as_mapping */
965 0, /* tp_hash */
966 0, /* tp_call */
967 0, /* tp_str */
968 PyObject_GenericGetAttr, /* tp_getattro */
969 0, /* tp_setattro */
970 0, /* tp_as_buffer */
971 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
972 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
973 0, /* tp_doc */
974 (traverseproc)gen_traverse, /* tp_traverse */
975 0, /* tp_clear */
976 0, /* tp_richcompare */
977 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
978 0, /* tp_iter */
979 0, /* tp_iternext */
980 coro_methods, /* tp_methods */
981 coro_memberlist, /* tp_members */
982 coro_getsetlist, /* tp_getset */
983 0, /* tp_base */
984 0, /* tp_dict */
985 0, /* tp_descr_get */
986 0, /* tp_descr_set */
987 0, /* tp_dictoffset */
988 0, /* tp_init */
989 0, /* tp_alloc */
990 0, /* tp_new */
991 0, /* tp_free */
992 0, /* tp_is_gc */
993 0, /* tp_bases */
994 0, /* tp_mro */
995 0, /* tp_cache */
996 0, /* tp_subclasses */
997 0, /* tp_weaklist */
998 0, /* tp_del */
999 0, /* tp_version_tag */
1000 _PyGen_Finalize, /* tp_finalize */
1001};
1002
1003static void
1004coro_wrapper_dealloc(PyCoroWrapper *cw)
1005{
1006 _PyObject_GC_UNTRACK((PyObject *)cw);
1007 Py_CLEAR(cw->cw_coroutine);
1008 PyObject_GC_Del(cw);
1009}
1010
1011static PyObject *
1012coro_wrapper_iternext(PyCoroWrapper *cw)
1013{
Yury Selivanov77c96812016-02-13 17:59:05 -05001014 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001015}
1016
1017static PyObject *
1018coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1019{
Yury Selivanov77c96812016-02-13 17:59:05 -05001020 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001021}
1022
1023static PyObject *
1024coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1025{
1026 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1027}
1028
1029static PyObject *
1030coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1031{
1032 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1033}
1034
1035static int
1036coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1037{
1038 Py_VISIT((PyObject *)cw->cw_coroutine);
1039 return 0;
1040}
1041
1042static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001043 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1044 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1045 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001046 {NULL, NULL} /* Sentinel */
1047};
1048
1049PyTypeObject _PyCoroWrapper_Type = {
1050 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1051 "coroutine_wrapper",
1052 sizeof(PyCoroWrapper), /* tp_basicsize */
1053 0, /* tp_itemsize */
1054 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
1055 0, /* tp_print */
1056 0, /* tp_getattr */
1057 0, /* tp_setattr */
1058 0, /* tp_as_async */
1059 0, /* tp_repr */
1060 0, /* tp_as_number */
1061 0, /* tp_as_sequence */
1062 0, /* tp_as_mapping */
1063 0, /* tp_hash */
1064 0, /* tp_call */
1065 0, /* tp_str */
1066 PyObject_GenericGetAttr, /* tp_getattro */
1067 0, /* tp_setattro */
1068 0, /* tp_as_buffer */
1069 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1070 "A wrapper object implementing __await__ for coroutines.",
1071 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1072 0, /* tp_clear */
1073 0, /* tp_richcompare */
1074 0, /* tp_weaklistoffset */
1075 PyObject_SelfIter, /* tp_iter */
1076 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1077 coro_wrapper_methods, /* tp_methods */
1078 0, /* tp_members */
1079 0, /* tp_getset */
1080 0, /* tp_base */
1081 0, /* tp_dict */
1082 0, /* tp_descr_get */
1083 0, /* tp_descr_set */
1084 0, /* tp_dictoffset */
1085 0, /* tp_init */
1086 0, /* tp_alloc */
1087 0, /* tp_new */
1088 PyObject_Del, /* tp_free */
1089};
1090
1091PyObject *
1092PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1093{
1094 return gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1095}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001096
1097
1098/* __aiter__ wrapper; see http://bugs.python.org/issue27243 for details. */
1099
1100typedef struct {
1101 PyObject_HEAD
Yury Selivanoveb636452016-09-08 22:01:51 -07001102 PyObject *ags_aiter;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001103} PyAIterWrapper;
1104
1105
1106static PyObject *
1107aiter_wrapper_iternext(PyAIterWrapper *aw)
1108{
Yury Selivanoveb636452016-09-08 22:01:51 -07001109 PyErr_SetObject(PyExc_StopIteration, aw->ags_aiter);
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001110 return NULL;
1111}
1112
1113static int
1114aiter_wrapper_traverse(PyAIterWrapper *aw, visitproc visit, void *arg)
1115{
Yury Selivanoveb636452016-09-08 22:01:51 -07001116 Py_VISIT((PyObject *)aw->ags_aiter);
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001117 return 0;
1118}
1119
1120static void
1121aiter_wrapper_dealloc(PyAIterWrapper *aw)
1122{
1123 _PyObject_GC_UNTRACK((PyObject *)aw);
Yury Selivanoveb636452016-09-08 22:01:51 -07001124 Py_CLEAR(aw->ags_aiter);
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001125 PyObject_GC_Del(aw);
1126}
1127
1128static PyAsyncMethods aiter_wrapper_as_async = {
1129 PyObject_SelfIter, /* am_await */
1130 0, /* am_aiter */
1131 0 /* am_anext */
1132};
1133
1134PyTypeObject _PyAIterWrapper_Type = {
1135 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1136 "aiter_wrapper",
1137 sizeof(PyAIterWrapper), /* tp_basicsize */
1138 0, /* tp_itemsize */
1139 (destructor)aiter_wrapper_dealloc, /* destructor tp_dealloc */
1140 0, /* tp_print */
1141 0, /* tp_getattr */
1142 0, /* tp_setattr */
1143 &aiter_wrapper_as_async, /* tp_as_async */
1144 0, /* tp_repr */
1145 0, /* tp_as_number */
1146 0, /* tp_as_sequence */
1147 0, /* tp_as_mapping */
1148 0, /* tp_hash */
1149 0, /* tp_call */
1150 0, /* tp_str */
1151 PyObject_GenericGetAttr, /* tp_getattro */
1152 0, /* tp_setattro */
1153 0, /* tp_as_buffer */
1154 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1155 "A wrapper object for __aiter__ bakwards compatibility.",
1156 (traverseproc)aiter_wrapper_traverse, /* tp_traverse */
1157 0, /* tp_clear */
1158 0, /* tp_richcompare */
1159 0, /* tp_weaklistoffset */
1160 PyObject_SelfIter, /* tp_iter */
1161 (iternextfunc)aiter_wrapper_iternext, /* tp_iternext */
1162 0, /* tp_methods */
1163 0, /* tp_members */
1164 0, /* tp_getset */
1165 0, /* tp_base */
1166 0, /* tp_dict */
1167 0, /* tp_descr_get */
1168 0, /* tp_descr_set */
1169 0, /* tp_dictoffset */
1170 0, /* tp_init */
1171 0, /* tp_alloc */
1172 0, /* tp_new */
1173 PyObject_Del, /* tp_free */
1174};
1175
1176
1177PyObject *
1178_PyAIterWrapper_New(PyObject *aiter)
1179{
1180 PyAIterWrapper *aw = PyObject_GC_New(PyAIterWrapper,
1181 &_PyAIterWrapper_Type);
1182 if (aw == NULL) {
1183 return NULL;
1184 }
1185 Py_INCREF(aiter);
Yury Selivanoveb636452016-09-08 22:01:51 -07001186 aw->ags_aiter = aiter;
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001187 _PyObject_GC_TRACK(aw);
1188 return (PyObject *)aw;
1189}
Yury Selivanoveb636452016-09-08 22:01:51 -07001190
1191
1192/* ========= Asynchronous Generators ========= */
1193
1194
1195typedef enum {
1196 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1197 AWAITABLE_STATE_ITER, /* being iterated */
1198 AWAITABLE_STATE_CLOSED, /* closed */
1199} AwaitableState;
1200
1201
1202typedef struct {
1203 PyObject_HEAD
1204 PyAsyncGenObject *ags_gen;
1205
1206 /* Can be NULL, when in the __anext__() mode
1207 (equivalent of "asend(None)") */
1208 PyObject *ags_sendval;
1209
1210 AwaitableState ags_state;
1211} PyAsyncGenASend;
1212
1213
1214typedef struct {
1215 PyObject_HEAD
1216 PyAsyncGenObject *agt_gen;
1217
1218 /* Can be NULL, when in the "aclose()" mode
1219 (equivalent of "athrow(GeneratorExit)") */
1220 PyObject *agt_args;
1221
1222 AwaitableState agt_state;
1223} PyAsyncGenAThrow;
1224
1225
1226typedef struct {
1227 PyObject_HEAD
1228 PyObject *agw_val;
1229} _PyAsyncGenWrappedValue;
1230
1231
1232#ifndef _PyAsyncGen_MAXFREELIST
1233#define _PyAsyncGen_MAXFREELIST 80
1234#endif
1235
1236/* Freelists boost performance 6-10%; they also reduce memory
1237 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1238 are short-living objects that are instantiated for every
1239 __anext__ call.
1240*/
1241
1242static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1243static int ag_value_freelist_free = 0;
1244
1245static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1246static int ag_asend_freelist_free = 0;
1247
1248#define _PyAsyncGenWrappedValue_CheckExact(o) \
1249 (Py_TYPE(o) == &_PyAsyncGenWrappedValue_Type)
1250
1251#define PyAsyncGenASend_CheckExact(o) \
1252 (Py_TYPE(o) == &_PyAsyncGenASend_Type)
1253
1254
1255static int
1256async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1257{
1258 Py_VISIT(gen->ag_finalizer);
1259 return gen_traverse((PyGenObject*)gen, visit, arg);
1260}
1261
1262
1263static PyObject *
1264async_gen_repr(PyAsyncGenObject *o)
1265{
1266 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1267 o->ag_qualname, o);
1268}
1269
1270
1271static int
1272async_gen_init_hooks(PyAsyncGenObject *o)
1273{
1274 PyThreadState *tstate;
1275 PyObject *finalizer;
1276 PyObject *firstiter;
1277
1278 if (o->ag_hooks_inited) {
1279 return 0;
1280 }
1281
1282 o->ag_hooks_inited = 1;
1283
1284 tstate = PyThreadState_GET();
1285
1286 finalizer = tstate->async_gen_finalizer;
1287 if (finalizer) {
1288 Py_INCREF(finalizer);
1289 o->ag_finalizer = finalizer;
1290 }
1291
1292 firstiter = tstate->async_gen_firstiter;
1293 if (firstiter) {
1294 PyObject *res;
1295
1296 Py_INCREF(firstiter);
1297 res = PyObject_CallFunction(firstiter, "O", o);
1298 Py_DECREF(firstiter);
1299 if (res == NULL) {
1300 return 1;
1301 }
1302 Py_DECREF(res);
1303 }
1304
1305 return 0;
1306}
1307
1308
1309static PyObject *
1310async_gen_anext(PyAsyncGenObject *o)
1311{
1312 if (async_gen_init_hooks(o)) {
1313 return NULL;
1314 }
1315 return async_gen_asend_new(o, NULL);
1316}
1317
1318
1319static PyObject *
1320async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1321{
1322 if (async_gen_init_hooks(o)) {
1323 return NULL;
1324 }
1325 return async_gen_asend_new(o, arg);
1326}
1327
1328
1329static PyObject *
1330async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1331{
1332 if (async_gen_init_hooks(o)) {
1333 return NULL;
1334 }
1335 return async_gen_athrow_new(o, NULL);
1336}
1337
1338static PyObject *
1339async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1340{
1341 if (async_gen_init_hooks(o)) {
1342 return NULL;
1343 }
1344 return async_gen_athrow_new(o, args);
1345}
1346
1347
1348static PyGetSetDef async_gen_getsetlist[] = {
1349 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1350 PyDoc_STR("name of the async generator")},
1351 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1352 PyDoc_STR("qualified name of the async generator")},
1353 {"ag_await", (getter)coro_get_cr_await, NULL,
1354 PyDoc_STR("object being awaited on, or None")},
1355 {NULL} /* Sentinel */
1356};
1357
1358static PyMemberDef async_gen_memberlist[] = {
1359 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
1360 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running), READONLY},
1361 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1362 {NULL} /* Sentinel */
1363};
1364
1365PyDoc_STRVAR(async_aclose_doc,
1366"aclose() -> raise GeneratorExit inside generator.");
1367
1368PyDoc_STRVAR(async_asend_doc,
1369"asend(v) -> send 'v' in generator.");
1370
1371PyDoc_STRVAR(async_athrow_doc,
1372"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1373
1374static PyMethodDef async_gen_methods[] = {
1375 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1376 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1377 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
1378 {NULL, NULL} /* Sentinel */
1379};
1380
1381
1382static PyAsyncMethods async_gen_as_async = {
1383 0, /* am_await */
1384 PyObject_SelfIter, /* am_aiter */
1385 (unaryfunc)async_gen_anext /* am_anext */
1386};
1387
1388
1389PyTypeObject PyAsyncGen_Type = {
1390 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1391 "async_generator", /* tp_name */
1392 sizeof(PyAsyncGenObject), /* tp_basicsize */
1393 0, /* tp_itemsize */
1394 /* methods */
1395 (destructor)gen_dealloc, /* tp_dealloc */
1396 0, /* tp_print */
1397 0, /* tp_getattr */
1398 0, /* tp_setattr */
1399 &async_gen_as_async, /* tp_as_async */
1400 (reprfunc)async_gen_repr, /* tp_repr */
1401 0, /* tp_as_number */
1402 0, /* tp_as_sequence */
1403 0, /* tp_as_mapping */
1404 0, /* tp_hash */
1405 0, /* tp_call */
1406 0, /* tp_str */
1407 PyObject_GenericGetAttr, /* tp_getattro */
1408 0, /* tp_setattro */
1409 0, /* tp_as_buffer */
1410 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1411 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1412 0, /* tp_doc */
1413 (traverseproc)async_gen_traverse, /* tp_traverse */
1414 0, /* tp_clear */
1415 0, /* tp_richcompare */
1416 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1417 0, /* tp_iter */
1418 0, /* tp_iternext */
1419 async_gen_methods, /* tp_methods */
1420 async_gen_memberlist, /* tp_members */
1421 async_gen_getsetlist, /* tp_getset */
1422 0, /* tp_base */
1423 0, /* tp_dict */
1424 0, /* tp_descr_get */
1425 0, /* tp_descr_set */
1426 0, /* tp_dictoffset */
1427 0, /* tp_init */
1428 0, /* tp_alloc */
1429 0, /* tp_new */
1430 0, /* tp_free */
1431 0, /* tp_is_gc */
1432 0, /* tp_bases */
1433 0, /* tp_mro */
1434 0, /* tp_cache */
1435 0, /* tp_subclasses */
1436 0, /* tp_weaklist */
1437 0, /* tp_del */
1438 0, /* tp_version_tag */
1439 _PyGen_Finalize, /* tp_finalize */
1440};
1441
1442
1443PyObject *
1444PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1445{
1446 PyAsyncGenObject *o;
1447 o = (PyAsyncGenObject *)gen_new_with_qualname(
1448 &PyAsyncGen_Type, f, name, qualname);
1449 if (o == NULL) {
1450 return NULL;
1451 }
1452 o->ag_finalizer = NULL;
1453 o->ag_closed = 0;
1454 o->ag_hooks_inited = 0;
1455 return (PyObject*)o;
1456}
1457
1458
1459int
1460PyAsyncGen_ClearFreeLists(void)
1461{
1462 int ret = ag_value_freelist_free + ag_asend_freelist_free;
1463
1464 while (ag_value_freelist_free) {
1465 _PyAsyncGenWrappedValue *o;
1466 o = ag_value_freelist[--ag_value_freelist_free];
1467 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1468 PyObject_Del(o);
1469 }
1470
1471 while (ag_asend_freelist_free) {
1472 PyAsyncGenASend *o;
1473 o = ag_asend_freelist[--ag_asend_freelist_free];
1474 assert(Py_TYPE(o) == &_PyAsyncGenASend_Type);
1475 PyObject_Del(o);
1476 }
1477
1478 return ret;
1479}
1480
1481void
1482PyAsyncGen_Fini(void)
1483{
1484 PyAsyncGen_ClearFreeLists();
1485}
1486
1487
1488static PyObject *
1489async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1490{
1491 if (result == NULL) {
1492 if (!PyErr_Occurred()) {
1493 PyErr_SetNone(PyExc_StopAsyncIteration);
1494 }
1495
1496 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1497 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1498 ) {
1499 gen->ag_closed = 1;
1500 }
1501
1502 return NULL;
1503 }
1504
1505 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1506 /* async yield */
1507 PyObject *e = PyObject_CallFunctionObjArgs(
1508 PyExc_StopIteration,
1509 ((_PyAsyncGenWrappedValue*)result)->agw_val,
1510 NULL);
1511 Py_DECREF(result);
1512 if (e == NULL) {
1513 return NULL;
1514 }
1515 PyErr_SetObject(PyExc_StopIteration, e);
1516 Py_DECREF(e);
1517 return NULL;
1518 }
1519
1520 return result;
1521}
1522
1523
1524/* ---------- Async Generator ASend Awaitable ------------ */
1525
1526
1527static void
1528async_gen_asend_dealloc(PyAsyncGenASend *o)
1529{
1530 Py_CLEAR(o->ags_gen);
1531 Py_CLEAR(o->ags_sendval);
1532 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1533 assert(PyAsyncGenASend_CheckExact(o));
1534 ag_asend_freelist[ag_asend_freelist_free++] = o;
1535 } else {
1536 PyObject_Del(o);
1537 }
1538}
1539
1540
1541static PyObject *
1542async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1543{
1544 PyObject *result;
1545
1546 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1547 PyErr_SetNone(PyExc_StopIteration);
1548 return NULL;
1549 }
1550
1551 if (o->ags_state == AWAITABLE_STATE_INIT) {
1552 if (arg == NULL || arg == Py_None) {
1553 arg = o->ags_sendval;
1554 }
1555 o->ags_state = AWAITABLE_STATE_ITER;
1556 }
1557
1558 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1559 result = async_gen_unwrap_value(o->ags_gen, result);
1560
1561 if (result == NULL) {
1562 o->ags_state = AWAITABLE_STATE_CLOSED;
1563 }
1564
1565 return result;
1566}
1567
1568
1569static PyObject *
1570async_gen_asend_iternext(PyAsyncGenASend *o)
1571{
1572 return async_gen_asend_send(o, NULL);
1573}
1574
1575
1576static PyObject *
1577async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1578{
1579 PyObject *result;
1580
1581 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1582 PyErr_SetNone(PyExc_StopIteration);
1583 return NULL;
1584 }
1585
1586 result = gen_throw((PyGenObject*)o->ags_gen, args);
1587 result = async_gen_unwrap_value(o->ags_gen, result);
1588
1589 if (result == NULL) {
1590 o->ags_state = AWAITABLE_STATE_CLOSED;
1591 }
1592
1593 return result;
1594}
1595
1596
1597static PyObject *
1598async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1599{
1600 o->ags_state = AWAITABLE_STATE_CLOSED;
1601 Py_RETURN_NONE;
1602}
1603
1604
1605static PyMethodDef async_gen_asend_methods[] = {
1606 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1607 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1608 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1609 {NULL, NULL} /* Sentinel */
1610};
1611
1612
1613static PyAsyncMethods async_gen_asend_as_async = {
1614 PyObject_SelfIter, /* am_await */
1615 0, /* am_aiter */
1616 0 /* am_anext */
1617};
1618
1619
1620PyTypeObject _PyAsyncGenASend_Type = {
1621 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1622 "async_generator_asend", /* tp_name */
1623 sizeof(PyAsyncGenASend), /* tp_basicsize */
1624 0, /* tp_itemsize */
1625 /* methods */
1626 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
1627 0, /* tp_print */
1628 0, /* tp_getattr */
1629 0, /* tp_setattr */
1630 &async_gen_asend_as_async, /* tp_as_async */
1631 0, /* tp_repr */
1632 0, /* tp_as_number */
1633 0, /* tp_as_sequence */
1634 0, /* tp_as_mapping */
1635 0, /* tp_hash */
1636 0, /* tp_call */
1637 0, /* tp_str */
1638 PyObject_GenericGetAttr, /* tp_getattro */
1639 0, /* tp_setattro */
1640 0, /* tp_as_buffer */
1641 Py_TPFLAGS_DEFAULT, /* tp_flags */
1642 0, /* tp_doc */
1643 0, /* tp_traverse */
1644 0, /* tp_clear */
1645 0, /* tp_richcompare */
1646 0, /* tp_weaklistoffset */
1647 PyObject_SelfIter, /* tp_iter */
1648 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1649 async_gen_asend_methods, /* tp_methods */
1650 0, /* tp_members */
1651 0, /* tp_getset */
1652 0, /* tp_base */
1653 0, /* tp_dict */
1654 0, /* tp_descr_get */
1655 0, /* tp_descr_set */
1656 0, /* tp_dictoffset */
1657 0, /* tp_init */
1658 0, /* tp_alloc */
1659 0, /* tp_new */
1660};
1661
1662
1663static PyObject *
1664async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1665{
1666 PyAsyncGenASend *o;
1667 if (ag_asend_freelist_free) {
1668 ag_asend_freelist_free--;
1669 o = ag_asend_freelist[ag_asend_freelist_free];
1670 _Py_NewReference((PyObject *)o);
1671 } else {
1672 o = PyObject_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
1673 if (o == NULL) {
1674 return NULL;
1675 }
1676 }
1677
1678 Py_INCREF(gen);
1679 o->ags_gen = gen;
1680
1681 Py_XINCREF(sendval);
1682 o->ags_sendval = sendval;
1683
1684 o->ags_state = AWAITABLE_STATE_INIT;
1685 return (PyObject*)o;
1686}
1687
1688
1689/* ---------- Async Generator Value Wrapper ------------ */
1690
1691
1692static void
1693async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1694{
1695 Py_CLEAR(o->agw_val);
1696 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1697 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1698 ag_value_freelist[ag_value_freelist_free++] = o;
1699 } else {
1700 PyObject_Del(o);
1701 }
1702}
1703
1704
1705PyTypeObject _PyAsyncGenWrappedValue_Type = {
1706 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1707 "async_generator_wrapped_value", /* tp_name */
1708 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1709 0, /* tp_itemsize */
1710 /* methods */
1711 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
1712 0, /* tp_print */
1713 0, /* tp_getattr */
1714 0, /* tp_setattr */
1715 0, /* tp_as_async */
1716 0, /* tp_repr */
1717 0, /* tp_as_number */
1718 0, /* tp_as_sequence */
1719 0, /* tp_as_mapping */
1720 0, /* tp_hash */
1721 0, /* tp_call */
1722 0, /* tp_str */
1723 PyObject_GenericGetAttr, /* tp_getattro */
1724 0, /* tp_setattro */
1725 0, /* tp_as_buffer */
1726 Py_TPFLAGS_DEFAULT, /* tp_flags */
1727 0, /* tp_doc */
1728 0, /* tp_traverse */
1729 0, /* tp_clear */
1730 0, /* tp_richcompare */
1731 0, /* tp_weaklistoffset */
1732 0, /* tp_iter */
1733 0, /* tp_iternext */
1734 0, /* tp_methods */
1735 0, /* tp_members */
1736 0, /* tp_getset */
1737 0, /* tp_base */
1738 0, /* tp_dict */
1739 0, /* tp_descr_get */
1740 0, /* tp_descr_set */
1741 0, /* tp_dictoffset */
1742 0, /* tp_init */
1743 0, /* tp_alloc */
1744 0, /* tp_new */
1745};
1746
1747
1748PyObject *
1749_PyAsyncGenValueWrapperNew(PyObject *val)
1750{
1751 _PyAsyncGenWrappedValue *o;
1752 assert(val);
1753
1754 if (ag_value_freelist_free) {
1755 ag_value_freelist_free--;
1756 o = ag_value_freelist[ag_value_freelist_free];
1757 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1758 _Py_NewReference((PyObject*)o);
1759 } else {
1760 o = PyObject_New(_PyAsyncGenWrappedValue, &_PyAsyncGenWrappedValue_Type);
1761 if (o == NULL) {
1762 return NULL;
1763 }
1764 }
1765 o->agw_val = val;
1766 Py_INCREF(val);
1767 return (PyObject*)o;
1768}
1769
1770
1771/* ---------- Async Generator AThrow awaitable ------------ */
1772
1773
1774static void
1775async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1776{
1777 Py_CLEAR(o->agt_gen);
1778 Py_CLEAR(o->agt_args);
1779 PyObject_Del(o);
1780}
1781
1782
1783static PyObject *
1784async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1785{
1786 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1787 PyFrameObject *f = gen->gi_frame;
1788 PyObject *retval;
1789
1790 if (f == NULL || f->f_stacktop == NULL ||
1791 o->agt_state == AWAITABLE_STATE_CLOSED) {
1792 PyErr_SetNone(PyExc_StopIteration);
1793 return NULL;
1794 }
1795
1796 if (o->agt_state == AWAITABLE_STATE_INIT) {
1797 if (o->agt_gen->ag_closed) {
1798 PyErr_SetNone(PyExc_StopIteration);
1799 return NULL;
1800 }
1801
1802 if (arg != Py_None) {
1803 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1804 return NULL;
1805 }
1806
1807 o->agt_state = AWAITABLE_STATE_ITER;
1808
1809 if (o->agt_args == NULL) {
1810 /* aclose() mode */
1811 o->agt_gen->ag_closed = 1;
1812
1813 retval = _gen_throw((PyGenObject *)gen,
1814 0, /* Do not close generator when
1815 PyExc_GeneratorExit is passed */
1816 PyExc_GeneratorExit, NULL, NULL);
1817
1818 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1819 Py_DECREF(retval);
1820 goto yield_close;
1821 }
1822 } else {
1823 PyObject *typ;
1824 PyObject *tb = NULL;
1825 PyObject *val = NULL;
1826
1827 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1828 &typ, &val, &tb)) {
1829 return NULL;
1830 }
1831
1832 retval = _gen_throw((PyGenObject *)gen,
1833 0, /* Do not close generator when
1834 PyExc_GeneratorExit is passed */
1835 typ, val, tb);
1836 retval = async_gen_unwrap_value(o->agt_gen, retval);
1837 }
1838 if (retval == NULL) {
1839 goto check_error;
1840 }
1841 return retval;
1842 }
1843
1844 assert(o->agt_state == AWAITABLE_STATE_ITER);
1845
1846 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1847 if (o->agt_args) {
1848 return async_gen_unwrap_value(o->agt_gen, retval);
1849 } else {
1850 /* aclose() mode */
1851 if (retval) {
1852 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1853 Py_DECREF(retval);
1854 goto yield_close;
1855 }
1856 else {
1857 return retval;
1858 }
1859 }
1860 else {
1861 goto check_error;
1862 }
1863 }
1864
1865yield_close:
1866 PyErr_SetString(
1867 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1868 return NULL;
1869
1870check_error:
1871 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1872 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1873 ) {
1874 o->agt_state = AWAITABLE_STATE_CLOSED;
1875 PyErr_Clear(); /* ignore these errors */
1876 PyErr_SetNone(PyExc_StopIteration);
1877 }
1878 return NULL;
1879}
1880
1881
1882static PyObject *
1883async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1884{
1885 PyObject *retval;
1886
1887 if (o->agt_state == AWAITABLE_STATE_INIT) {
1888 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1889 return NULL;
1890 }
1891
1892 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
1893 PyErr_SetNone(PyExc_StopIteration);
1894 return NULL;
1895 }
1896
1897 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1898 if (o->agt_args) {
1899 return async_gen_unwrap_value(o->agt_gen, retval);
1900 } else {
1901 /* aclose() mode */
1902 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1903 Py_DECREF(retval);
1904 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1905 return NULL;
1906 }
1907 return retval;
1908 }
1909}
1910
1911
1912static PyObject *
1913async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1914{
1915 return async_gen_athrow_send(o, Py_None);
1916}
1917
1918
1919static PyObject *
1920async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1921{
1922 o->agt_state = AWAITABLE_STATE_CLOSED;
1923 Py_RETURN_NONE;
1924}
1925
1926
1927static PyMethodDef async_gen_athrow_methods[] = {
1928 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1929 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1930 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1931 {NULL, NULL} /* Sentinel */
1932};
1933
1934
1935static PyAsyncMethods async_gen_athrow_as_async = {
1936 PyObject_SelfIter, /* am_await */
1937 0, /* am_aiter */
1938 0 /* am_anext */
1939};
1940
1941
1942PyTypeObject _PyAsyncGenAThrow_Type = {
1943 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1944 "async_generator_athrow", /* tp_name */
1945 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1946 0, /* tp_itemsize */
1947 /* methods */
1948 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
1949 0, /* tp_print */
1950 0, /* tp_getattr */
1951 0, /* tp_setattr */
1952 &async_gen_athrow_as_async, /* tp_as_async */
1953 0, /* tp_repr */
1954 0, /* tp_as_number */
1955 0, /* tp_as_sequence */
1956 0, /* tp_as_mapping */
1957 0, /* tp_hash */
1958 0, /* tp_call */
1959 0, /* tp_str */
1960 PyObject_GenericGetAttr, /* tp_getattro */
1961 0, /* tp_setattro */
1962 0, /* tp_as_buffer */
1963 Py_TPFLAGS_DEFAULT, /* tp_flags */
1964 0, /* tp_doc */
1965 0, /* tp_traverse */
1966 0, /* tp_clear */
1967 0, /* tp_richcompare */
1968 0, /* tp_weaklistoffset */
1969 PyObject_SelfIter, /* tp_iter */
1970 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
1971 async_gen_athrow_methods, /* tp_methods */
1972 0, /* tp_members */
1973 0, /* tp_getset */
1974 0, /* tp_base */
1975 0, /* tp_dict */
1976 0, /* tp_descr_get */
1977 0, /* tp_descr_set */
1978 0, /* tp_dictoffset */
1979 0, /* tp_init */
1980 0, /* tp_alloc */
1981 0, /* tp_new */
1982};
1983
1984
1985static PyObject *
1986async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
1987{
1988 PyAsyncGenAThrow *o;
1989 o = PyObject_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
1990 if (o == NULL) {
1991 return NULL;
1992 }
1993 o->agt_gen = gen;
1994 o->agt_args = args;
1995 o->agt_state = AWAITABLE_STATE_INIT;
1996 Py_INCREF(gen);
1997 Py_XINCREF(args);
1998 return (PyObject*)o;
1999}