blob: 5d5798c2f48dfe9c670297edd3f358cb15f19848 [file] [log] [blame]
Martin v. Löwise440e472004-06-01 15:22:42 +00001/* Generator object implementation */
2
3#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06004#include "internal/pystate.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
Martin v. Löwise440e472004-06-01 15:22:42 +000019static int
20gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
21{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 Py_VISIT((PyObject *)gen->gi_frame);
23 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020024 Py_VISIT(gen->gi_name);
25 Py_VISIT(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000027}
28
Antoine Pitrou58720d62013-08-05 23:26:40 +020029void
30_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020031{
32 PyGenObject *gen = (PyGenObject *)self;
Benjamin Petersonb88db872016-09-07 08:46:59 -070033 PyObject *res = NULL;
Antoine Pitrou796564c2013-07-30 19:59:21 +020034 PyObject *error_type, *error_value, *error_traceback;
35
36 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
37 /* Generator isn't paused, so no need to close */
38 return;
39
Yury Selivanoveb636452016-09-08 22:01:51 -070040 if (PyAsyncGen_CheckExact(self)) {
41 PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
42 PyObject *finalizer = agen->ag_finalizer;
43 if (finalizer && !agen->ag_closed) {
44 /* Save the current exception, if any. */
45 PyErr_Fetch(&error_type, &error_value, &error_traceback);
46
Victor Stinnerde4ae3d2016-12-04 22:59:09 +010047 res = PyObject_CallFunctionObjArgs(finalizer, self, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -070048
49 if (res == NULL) {
50 PyErr_WriteUnraisable(self);
51 } else {
52 Py_DECREF(res);
53 }
54 /* Restore the saved exception. */
55 PyErr_Restore(error_type, error_value, error_traceback);
56 return;
57 }
58 }
59
Antoine Pitrou796564c2013-07-30 19:59:21 +020060 /* Save the current exception, if any. */
61 PyErr_Fetch(&error_type, &error_value, &error_traceback);
62
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070063 /* If `gen` is a coroutine, and if it was never awaited on,
64 issue a RuntimeWarning. */
Benjamin Petersonb88db872016-09-07 08:46:59 -070065 if (gen->gi_code != NULL &&
66 ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
67 gen->gi_frame->f_lasti == -1) {
68 if (!error_value) {
69 PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
70 "coroutine '%.50S' was never awaited",
71 gen->gi_qualname);
72 }
Benjamin Peterson2f40ed42016-09-05 10:14:54 -070073 }
74 else {
75 res = gen_close(gen, NULL);
76 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020077
Benjamin Petersonb88db872016-09-07 08:46:59 -070078 if (res == NULL) {
79 if (PyErr_Occurred())
80 PyErr_WriteUnraisable(self);
81 }
82 else {
Antoine Pitrou796564c2013-07-30 19:59:21 +020083 Py_DECREF(res);
Benjamin Petersonb88db872016-09-07 08:46:59 -070084 }
Antoine Pitrou796564c2013-07-30 19:59:21 +020085
86 /* Restore the saved exception. */
87 PyErr_Restore(error_type, error_value, error_traceback);
88}
89
90static void
Martin v. Löwise440e472004-06-01 15:22:42 +000091gen_dealloc(PyGenObject *gen)
92{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 if (gen->gi_weakreflist != NULL)
98 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000099
Antoine Pitrou93963562013-05-14 20:37:52 +0200100 _PyObject_GC_TRACK(self);
101
Antoine Pitrou796564c2013-07-30 19:59:21 +0200102 if (PyObject_CallFinalizerFromDealloc(self))
103 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +0200104
105 _PyObject_GC_UNTRACK(self);
Yury Selivanoveb636452016-09-08 22:01:51 -0700106 if (PyAsyncGen_CheckExact(gen)) {
107 /* We have to handle this case for asynchronous generators
108 right here, because this code has to be between UNTRACK
109 and GC_Del. */
110 Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer);
111 }
Benjamin Petersonbdddb112016-09-05 10:39:57 -0700112 if (gen->gi_frame != NULL) {
113 gen->gi_frame->f_gen = NULL;
114 Py_CLEAR(gen->gi_frame);
115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +0200117 Py_CLEAR(gen->gi_name);
118 Py_CLEAR(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +0000120}
121
122static PyObject *
Yury Selivanov77c96812016-02-13 17:59:05 -0500123gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
Martin v. Löwise440e472004-06-01 15:22:42 +0000124{
Antoine Pitrou93963562013-05-14 20:37:52 +0200125 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200127 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000128
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500129 if (gen->gi_running) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400130 char *msg = "generator already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700131 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400132 msg = "coroutine already executing";
Yury Selivanoveb636452016-09-08 22:01:51 -0700133 }
134 else if (PyAsyncGen_CheckExact(gen)) {
135 msg = "async generator already executing";
136 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400137 PyErr_SetString(PyExc_ValueError, msg);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500138 return NULL;
139 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200140 if (f == NULL || f->f_stacktop == NULL) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500141 if (PyCoro_CheckExact(gen) && !closing) {
142 /* `gen` is an exhausted coroutine: raise an error,
143 except when called from gen_close(), which should
144 always be a silent method. */
145 PyErr_SetString(
146 PyExc_RuntimeError,
147 "cannot reuse already awaited coroutine");
Yury Selivanoveb636452016-09-08 22:01:51 -0700148 }
149 else if (arg && !exc) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500150 /* `gen` is an exhausted generator:
151 only set exception if called from send(). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700152 if (PyAsyncGen_CheckExact(gen)) {
153 PyErr_SetNone(PyExc_StopAsyncIteration);
154 }
155 else {
156 PyErr_SetNone(PyExc_StopIteration);
157 }
Yury Selivanov77c96812016-02-13 17:59:05 -0500158 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 return NULL;
160 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000161
Antoine Pitrou93963562013-05-14 20:37:52 +0200162 if (f->f_lasti == -1) {
163 if (arg && arg != Py_None) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400164 char *msg = "can't send non-None value to a "
165 "just-started generator";
Yury Selivanoveb636452016-09-08 22:01:51 -0700166 if (PyCoro_CheckExact(gen)) {
167 msg = NON_INIT_CORO_MSG;
168 }
169 else if (PyAsyncGen_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400170 msg = "can't send non-None value to a "
Yury Selivanoveb636452016-09-08 22:01:51 -0700171 "just-started async generator";
172 }
Yury Selivanov5376ba92015-06-22 12:19:30 -0400173 PyErr_SetString(PyExc_TypeError, msg);
Antoine Pitrou93963562013-05-14 20:37:52 +0200174 return NULL;
175 }
176 } else {
177 /* Push arg onto the frame's value stack */
178 result = arg ? arg : Py_None;
179 Py_INCREF(result);
180 *(f->f_stacktop++) = result;
181 }
182
183 /* Generators always return to their most recent caller, not
184 * necessarily their creator. */
185 Py_XINCREF(tstate->frame);
186 assert(f->f_back == NULL);
187 f->f_back = tstate->frame;
188
189 gen->gi_running = 1;
Victor Stinner59a73272016-12-09 18:51:13 +0100190 result = PyEval_EvalFrameEx(f, exc);
Antoine Pitrou93963562013-05-14 20:37:52 +0200191 gen->gi_running = 0;
192
193 /* Don't keep the reference to f_back any longer than necessary. It
194 * may keep a chain of frames alive or it could create a reference
195 * cycle. */
196 assert(f->f_back == tstate->frame);
197 Py_CLEAR(f->f_back);
198
199 /* If the generator just returned (as opposed to yielding), signal
200 * that the generator is exhausted. */
201 if (result && f->f_stacktop == NULL) {
202 if (result == Py_None) {
203 /* Delay exception instantiation if we can */
Yury Selivanoveb636452016-09-08 22:01:51 -0700204 if (PyAsyncGen_CheckExact(gen)) {
205 PyErr_SetNone(PyExc_StopAsyncIteration);
206 }
207 else {
208 PyErr_SetNone(PyExc_StopIteration);
209 }
210 }
211 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700212 /* Async generators cannot return anything but None */
213 assert(!PyAsyncGen_CheckExact(gen));
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200214 _PyGen_SetStopIterationValue(result);
Antoine Pitrou93963562013-05-14 20:37:52 +0200215 }
216 Py_CLEAR(result);
217 }
Yury Selivanov68333392015-05-22 11:16:47 -0400218 else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400219 /* Check for __future__ generator_stop and conditionally turn
220 * a leaking StopIteration into RuntimeError (with its cause
221 * set appropriately). */
Yury Selivanoveb636452016-09-08 22:01:51 -0700222
223 const int check_stop_iter_error_flags = CO_FUTURE_GENERATOR_STOP |
224 CO_COROUTINE |
225 CO_ITERABLE_COROUTINE |
226 CO_ASYNC_GENERATOR;
227
228 if (gen->gi_code != NULL &&
229 ((PyCodeObject *)gen->gi_code)->co_flags &
230 check_stop_iter_error_flags)
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400231 {
Yury Selivanoveb636452016-09-08 22:01:51 -0700232 /* `gen` is either:
233 * a generator with CO_FUTURE_GENERATOR_STOP flag;
234 * a coroutine;
235 * a generator with CO_ITERABLE_COROUTINE flag
236 (decorated with types.coroutine decorator);
237 * an async generator.
238 */
239 const char *msg = "generator raised StopIteration";
240 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400241 msg = "coroutine raised StopIteration";
Yury Selivanoveb636452016-09-08 22:01:51 -0700242 }
243 else if PyAsyncGen_CheckExact(gen) {
244 msg = "async generator raised StopIteration";
245 }
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300246 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400247 }
Yury Selivanov68333392015-05-22 11:16:47 -0400248 else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700249 /* `gen` is an ordinary generator without
250 CO_FUTURE_GENERATOR_STOP flag.
251 */
252
Yury Selivanov68333392015-05-22 11:16:47 -0400253 PyObject *exc, *val, *tb;
254
255 /* Pop the exception before issuing a warning. */
256 PyErr_Fetch(&exc, &val, &tb);
257
Martin Panter7e3a91a2016-02-10 04:40:48 +0000258 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Yury Selivanov68333392015-05-22 11:16:47 -0400259 "generator '%.50S' raised StopIteration",
260 gen->gi_qualname)) {
261 /* Warning was converted to an error. */
262 Py_XDECREF(exc);
263 Py_XDECREF(val);
264 Py_XDECREF(tb);
265 }
266 else {
267 PyErr_Restore(exc, val, tb);
268 }
269 }
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400270 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700271 else if (PyAsyncGen_CheckExact(gen) && !result &&
272 PyErr_ExceptionMatches(PyExc_StopAsyncIteration))
273 {
274 /* code in `gen` raised a StopAsyncIteration error:
275 raise a RuntimeError.
276 */
277 const char *msg = "async generator raised StopAsyncIteration";
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300278 _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg);
Yury Selivanoveb636452016-09-08 22:01:51 -0700279 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200280
281 if (!result || f->f_stacktop == NULL) {
282 /* generator can't be rerun, so release the frame */
283 /* first clean reference cycle through stored exception traceback */
284 PyObject *t, *v, *tb;
285 t = f->f_exc_type;
286 v = f->f_exc_value;
287 tb = f->f_exc_traceback;
288 f->f_exc_type = NULL;
289 f->f_exc_value = NULL;
290 f->f_exc_traceback = NULL;
291 Py_XDECREF(t);
292 Py_XDECREF(v);
293 Py_XDECREF(tb);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200294 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200295 gen->gi_frame = NULL;
296 Py_DECREF(f);
297 }
298
299 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000300}
301
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000302PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000303"send(arg) -> send 'arg' into generator,\n\
304return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000305
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500306PyObject *
307_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000308{
Yury Selivanov77c96812016-02-13 17:59:05 -0500309 return gen_send_ex(gen, arg, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000310}
311
312PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400313"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000314
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000315/*
316 * This helper function is used by gen_close and gen_throw to
317 * close a subiterator being delegated to by yield-from.
318 */
319
Antoine Pitrou93963562013-05-14 20:37:52 +0200320static int
321gen_close_iter(PyObject *yf)
322{
323 PyObject *retval = NULL;
324 _Py_IDENTIFIER(close);
325
Yury Selivanoveb636452016-09-08 22:01:51 -0700326 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
Antoine Pitrou93963562013-05-14 20:37:52 +0200327 retval = gen_close((PyGenObject *)yf, NULL);
328 if (retval == NULL)
329 return -1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700330 }
331 else {
Antoine Pitrou93963562013-05-14 20:37:52 +0200332 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
333 if (meth == NULL) {
334 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
335 PyErr_WriteUnraisable(yf);
336 PyErr_Clear();
Yury Selivanoveb636452016-09-08 22:01:51 -0700337 }
338 else {
Victor Stinner3466bde2016-09-05 18:16:01 -0700339 retval = _PyObject_CallNoArg(meth);
Antoine Pitrou93963562013-05-14 20:37:52 +0200340 Py_DECREF(meth);
341 if (retval == NULL)
342 return -1;
343 }
344 }
345 Py_XDECREF(retval);
346 return 0;
347}
348
Yury Selivanovc724bae2016-03-02 11:30:46 -0500349PyObject *
350_PyGen_yf(PyGenObject *gen)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500351{
Antoine Pitrou93963562013-05-14 20:37:52 +0200352 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500353 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200354
355 if (f && f->f_stacktop) {
356 PyObject *bytecode = f->f_code->co_code;
357 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
358
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100359 if (f->f_lasti < 0) {
360 /* Return immediately if the frame didn't start yet. YIELD_FROM
361 always come after LOAD_CONST: a code object should not start
362 with YIELD_FROM */
363 assert(code[0] != YIELD_FROM);
364 return NULL;
365 }
366
Serhiy Storchakaab874002016-09-11 13:48:15 +0300367 if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM)
Antoine Pitrou93963562013-05-14 20:37:52 +0200368 return NULL;
369 yf = f->f_stacktop[-1];
370 Py_INCREF(yf);
371 }
372
373 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500374}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000375
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000376static PyObject *
377gen_close(PyGenObject *gen, PyObject *args)
378{
Antoine Pitrou93963562013-05-14 20:37:52 +0200379 PyObject *retval;
Yury Selivanovc724bae2016-03-02 11:30:46 -0500380 PyObject *yf = _PyGen_yf(gen);
Antoine Pitrou93963562013-05-14 20:37:52 +0200381 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000382
Antoine Pitrou93963562013-05-14 20:37:52 +0200383 if (yf) {
384 gen->gi_running = 1;
385 err = gen_close_iter(yf);
386 gen->gi_running = 0;
387 Py_DECREF(yf);
388 }
389 if (err == 0)
390 PyErr_SetNone(PyExc_GeneratorExit);
Yury Selivanov77c96812016-02-13 17:59:05 -0500391 retval = gen_send_ex(gen, Py_None, 1, 1);
Antoine Pitrou93963562013-05-14 20:37:52 +0200392 if (retval) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400393 char *msg = "generator ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700394 if (PyCoro_CheckExact(gen)) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400395 msg = "coroutine ignored GeneratorExit";
Yury Selivanoveb636452016-09-08 22:01:51 -0700396 } else if (PyAsyncGen_CheckExact(gen)) {
397 msg = ASYNC_GEN_IGNORED_EXIT_MSG;
398 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200399 Py_DECREF(retval);
Yury Selivanov5376ba92015-06-22 12:19:30 -0400400 PyErr_SetString(PyExc_RuntimeError, msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 return NULL;
402 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200403 if (PyErr_ExceptionMatches(PyExc_StopIteration)
404 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
405 PyErr_Clear(); /* ignore these errors */
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200406 Py_RETURN_NONE;
Antoine Pitrou93963562013-05-14 20:37:52 +0200407 }
408 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000409}
410
Antoine Pitrou93963562013-05-14 20:37:52 +0200411
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000412PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000413"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
414return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000415
416static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700417_gen_throw(PyGenObject *gen, int close_on_genexit,
418 PyObject *typ, PyObject *val, PyObject *tb)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000419{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500420 PyObject *yf = _PyGen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000421 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000422
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000423 if (yf) {
424 PyObject *ret;
425 int err;
Yury Selivanoveb636452016-09-08 22:01:51 -0700426 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
427 close_on_genexit
428 ) {
429 /* Asynchronous generators *should not* be closed right away.
430 We have to allow some awaits to work it through, hence the
431 `close_on_genexit` parameter here.
432 */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500433 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200434 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500435 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000436 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000437 if (err < 0)
Yury Selivanov77c96812016-02-13 17:59:05 -0500438 return gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000439 goto throw_here;
440 }
Yury Selivanoveb636452016-09-08 22:01:51 -0700441 if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
442 /* `yf` is a generator or a coroutine. */
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500443 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700444 /* Close the generator that we are currently iterating with
445 'yield from' or awaiting on with 'await'. */
446 ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
447 typ, val, tb);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500448 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000449 } else {
Yury Selivanoveb636452016-09-08 22:01:51 -0700450 /* `yf` is an iterator or a coroutine-like object. */
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000451 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000452 if (meth == NULL) {
453 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
454 Py_DECREF(yf);
455 return NULL;
456 }
457 PyErr_Clear();
458 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000459 goto throw_here;
460 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500461 gen->gi_running = 1;
Yury Selivanoveb636452016-09-08 22:01:51 -0700462 ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500463 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000464 Py_DECREF(meth);
465 }
466 Py_DECREF(yf);
467 if (!ret) {
468 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500469 /* Pop subiterator from stack */
470 ret = *(--gen->gi_frame->f_stacktop);
471 assert(ret == yf);
472 Py_DECREF(ret);
473 /* Termination repetition of YIELD_FROM */
Victor Stinnerf7d199f2016-11-24 22:33:01 +0100474 assert(gen->gi_frame->f_lasti >= 0);
Serhiy Storchakaab874002016-09-11 13:48:15 +0300475 gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT);
Nick Coghlanc40bc092012-06-17 15:15:49 +1000476 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Yury Selivanov77c96812016-02-13 17:59:05 -0500477 ret = gen_send_ex(gen, val, 0, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000478 Py_DECREF(val);
479 } else {
Yury Selivanov77c96812016-02-13 17:59:05 -0500480 ret = gen_send_ex(gen, Py_None, 1, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000481 }
482 }
483 return ret;
484 }
485
486throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 /* First, check the traceback argument, replacing None with
488 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400489 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400491 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 else if (tb != NULL && !PyTraceBack_Check(tb)) {
493 PyErr_SetString(PyExc_TypeError,
494 "throw() third argument must be a traceback object");
495 return NULL;
496 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 Py_INCREF(typ);
499 Py_XINCREF(val);
500 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000501
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400502 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 else if (PyExceptionInstance_Check(typ)) {
506 /* Raising an instance. The value should be a dummy. */
507 if (val && val != Py_None) {
508 PyErr_SetString(PyExc_TypeError,
509 "instance exception may not have a separate value");
510 goto failed_throw;
511 }
512 else {
513 /* Normalize to raise <class>, <instance> */
514 Py_XDECREF(val);
515 val = typ;
516 typ = PyExceptionInstance_Class(typ);
517 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200518
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400519 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200520 /* Returns NULL if there's no traceback */
521 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 }
523 }
524 else {
525 /* Not something you can raise. throw() fails. */
526 PyErr_Format(PyExc_TypeError,
527 "exceptions must be classes or instances "
528 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000529 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 goto failed_throw;
531 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyErr_Restore(typ, val, tb);
Yury Selivanov77c96812016-02-13 17:59:05 -0500534 return gen_send_ex(gen, Py_None, 1, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000535
536failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* Didn't use our arguments, so restore their original refcounts */
538 Py_DECREF(typ);
539 Py_XDECREF(val);
540 Py_XDECREF(tb);
541 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000542}
543
544
545static PyObject *
Yury Selivanoveb636452016-09-08 22:01:51 -0700546gen_throw(PyGenObject *gen, PyObject *args)
547{
548 PyObject *typ;
549 PyObject *tb = NULL;
550 PyObject *val = NULL;
551
552 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) {
553 return NULL;
554 }
555
556 return _gen_throw(gen, 1, typ, val, tb);
557}
558
559
560static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000561gen_iternext(PyGenObject *gen)
562{
Yury Selivanov77c96812016-02-13 17:59:05 -0500563 return gen_send_ex(gen, NULL, 0, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000564}
565
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000566/*
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200567 * Set StopIteration with specified value. Value can be arbitrary object
568 * or NULL.
569 *
570 * Returns 0 if StopIteration is set and -1 if any other exception is set.
571 */
572int
573_PyGen_SetStopIterationValue(PyObject *value)
574{
575 PyObject *e;
576
577 if (value == NULL ||
Yury Selivanovb7c91502017-03-12 15:53:07 -0400578 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200579 {
580 /* Delay exception instantiation if we can */
581 PyErr_SetObject(PyExc_StopIteration, value);
582 return 0;
583 }
584 /* Construct an exception instance manually with
585 * PyObject_CallFunctionObjArgs and pass it to PyErr_SetObject.
586 *
587 * We do this to handle a situation when "value" is a tuple, in which
588 * case PyErr_SetObject would set the value of StopIteration to
589 * the first element of the tuple.
590 *
591 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
592 */
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100593 e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, value, NULL);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200594 if (e == NULL) {
595 return -1;
596 }
597 PyErr_SetObject(PyExc_StopIteration, e);
598 Py_DECREF(e);
599 return 0;
600}
601
602/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000603 * If StopIteration exception is set, fetches its 'value'
604 * attribute if any, otherwise sets pvalue to None.
605 *
606 * Returns 0 if no exception or StopIteration is set.
607 * If any other exception is set, returns -1 and leaves
608 * pvalue unchanged.
609 */
610
611int
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200612_PyGen_FetchStopIterationValue(PyObject **pvalue)
613{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000614 PyObject *et, *ev, *tb;
615 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500616
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000617 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
618 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200619 if (ev) {
620 /* exception will usually be normalised already */
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300621 if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200622 value = ((PyStopIterationObject *)ev)->value;
623 Py_INCREF(value);
624 Py_DECREF(ev);
Serhiy Storchaka24411f82016-11-06 18:44:42 +0200625 } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
626 /* Avoid normalisation and take ev as value.
627 *
628 * Normalization is required if the value is a tuple, in
629 * that case the value of StopIteration would be set to
630 * the first element of the tuple.
631 *
632 * (See _PyErr_CreateException code for details.)
633 */
Antoine Pitrou7403e912015-04-26 18:46:40 +0200634 value = ev;
635 } else {
636 /* normalisation required */
637 PyErr_NormalizeException(&et, &ev, &tb);
Serhiy Storchaka08d230a2015-05-22 11:02:49 +0300638 if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) {
Antoine Pitrou7403e912015-04-26 18:46:40 +0200639 PyErr_Restore(et, ev, tb);
640 return -1;
641 }
642 value = ((PyStopIterationObject *)ev)->value;
643 Py_INCREF(value);
644 Py_DECREF(ev);
645 }
646 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000647 Py_XDECREF(et);
648 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000649 } else if (PyErr_Occurred()) {
650 return -1;
651 }
652 if (value == NULL) {
653 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100654 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000655 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000656 *pvalue = value;
657 return 0;
658}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000659
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000660static PyObject *
661gen_repr(PyGenObject *gen)
662{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400663 return PyUnicode_FromFormat("<generator object %S at %p>",
664 gen->gi_qualname, gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000665}
666
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000667static PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200668gen_get_name(PyGenObject *op)
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000669{
Victor Stinner40ee3012014-06-16 15:59:28 +0200670 Py_INCREF(op->gi_name);
671 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000672}
673
Victor Stinner40ee3012014-06-16 15:59:28 +0200674static int
675gen_set_name(PyGenObject *op, PyObject *value)
676{
Victor Stinner40ee3012014-06-16 15:59:28 +0200677 /* Not legal to del gen.gi_name or to set it to anything
678 * other than a string object. */
679 if (value == NULL || !PyUnicode_Check(value)) {
680 PyErr_SetString(PyExc_TypeError,
681 "__name__ must be set to a string object");
682 return -1;
683 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200684 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300685 Py_XSETREF(op->gi_name, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200686 return 0;
687}
688
689static PyObject *
690gen_get_qualname(PyGenObject *op)
691{
692 Py_INCREF(op->gi_qualname);
693 return op->gi_qualname;
694}
695
696static int
697gen_set_qualname(PyGenObject *op, PyObject *value)
698{
Victor Stinner40ee3012014-06-16 15:59:28 +0200699 /* Not legal to del gen.__qualname__ or to set it to anything
700 * other than a string object. */
701 if (value == NULL || !PyUnicode_Check(value)) {
702 PyErr_SetString(PyExc_TypeError,
703 "__qualname__ must be set to a string object");
704 return -1;
705 }
Victor Stinner40ee3012014-06-16 15:59:28 +0200706 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300707 Py_XSETREF(op->gi_qualname, value);
Victor Stinner40ee3012014-06-16 15:59:28 +0200708 return 0;
709}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000710
Yury Selivanove13f8f32015-07-03 00:23:30 -0400711static PyObject *
712gen_getyieldfrom(PyGenObject *gen)
713{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500714 PyObject *yf = _PyGen_yf(gen);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400715 if (yf == NULL)
716 Py_RETURN_NONE;
717 return yf;
718}
719
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000720static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200721 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
722 PyDoc_STR("name of the generator")},
723 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
724 PyDoc_STR("qualified name of the generator")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400725 {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL,
726 PyDoc_STR("object being iterated by yield from, or None")},
Victor Stinner40ee3012014-06-16 15:59:28 +0200727 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000728};
729
Martin v. Löwise440e472004-06-01 15:22:42 +0000730static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200731 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
732 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
733 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000735};
736
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000737static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500738 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
740 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
741 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000742};
743
Martin v. Löwise440e472004-06-01 15:22:42 +0000744PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyVarObject_HEAD_INIT(&PyType_Type, 0)
746 "generator", /* tp_name */
747 sizeof(PyGenObject), /* tp_basicsize */
748 0, /* tp_itemsize */
749 /* methods */
750 (destructor)gen_dealloc, /* tp_dealloc */
751 0, /* tp_print */
752 0, /* tp_getattr */
753 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400754 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 (reprfunc)gen_repr, /* tp_repr */
756 0, /* tp_as_number */
757 0, /* tp_as_sequence */
758 0, /* tp_as_mapping */
759 0, /* tp_hash */
760 0, /* tp_call */
761 0, /* tp_str */
762 PyObject_GenericGetAttr, /* tp_getattro */
763 0, /* tp_setattro */
764 0, /* tp_as_buffer */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200765 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
766 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 0, /* tp_doc */
768 (traverseproc)gen_traverse, /* tp_traverse */
769 0, /* tp_clear */
770 0, /* tp_richcompare */
771 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov5376ba92015-06-22 12:19:30 -0400772 PyObject_SelfIter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 (iternextfunc)gen_iternext, /* tp_iternext */
774 gen_methods, /* tp_methods */
775 gen_memberlist, /* tp_members */
776 gen_getsetlist, /* tp_getset */
777 0, /* tp_base */
778 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 0, /* tp_descr_get */
781 0, /* tp_descr_set */
782 0, /* tp_dictoffset */
783 0, /* tp_init */
784 0, /* tp_alloc */
785 0, /* tp_new */
786 0, /* tp_free */
787 0, /* tp_is_gc */
788 0, /* tp_bases */
789 0, /* tp_mro */
790 0, /* tp_cache */
791 0, /* tp_subclasses */
792 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200793 0, /* tp_del */
794 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200795 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000796};
797
Yury Selivanov5376ba92015-06-22 12:19:30 -0400798static PyObject *
799gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
800 PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000801{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400802 PyGenObject *gen = PyObject_GC_New(PyGenObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 if (gen == NULL) {
804 Py_DECREF(f);
805 return NULL;
806 }
807 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200808 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 Py_INCREF(f->f_code);
810 gen->gi_code = (PyObject *)(f->f_code);
811 gen->gi_running = 0;
812 gen->gi_weakreflist = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200813 if (name != NULL)
814 gen->gi_name = name;
815 else
816 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
817 Py_INCREF(gen->gi_name);
818 if (qualname != NULL)
819 gen->gi_qualname = qualname;
820 else
821 gen->gi_qualname = gen->gi_name;
822 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 _PyObject_GC_TRACK(gen);
824 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000825}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826
Victor Stinner40ee3012014-06-16 15:59:28 +0200827PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400828PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
829{
830 return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
831}
832
833PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200834PyGen_New(PyFrameObject *f)
835{
Yury Selivanov5376ba92015-06-22 12:19:30 -0400836 return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
Victor Stinner40ee3012014-06-16 15:59:28 +0200837}
838
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839int
840PyGen_NeedsFinalizing(PyGenObject *gen)
841{
Antoine Pitrou93963562013-05-14 20:37:52 +0200842 int i;
843 PyFrameObject *f = gen->gi_frame;
844
845 if (f == NULL || f->f_stacktop == NULL)
846 return 0; /* no frame or empty blockstack == no finalization */
847
848 /* Any block type besides a loop requires cleanup. */
849 for (i = 0; i < f->f_iblock; i++)
850 if (f->f_blockstack[i].b_type != SETUP_LOOP)
851 return 1;
852
853 /* No blocks except loops, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000855}
Yury Selivanov75445082015-05-11 22:57:16 -0400856
Yury Selivanov5376ba92015-06-22 12:19:30 -0400857/* Coroutine Object */
858
859typedef struct {
860 PyObject_HEAD
861 PyCoroObject *cw_coroutine;
862} PyCoroWrapper;
863
864static int
865gen_is_coroutine(PyObject *o)
866{
867 if (PyGen_CheckExact(o)) {
868 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
869 if (code->co_flags & CO_ITERABLE_COROUTINE) {
870 return 1;
871 }
872 }
873 return 0;
874}
875
Yury Selivanov75445082015-05-11 22:57:16 -0400876/*
877 * This helper function returns an awaitable for `o`:
878 * - `o` if `o` is a coroutine-object;
879 * - `type(o)->tp_as_async->am_await(o)`
880 *
881 * Raises a TypeError if it's not possible to return
882 * an awaitable and returns NULL.
883 */
884PyObject *
Yury Selivanov5376ba92015-06-22 12:19:30 -0400885_PyCoro_GetAwaitableIter(PyObject *o)
Yury Selivanov75445082015-05-11 22:57:16 -0400886{
Yury Selivanov6ef05902015-05-28 11:21:31 -0400887 unaryfunc getter = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -0400888 PyTypeObject *ot;
889
Yury Selivanov5376ba92015-06-22 12:19:30 -0400890 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
891 /* 'o' is a coroutine. */
Yury Selivanov75445082015-05-11 22:57:16 -0400892 Py_INCREF(o);
893 return o;
894 }
895
896 ot = Py_TYPE(o);
897 if (ot->tp_as_async != NULL) {
898 getter = ot->tp_as_async->am_await;
899 }
900 if (getter != NULL) {
901 PyObject *res = (*getter)(o);
902 if (res != NULL) {
Yury Selivanov5376ba92015-06-22 12:19:30 -0400903 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
904 /* __await__ must return an *iterator*, not
905 a coroutine or another awaitable (see PEP 492) */
906 PyErr_SetString(PyExc_TypeError,
907 "__await__() returned a coroutine");
908 Py_CLEAR(res);
909 } else if (!PyIter_Check(res)) {
Yury Selivanov75445082015-05-11 22:57:16 -0400910 PyErr_Format(PyExc_TypeError,
911 "__await__() returned non-iterator "
912 "of type '%.100s'",
913 Py_TYPE(res)->tp_name);
914 Py_CLEAR(res);
915 }
Yury Selivanov75445082015-05-11 22:57:16 -0400916 }
917 return res;
918 }
919
920 PyErr_Format(PyExc_TypeError,
921 "object %.100s can't be used in 'await' expression",
922 ot->tp_name);
Yury Selivanov75445082015-05-11 22:57:16 -0400923 return NULL;
924}
Yury Selivanov5376ba92015-06-22 12:19:30 -0400925
926static PyObject *
927coro_repr(PyCoroObject *coro)
928{
929 return PyUnicode_FromFormat("<coroutine object %S at %p>",
930 coro->cr_qualname, coro);
931}
932
933static PyObject *
934coro_await(PyCoroObject *coro)
935{
936 PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
937 if (cw == NULL) {
938 return NULL;
939 }
940 Py_INCREF(coro);
941 cw->cw_coroutine = coro;
942 _PyObject_GC_TRACK(cw);
943 return (PyObject *)cw;
944}
945
Yury Selivanove13f8f32015-07-03 00:23:30 -0400946static PyObject *
947coro_get_cr_await(PyCoroObject *coro)
948{
Yury Selivanovc724bae2016-03-02 11:30:46 -0500949 PyObject *yf = _PyGen_yf((PyGenObject *) coro);
Yury Selivanove13f8f32015-07-03 00:23:30 -0400950 if (yf == NULL)
951 Py_RETURN_NONE;
952 return yf;
953}
954
Yury Selivanov5376ba92015-06-22 12:19:30 -0400955static PyGetSetDef coro_getsetlist[] = {
956 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
957 PyDoc_STR("name of the coroutine")},
958 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
959 PyDoc_STR("qualified name of the coroutine")},
Yury Selivanove13f8f32015-07-03 00:23:30 -0400960 {"cr_await", (getter)coro_get_cr_await, NULL,
961 PyDoc_STR("object being awaited on, or None")},
Yury Selivanov5376ba92015-06-22 12:19:30 -0400962 {NULL} /* Sentinel */
963};
964
965static PyMemberDef coro_memberlist[] = {
966 {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY},
967 {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY},
968 {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY},
969 {NULL} /* Sentinel */
970};
971
972PyDoc_STRVAR(coro_send_doc,
973"send(arg) -> send 'arg' into coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400974return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400975
976PyDoc_STRVAR(coro_throw_doc,
977"throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\
Yury Selivanov66f88282015-06-24 11:04:15 -0400978return next iterated value or raise StopIteration.");
Yury Selivanov5376ba92015-06-22 12:19:30 -0400979
980PyDoc_STRVAR(coro_close_doc,
981"close() -> raise GeneratorExit inside coroutine.");
982
983static PyMethodDef coro_methods[] = {
984 {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc},
985 {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc},
986 {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc},
987 {NULL, NULL} /* Sentinel */
988};
989
990static PyAsyncMethods coro_as_async = {
991 (unaryfunc)coro_await, /* am_await */
992 0, /* am_aiter */
993 0 /* am_anext */
994};
995
996PyTypeObject PyCoro_Type = {
997 PyVarObject_HEAD_INIT(&PyType_Type, 0)
998 "coroutine", /* tp_name */
999 sizeof(PyCoroObject), /* tp_basicsize */
1000 0, /* tp_itemsize */
1001 /* methods */
1002 (destructor)gen_dealloc, /* tp_dealloc */
1003 0, /* tp_print */
1004 0, /* tp_getattr */
1005 0, /* tp_setattr */
1006 &coro_as_async, /* tp_as_async */
1007 (reprfunc)coro_repr, /* tp_repr */
1008 0, /* tp_as_number */
1009 0, /* tp_as_sequence */
1010 0, /* tp_as_mapping */
1011 0, /* tp_hash */
1012 0, /* tp_call */
1013 0, /* tp_str */
1014 PyObject_GenericGetAttr, /* tp_getattro */
1015 0, /* tp_setattro */
1016 0, /* tp_as_buffer */
1017 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1018 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1019 0, /* tp_doc */
1020 (traverseproc)gen_traverse, /* tp_traverse */
1021 0, /* tp_clear */
1022 0, /* tp_richcompare */
1023 offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */
1024 0, /* tp_iter */
1025 0, /* tp_iternext */
1026 coro_methods, /* tp_methods */
1027 coro_memberlist, /* tp_members */
1028 coro_getsetlist, /* tp_getset */
1029 0, /* tp_base */
1030 0, /* tp_dict */
1031 0, /* tp_descr_get */
1032 0, /* tp_descr_set */
1033 0, /* tp_dictoffset */
1034 0, /* tp_init */
1035 0, /* tp_alloc */
1036 0, /* tp_new */
1037 0, /* tp_free */
1038 0, /* tp_is_gc */
1039 0, /* tp_bases */
1040 0, /* tp_mro */
1041 0, /* tp_cache */
1042 0, /* tp_subclasses */
1043 0, /* tp_weaklist */
1044 0, /* tp_del */
1045 0, /* tp_version_tag */
1046 _PyGen_Finalize, /* tp_finalize */
1047};
1048
1049static void
1050coro_wrapper_dealloc(PyCoroWrapper *cw)
1051{
1052 _PyObject_GC_UNTRACK((PyObject *)cw);
1053 Py_CLEAR(cw->cw_coroutine);
1054 PyObject_GC_Del(cw);
1055}
1056
1057static PyObject *
1058coro_wrapper_iternext(PyCoroWrapper *cw)
1059{
Yury Selivanov77c96812016-02-13 17:59:05 -05001060 return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001061}
1062
1063static PyObject *
1064coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg)
1065{
Yury Selivanov77c96812016-02-13 17:59:05 -05001066 return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0);
Yury Selivanov5376ba92015-06-22 12:19:30 -04001067}
1068
1069static PyObject *
1070coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args)
1071{
1072 return gen_throw((PyGenObject *)cw->cw_coroutine, args);
1073}
1074
1075static PyObject *
1076coro_wrapper_close(PyCoroWrapper *cw, PyObject *args)
1077{
1078 return gen_close((PyGenObject *)cw->cw_coroutine, args);
1079}
1080
1081static int
1082coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg)
1083{
1084 Py_VISIT((PyObject *)cw->cw_coroutine);
1085 return 0;
1086}
1087
1088static PyMethodDef coro_wrapper_methods[] = {
Yury Selivanov66f88282015-06-24 11:04:15 -04001089 {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc},
1090 {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc},
1091 {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc},
Yury Selivanov5376ba92015-06-22 12:19:30 -04001092 {NULL, NULL} /* Sentinel */
1093};
1094
1095PyTypeObject _PyCoroWrapper_Type = {
1096 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1097 "coroutine_wrapper",
1098 sizeof(PyCoroWrapper), /* tp_basicsize */
1099 0, /* tp_itemsize */
1100 (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */
1101 0, /* tp_print */
1102 0, /* tp_getattr */
1103 0, /* tp_setattr */
1104 0, /* tp_as_async */
1105 0, /* tp_repr */
1106 0, /* tp_as_number */
1107 0, /* tp_as_sequence */
1108 0, /* tp_as_mapping */
1109 0, /* tp_hash */
1110 0, /* tp_call */
1111 0, /* tp_str */
1112 PyObject_GenericGetAttr, /* tp_getattro */
1113 0, /* tp_setattro */
1114 0, /* tp_as_buffer */
1115 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1116 "A wrapper object implementing __await__ for coroutines.",
1117 (traverseproc)coro_wrapper_traverse, /* tp_traverse */
1118 0, /* tp_clear */
1119 0, /* tp_richcompare */
1120 0, /* tp_weaklistoffset */
1121 PyObject_SelfIter, /* tp_iter */
1122 (iternextfunc)coro_wrapper_iternext, /* tp_iternext */
1123 coro_wrapper_methods, /* tp_methods */
1124 0, /* tp_members */
1125 0, /* tp_getset */
1126 0, /* tp_base */
1127 0, /* tp_dict */
1128 0, /* tp_descr_get */
1129 0, /* tp_descr_set */
1130 0, /* tp_dictoffset */
1131 0, /* tp_init */
1132 0, /* tp_alloc */
1133 0, /* tp_new */
Yury Selivanov33499b72016-11-08 19:19:28 -05001134 0, /* tp_free */
Yury Selivanov5376ba92015-06-22 12:19:30 -04001135};
1136
1137PyObject *
1138PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1139{
1140 return gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1141}
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001142
1143
Yury Selivanoveb636452016-09-08 22:01:51 -07001144/* ========= Asynchronous Generators ========= */
1145
1146
1147typedef enum {
1148 AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */
1149 AWAITABLE_STATE_ITER, /* being iterated */
1150 AWAITABLE_STATE_CLOSED, /* closed */
1151} AwaitableState;
1152
1153
1154typedef struct {
1155 PyObject_HEAD
1156 PyAsyncGenObject *ags_gen;
1157
1158 /* Can be NULL, when in the __anext__() mode
1159 (equivalent of "asend(None)") */
1160 PyObject *ags_sendval;
1161
1162 AwaitableState ags_state;
1163} PyAsyncGenASend;
1164
1165
1166typedef struct {
1167 PyObject_HEAD
1168 PyAsyncGenObject *agt_gen;
1169
1170 /* Can be NULL, when in the "aclose()" mode
1171 (equivalent of "athrow(GeneratorExit)") */
1172 PyObject *agt_args;
1173
1174 AwaitableState agt_state;
1175} PyAsyncGenAThrow;
1176
1177
1178typedef struct {
1179 PyObject_HEAD
1180 PyObject *agw_val;
1181} _PyAsyncGenWrappedValue;
1182
1183
1184#ifndef _PyAsyncGen_MAXFREELIST
1185#define _PyAsyncGen_MAXFREELIST 80
1186#endif
1187
1188/* Freelists boost performance 6-10%; they also reduce memory
1189 fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend
1190 are short-living objects that are instantiated for every
1191 __anext__ call.
1192*/
1193
1194static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST];
1195static int ag_value_freelist_free = 0;
1196
1197static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST];
1198static int ag_asend_freelist_free = 0;
1199
1200#define _PyAsyncGenWrappedValue_CheckExact(o) \
1201 (Py_TYPE(o) == &_PyAsyncGenWrappedValue_Type)
1202
1203#define PyAsyncGenASend_CheckExact(o) \
1204 (Py_TYPE(o) == &_PyAsyncGenASend_Type)
1205
1206
1207static int
1208async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg)
1209{
1210 Py_VISIT(gen->ag_finalizer);
1211 return gen_traverse((PyGenObject*)gen, visit, arg);
1212}
1213
1214
1215static PyObject *
1216async_gen_repr(PyAsyncGenObject *o)
1217{
1218 return PyUnicode_FromFormat("<async_generator object %S at %p>",
1219 o->ag_qualname, o);
1220}
1221
1222
1223static int
1224async_gen_init_hooks(PyAsyncGenObject *o)
1225{
1226 PyThreadState *tstate;
1227 PyObject *finalizer;
1228 PyObject *firstiter;
1229
1230 if (o->ag_hooks_inited) {
1231 return 0;
1232 }
1233
1234 o->ag_hooks_inited = 1;
1235
1236 tstate = PyThreadState_GET();
1237
1238 finalizer = tstate->async_gen_finalizer;
1239 if (finalizer) {
1240 Py_INCREF(finalizer);
1241 o->ag_finalizer = finalizer;
1242 }
1243
1244 firstiter = tstate->async_gen_firstiter;
1245 if (firstiter) {
1246 PyObject *res;
1247
1248 Py_INCREF(firstiter);
Victor Stinner7bfb42d2016-12-05 17:04:32 +01001249 res = PyObject_CallFunctionObjArgs(firstiter, o, NULL);
Yury Selivanoveb636452016-09-08 22:01:51 -07001250 Py_DECREF(firstiter);
1251 if (res == NULL) {
1252 return 1;
1253 }
1254 Py_DECREF(res);
1255 }
1256
1257 return 0;
1258}
1259
1260
1261static PyObject *
1262async_gen_anext(PyAsyncGenObject *o)
1263{
1264 if (async_gen_init_hooks(o)) {
1265 return NULL;
1266 }
1267 return async_gen_asend_new(o, NULL);
1268}
1269
1270
1271static PyObject *
1272async_gen_asend(PyAsyncGenObject *o, PyObject *arg)
1273{
1274 if (async_gen_init_hooks(o)) {
1275 return NULL;
1276 }
1277 return async_gen_asend_new(o, arg);
1278}
1279
1280
1281static PyObject *
1282async_gen_aclose(PyAsyncGenObject *o, PyObject *arg)
1283{
1284 if (async_gen_init_hooks(o)) {
1285 return NULL;
1286 }
1287 return async_gen_athrow_new(o, NULL);
1288}
1289
1290static PyObject *
1291async_gen_athrow(PyAsyncGenObject *o, PyObject *args)
1292{
1293 if (async_gen_init_hooks(o)) {
1294 return NULL;
1295 }
1296 return async_gen_athrow_new(o, args);
1297}
1298
1299
1300static PyGetSetDef async_gen_getsetlist[] = {
1301 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
1302 PyDoc_STR("name of the async generator")},
1303 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
1304 PyDoc_STR("qualified name of the async generator")},
1305 {"ag_await", (getter)coro_get_cr_await, NULL,
1306 PyDoc_STR("object being awaited on, or None")},
1307 {NULL} /* Sentinel */
1308};
1309
1310static PyMemberDef async_gen_memberlist[] = {
1311 {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
1312 {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running), READONLY},
1313 {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
1314 {NULL} /* Sentinel */
1315};
1316
1317PyDoc_STRVAR(async_aclose_doc,
1318"aclose() -> raise GeneratorExit inside generator.");
1319
1320PyDoc_STRVAR(async_asend_doc,
1321"asend(v) -> send 'v' in generator.");
1322
1323PyDoc_STRVAR(async_athrow_doc,
1324"athrow(typ[,val[,tb]]) -> raise exception in generator.");
1325
1326static PyMethodDef async_gen_methods[] = {
1327 {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc},
1328 {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc},
1329 {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc},
1330 {NULL, NULL} /* Sentinel */
1331};
1332
1333
1334static PyAsyncMethods async_gen_as_async = {
1335 0, /* am_await */
1336 PyObject_SelfIter, /* am_aiter */
1337 (unaryfunc)async_gen_anext /* am_anext */
1338};
1339
1340
1341PyTypeObject PyAsyncGen_Type = {
1342 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1343 "async_generator", /* tp_name */
1344 sizeof(PyAsyncGenObject), /* tp_basicsize */
1345 0, /* tp_itemsize */
1346 /* methods */
1347 (destructor)gen_dealloc, /* tp_dealloc */
1348 0, /* tp_print */
1349 0, /* tp_getattr */
1350 0, /* tp_setattr */
1351 &async_gen_as_async, /* tp_as_async */
1352 (reprfunc)async_gen_repr, /* tp_repr */
1353 0, /* tp_as_number */
1354 0, /* tp_as_sequence */
1355 0, /* tp_as_mapping */
1356 0, /* tp_hash */
1357 0, /* tp_call */
1358 0, /* tp_str */
1359 PyObject_GenericGetAttr, /* tp_getattro */
1360 0, /* tp_setattro */
1361 0, /* tp_as_buffer */
1362 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1363 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
1364 0, /* tp_doc */
1365 (traverseproc)async_gen_traverse, /* tp_traverse */
1366 0, /* tp_clear */
1367 0, /* tp_richcompare */
1368 offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1369 0, /* tp_iter */
1370 0, /* tp_iternext */
1371 async_gen_methods, /* tp_methods */
1372 async_gen_memberlist, /* tp_members */
1373 async_gen_getsetlist, /* tp_getset */
1374 0, /* tp_base */
1375 0, /* tp_dict */
1376 0, /* tp_descr_get */
1377 0, /* tp_descr_set */
1378 0, /* tp_dictoffset */
1379 0, /* tp_init */
1380 0, /* tp_alloc */
1381 0, /* tp_new */
1382 0, /* tp_free */
1383 0, /* tp_is_gc */
1384 0, /* tp_bases */
1385 0, /* tp_mro */
1386 0, /* tp_cache */
1387 0, /* tp_subclasses */
1388 0, /* tp_weaklist */
1389 0, /* tp_del */
1390 0, /* tp_version_tag */
1391 _PyGen_Finalize, /* tp_finalize */
1392};
1393
1394
1395PyObject *
1396PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1397{
1398 PyAsyncGenObject *o;
1399 o = (PyAsyncGenObject *)gen_new_with_qualname(
1400 &PyAsyncGen_Type, f, name, qualname);
1401 if (o == NULL) {
1402 return NULL;
1403 }
1404 o->ag_finalizer = NULL;
1405 o->ag_closed = 0;
1406 o->ag_hooks_inited = 0;
1407 return (PyObject*)o;
1408}
1409
1410
1411int
1412PyAsyncGen_ClearFreeLists(void)
1413{
1414 int ret = ag_value_freelist_free + ag_asend_freelist_free;
1415
1416 while (ag_value_freelist_free) {
1417 _PyAsyncGenWrappedValue *o;
1418 o = ag_value_freelist[--ag_value_freelist_free];
1419 assert(_PyAsyncGenWrappedValue_CheckExact(o));
Yury Selivanov29310c42016-11-08 19:46:22 -05001420 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001421 }
1422
1423 while (ag_asend_freelist_free) {
1424 PyAsyncGenASend *o;
1425 o = ag_asend_freelist[--ag_asend_freelist_free];
1426 assert(Py_TYPE(o) == &_PyAsyncGenASend_Type);
Yury Selivanov29310c42016-11-08 19:46:22 -05001427 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001428 }
1429
1430 return ret;
1431}
1432
1433void
1434PyAsyncGen_Fini(void)
1435{
1436 PyAsyncGen_ClearFreeLists();
1437}
1438
1439
1440static PyObject *
1441async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1442{
1443 if (result == NULL) {
1444 if (!PyErr_Occurred()) {
1445 PyErr_SetNone(PyExc_StopAsyncIteration);
1446 }
1447
1448 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1449 || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1450 ) {
1451 gen->ag_closed = 1;
1452 }
1453
1454 return NULL;
1455 }
1456
1457 if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1458 /* async yield */
Serhiy Storchaka60e49aa2016-11-06 18:47:03 +02001459 _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
Yury Selivanoveb636452016-09-08 22:01:51 -07001460 Py_DECREF(result);
Yury Selivanoveb636452016-09-08 22:01:51 -07001461 return NULL;
1462 }
1463
1464 return result;
1465}
1466
1467
1468/* ---------- Async Generator ASend Awaitable ------------ */
1469
1470
1471static void
1472async_gen_asend_dealloc(PyAsyncGenASend *o)
1473{
Yury Selivanov29310c42016-11-08 19:46:22 -05001474 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001475 Py_CLEAR(o->ags_gen);
1476 Py_CLEAR(o->ags_sendval);
1477 if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) {
1478 assert(PyAsyncGenASend_CheckExact(o));
1479 ag_asend_freelist[ag_asend_freelist_free++] = o;
1480 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001481 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001482 }
1483}
1484
Yury Selivanov29310c42016-11-08 19:46:22 -05001485static int
1486async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg)
1487{
1488 Py_VISIT(o->ags_gen);
1489 Py_VISIT(o->ags_sendval);
1490 return 0;
1491}
1492
Yury Selivanoveb636452016-09-08 22:01:51 -07001493
1494static PyObject *
1495async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
1496{
1497 PyObject *result;
1498
1499 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1500 PyErr_SetNone(PyExc_StopIteration);
1501 return NULL;
1502 }
1503
1504 if (o->ags_state == AWAITABLE_STATE_INIT) {
1505 if (arg == NULL || arg == Py_None) {
1506 arg = o->ags_sendval;
1507 }
1508 o->ags_state = AWAITABLE_STATE_ITER;
1509 }
1510
1511 result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
1512 result = async_gen_unwrap_value(o->ags_gen, result);
1513
1514 if (result == NULL) {
1515 o->ags_state = AWAITABLE_STATE_CLOSED;
1516 }
1517
1518 return result;
1519}
1520
1521
1522static PyObject *
1523async_gen_asend_iternext(PyAsyncGenASend *o)
1524{
1525 return async_gen_asend_send(o, NULL);
1526}
1527
1528
1529static PyObject *
1530async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args)
1531{
1532 PyObject *result;
1533
1534 if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1535 PyErr_SetNone(PyExc_StopIteration);
1536 return NULL;
1537 }
1538
1539 result = gen_throw((PyGenObject*)o->ags_gen, args);
1540 result = async_gen_unwrap_value(o->ags_gen, result);
1541
1542 if (result == NULL) {
1543 o->ags_state = AWAITABLE_STATE_CLOSED;
1544 }
1545
1546 return result;
1547}
1548
1549
1550static PyObject *
1551async_gen_asend_close(PyAsyncGenASend *o, PyObject *args)
1552{
1553 o->ags_state = AWAITABLE_STATE_CLOSED;
1554 Py_RETURN_NONE;
1555}
1556
1557
1558static PyMethodDef async_gen_asend_methods[] = {
1559 {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc},
1560 {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc},
1561 {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc},
1562 {NULL, NULL} /* Sentinel */
1563};
1564
1565
1566static PyAsyncMethods async_gen_asend_as_async = {
1567 PyObject_SelfIter, /* am_await */
1568 0, /* am_aiter */
1569 0 /* am_anext */
1570};
1571
1572
1573PyTypeObject _PyAsyncGenASend_Type = {
1574 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1575 "async_generator_asend", /* tp_name */
1576 sizeof(PyAsyncGenASend), /* tp_basicsize */
1577 0, /* tp_itemsize */
1578 /* methods */
1579 (destructor)async_gen_asend_dealloc, /* tp_dealloc */
1580 0, /* tp_print */
1581 0, /* tp_getattr */
1582 0, /* tp_setattr */
1583 &async_gen_asend_as_async, /* tp_as_async */
1584 0, /* tp_repr */
1585 0, /* tp_as_number */
1586 0, /* tp_as_sequence */
1587 0, /* tp_as_mapping */
1588 0, /* tp_hash */
1589 0, /* tp_call */
1590 0, /* tp_str */
1591 PyObject_GenericGetAttr, /* tp_getattro */
1592 0, /* tp_setattro */
1593 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001594 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001595 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001596 (traverseproc)async_gen_asend_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001597 0, /* tp_clear */
1598 0, /* tp_richcompare */
1599 0, /* tp_weaklistoffset */
1600 PyObject_SelfIter, /* tp_iter */
1601 (iternextfunc)async_gen_asend_iternext, /* tp_iternext */
1602 async_gen_asend_methods, /* tp_methods */
1603 0, /* tp_members */
1604 0, /* tp_getset */
1605 0, /* tp_base */
1606 0, /* tp_dict */
1607 0, /* tp_descr_get */
1608 0, /* tp_descr_set */
1609 0, /* tp_dictoffset */
1610 0, /* tp_init */
1611 0, /* tp_alloc */
1612 0, /* tp_new */
1613};
1614
1615
1616static PyObject *
1617async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
1618{
1619 PyAsyncGenASend *o;
1620 if (ag_asend_freelist_free) {
1621 ag_asend_freelist_free--;
1622 o = ag_asend_freelist[ag_asend_freelist_free];
1623 _Py_NewReference((PyObject *)o);
1624 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001625 o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001626 if (o == NULL) {
1627 return NULL;
1628 }
1629 }
1630
1631 Py_INCREF(gen);
1632 o->ags_gen = gen;
1633
1634 Py_XINCREF(sendval);
1635 o->ags_sendval = sendval;
1636
1637 o->ags_state = AWAITABLE_STATE_INIT;
Yury Selivanov29310c42016-11-08 19:46:22 -05001638
1639 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001640 return (PyObject*)o;
1641}
1642
1643
1644/* ---------- Async Generator Value Wrapper ------------ */
1645
1646
1647static void
1648async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o)
1649{
Yury Selivanov29310c42016-11-08 19:46:22 -05001650 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001651 Py_CLEAR(o->agw_val);
1652 if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) {
1653 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1654 ag_value_freelist[ag_value_freelist_free++] = o;
1655 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001656 PyObject_GC_Del(o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001657 }
1658}
1659
1660
Yury Selivanov29310c42016-11-08 19:46:22 -05001661static int
1662async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o,
1663 visitproc visit, void *arg)
1664{
1665 Py_VISIT(o->agw_val);
1666 return 0;
1667}
1668
1669
Yury Selivanoveb636452016-09-08 22:01:51 -07001670PyTypeObject _PyAsyncGenWrappedValue_Type = {
1671 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1672 "async_generator_wrapped_value", /* tp_name */
1673 sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */
1674 0, /* tp_itemsize */
1675 /* methods */
1676 (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */
1677 0, /* tp_print */
1678 0, /* tp_getattr */
1679 0, /* tp_setattr */
1680 0, /* tp_as_async */
1681 0, /* tp_repr */
1682 0, /* tp_as_number */
1683 0, /* tp_as_sequence */
1684 0, /* tp_as_mapping */
1685 0, /* tp_hash */
1686 0, /* tp_call */
1687 0, /* tp_str */
1688 PyObject_GenericGetAttr, /* tp_getattro */
1689 0, /* tp_setattro */
1690 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001691 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001692 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001693 (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001694 0, /* tp_clear */
1695 0, /* tp_richcompare */
1696 0, /* tp_weaklistoffset */
1697 0, /* tp_iter */
1698 0, /* tp_iternext */
1699 0, /* tp_methods */
1700 0, /* tp_members */
1701 0, /* tp_getset */
1702 0, /* tp_base */
1703 0, /* tp_dict */
1704 0, /* tp_descr_get */
1705 0, /* tp_descr_set */
1706 0, /* tp_dictoffset */
1707 0, /* tp_init */
1708 0, /* tp_alloc */
1709 0, /* tp_new */
1710};
1711
1712
1713PyObject *
1714_PyAsyncGenValueWrapperNew(PyObject *val)
1715{
1716 _PyAsyncGenWrappedValue *o;
1717 assert(val);
1718
1719 if (ag_value_freelist_free) {
1720 ag_value_freelist_free--;
1721 o = ag_value_freelist[ag_value_freelist_free];
1722 assert(_PyAsyncGenWrappedValue_CheckExact(o));
1723 _Py_NewReference((PyObject*)o);
1724 } else {
Yury Selivanov29310c42016-11-08 19:46:22 -05001725 o = PyObject_GC_New(_PyAsyncGenWrappedValue,
1726 &_PyAsyncGenWrappedValue_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001727 if (o == NULL) {
1728 return NULL;
1729 }
1730 }
1731 o->agw_val = val;
1732 Py_INCREF(val);
Yury Selivanov29310c42016-11-08 19:46:22 -05001733 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001734 return (PyObject*)o;
1735}
1736
1737
1738/* ---------- Async Generator AThrow awaitable ------------ */
1739
1740
1741static void
1742async_gen_athrow_dealloc(PyAsyncGenAThrow *o)
1743{
Yury Selivanov29310c42016-11-08 19:46:22 -05001744 _PyObject_GC_UNTRACK((PyObject *)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001745 Py_CLEAR(o->agt_gen);
1746 Py_CLEAR(o->agt_args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001747 PyObject_GC_Del(o);
1748}
1749
1750
1751static int
1752async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg)
1753{
1754 Py_VISIT(o->agt_gen);
1755 Py_VISIT(o->agt_args);
1756 return 0;
Yury Selivanoveb636452016-09-08 22:01:51 -07001757}
1758
1759
1760static PyObject *
1761async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
1762{
1763 PyGenObject *gen = (PyGenObject*)o->agt_gen;
1764 PyFrameObject *f = gen->gi_frame;
1765 PyObject *retval;
1766
1767 if (f == NULL || f->f_stacktop == NULL ||
1768 o->agt_state == AWAITABLE_STATE_CLOSED) {
1769 PyErr_SetNone(PyExc_StopIteration);
1770 return NULL;
1771 }
1772
1773 if (o->agt_state == AWAITABLE_STATE_INIT) {
1774 if (o->agt_gen->ag_closed) {
1775 PyErr_SetNone(PyExc_StopIteration);
1776 return NULL;
1777 }
1778
1779 if (arg != Py_None) {
1780 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1781 return NULL;
1782 }
1783
1784 o->agt_state = AWAITABLE_STATE_ITER;
1785
1786 if (o->agt_args == NULL) {
1787 /* aclose() mode */
1788 o->agt_gen->ag_closed = 1;
1789
1790 retval = _gen_throw((PyGenObject *)gen,
1791 0, /* Do not close generator when
1792 PyExc_GeneratorExit is passed */
1793 PyExc_GeneratorExit, NULL, NULL);
1794
1795 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1796 Py_DECREF(retval);
1797 goto yield_close;
1798 }
1799 } else {
1800 PyObject *typ;
1801 PyObject *tb = NULL;
1802 PyObject *val = NULL;
1803
1804 if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3,
1805 &typ, &val, &tb)) {
1806 return NULL;
1807 }
1808
1809 retval = _gen_throw((PyGenObject *)gen,
1810 0, /* Do not close generator when
1811 PyExc_GeneratorExit is passed */
1812 typ, val, tb);
1813 retval = async_gen_unwrap_value(o->agt_gen, retval);
1814 }
1815 if (retval == NULL) {
1816 goto check_error;
1817 }
1818 return retval;
1819 }
1820
1821 assert(o->agt_state == AWAITABLE_STATE_ITER);
1822
1823 retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0);
1824 if (o->agt_args) {
1825 return async_gen_unwrap_value(o->agt_gen, retval);
1826 } else {
1827 /* aclose() mode */
1828 if (retval) {
1829 if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1830 Py_DECREF(retval);
1831 goto yield_close;
1832 }
1833 else {
1834 return retval;
1835 }
1836 }
1837 else {
1838 goto check_error;
1839 }
1840 }
1841
1842yield_close:
1843 PyErr_SetString(
1844 PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1845 return NULL;
1846
1847check_error:
Yury Selivanov41782e42016-11-16 18:16:17 -05001848 if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
1849 o->agt_state = AWAITABLE_STATE_CLOSED;
1850 if (o->agt_args == NULL) {
1851 /* when aclose() is called we don't want to propagate
1852 StopAsyncIteration; just raise StopIteration, signalling
1853 that 'aclose()' is done. */
1854 PyErr_Clear();
1855 PyErr_SetNone(PyExc_StopIteration);
1856 }
1857 }
1858 else if (PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
Yury Selivanoveb636452016-09-08 22:01:51 -07001859 o->agt_state = AWAITABLE_STATE_CLOSED;
1860 PyErr_Clear(); /* ignore these errors */
1861 PyErr_SetNone(PyExc_StopIteration);
1862 }
1863 return NULL;
1864}
1865
1866
1867static PyObject *
1868async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
1869{
1870 PyObject *retval;
1871
1872 if (o->agt_state == AWAITABLE_STATE_INIT) {
1873 PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1874 return NULL;
1875 }
1876
1877 if (o->agt_state == AWAITABLE_STATE_CLOSED) {
1878 PyErr_SetNone(PyExc_StopIteration);
1879 return NULL;
1880 }
1881
1882 retval = gen_throw((PyGenObject*)o->agt_gen, args);
1883 if (o->agt_args) {
1884 return async_gen_unwrap_value(o->agt_gen, retval);
1885 } else {
1886 /* aclose() mode */
1887 if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1888 Py_DECREF(retval);
1889 PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
1890 return NULL;
1891 }
1892 return retval;
1893 }
1894}
1895
1896
1897static PyObject *
1898async_gen_athrow_iternext(PyAsyncGenAThrow *o)
1899{
1900 return async_gen_athrow_send(o, Py_None);
1901}
1902
1903
1904static PyObject *
1905async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args)
1906{
1907 o->agt_state = AWAITABLE_STATE_CLOSED;
1908 Py_RETURN_NONE;
1909}
1910
1911
1912static PyMethodDef async_gen_athrow_methods[] = {
1913 {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc},
1914 {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc},
1915 {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc},
1916 {NULL, NULL} /* Sentinel */
1917};
1918
1919
1920static PyAsyncMethods async_gen_athrow_as_async = {
1921 PyObject_SelfIter, /* am_await */
1922 0, /* am_aiter */
1923 0 /* am_anext */
1924};
1925
1926
1927PyTypeObject _PyAsyncGenAThrow_Type = {
1928 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1929 "async_generator_athrow", /* tp_name */
1930 sizeof(PyAsyncGenAThrow), /* tp_basicsize */
1931 0, /* tp_itemsize */
1932 /* methods */
1933 (destructor)async_gen_athrow_dealloc, /* tp_dealloc */
1934 0, /* tp_print */
1935 0, /* tp_getattr */
1936 0, /* tp_setattr */
1937 &async_gen_athrow_as_async, /* tp_as_async */
1938 0, /* tp_repr */
1939 0, /* tp_as_number */
1940 0, /* tp_as_sequence */
1941 0, /* tp_as_mapping */
1942 0, /* tp_hash */
1943 0, /* tp_call */
1944 0, /* tp_str */
1945 PyObject_GenericGetAttr, /* tp_getattro */
1946 0, /* tp_setattro */
1947 0, /* tp_as_buffer */
Yury Selivanov29310c42016-11-08 19:46:22 -05001948 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Yury Selivanoveb636452016-09-08 22:01:51 -07001949 0, /* tp_doc */
Yury Selivanov29310c42016-11-08 19:46:22 -05001950 (traverseproc)async_gen_athrow_traverse, /* tp_traverse */
Yury Selivanoveb636452016-09-08 22:01:51 -07001951 0, /* tp_clear */
1952 0, /* tp_richcompare */
1953 0, /* tp_weaklistoffset */
1954 PyObject_SelfIter, /* tp_iter */
1955 (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */
1956 async_gen_athrow_methods, /* tp_methods */
1957 0, /* tp_members */
1958 0, /* tp_getset */
1959 0, /* tp_base */
1960 0, /* tp_dict */
1961 0, /* tp_descr_get */
1962 0, /* tp_descr_set */
1963 0, /* tp_dictoffset */
1964 0, /* tp_init */
1965 0, /* tp_alloc */
1966 0, /* tp_new */
1967};
1968
1969
1970static PyObject *
1971async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
1972{
1973 PyAsyncGenAThrow *o;
Yury Selivanov29310c42016-11-08 19:46:22 -05001974 o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
Yury Selivanoveb636452016-09-08 22:01:51 -07001975 if (o == NULL) {
1976 return NULL;
1977 }
1978 o->agt_gen = gen;
1979 o->agt_args = args;
1980 o->agt_state = AWAITABLE_STATE_INIT;
1981 Py_INCREF(gen);
1982 Py_XINCREF(args);
Yury Selivanov29310c42016-11-08 19:46:22 -05001983 _PyObject_GC_TRACK((PyObject*)o);
Yury Selivanoveb636452016-09-08 22:01:51 -07001984 return (PyObject*)o;
1985}