blob: 3c32e7b9788f22642303f9cc1e8cf6841bef9c63 [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
Nick Coghlan1f7ce622012-01-13 21:43:40 +10008static PyObject *gen_close(PyGenObject *gen, PyObject *args);
Nick Coghlan1f7ce622012-01-13 21:43:40 +10009
Martin v. Löwise440e472004-06-01 15:22:42 +000010static int
11gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
12{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013 Py_VISIT((PyObject *)gen->gi_frame);
14 Py_VISIT(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020015 Py_VISIT(gen->gi_name);
16 Py_VISIT(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000018}
19
Antoine Pitrou58720d62013-08-05 23:26:40 +020020void
21_PyGen_Finalize(PyObject *self)
Antoine Pitrou796564c2013-07-30 19:59:21 +020022{
23 PyGenObject *gen = (PyGenObject *)self;
24 PyObject *res;
25 PyObject *error_type, *error_value, *error_traceback;
26
Yury Selivanov75445082015-05-11 22:57:16 -040027 /* If `gen` is a coroutine, and if it was never awaited on,
28 issue a RuntimeWarning. */
29 if (gen->gi_code != NULL
30 && ((PyCodeObject *)gen->gi_code)->co_flags & (CO_COROUTINE
31 | CO_ITERABLE_COROUTINE)
32 && gen->gi_frame != NULL
33 && gen->gi_frame->f_lasti == -1
34 && !PyErr_Occurred()
35 && PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
36 "coroutine '%.50S' was never awaited",
37 gen->gi_qualname))
38 return;
39
Antoine Pitrou796564c2013-07-30 19:59:21 +020040 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
41 /* Generator isn't paused, so no need to close */
42 return;
43
44 /* Save the current exception, if any. */
45 PyErr_Fetch(&error_type, &error_value, &error_traceback);
46
47 res = gen_close(gen, NULL);
48
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}
57
58static void
Martin v. Löwise440e472004-06-01 15:22:42 +000059gen_dealloc(PyGenObject *gen)
60{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (gen->gi_weakreflist != NULL)
66 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000067
Antoine Pitrou93963562013-05-14 20:37:52 +020068 _PyObject_GC_TRACK(self);
69
Antoine Pitrou796564c2013-07-30 19:59:21 +020070 if (PyObject_CallFinalizerFromDealloc(self))
71 return; /* resurrected. :( */
Antoine Pitrou93963562013-05-14 20:37:52 +020072
73 _PyObject_GC_UNTRACK(self);
74 Py_CLEAR(gen->gi_frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 Py_CLEAR(gen->gi_code);
Victor Stinner40ee3012014-06-16 15:59:28 +020076 Py_CLEAR(gen->gi_name);
77 Py_CLEAR(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +000079}
80
81static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000082gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
Martin v. Löwise440e472004-06-01 15:22:42 +000083{
Antoine Pitrou93963562013-05-14 20:37:52 +020084 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +020086 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +000087
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -050088 if (gen->gi_running) {
89 PyErr_SetString(PyExc_ValueError,
90 "generator already executing");
91 return NULL;
92 }
Antoine Pitrou93963562013-05-14 20:37:52 +020093 if (f == NULL || f->f_stacktop == NULL) {
94 /* Only set exception if called from send() */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 if (arg && !exc)
96 PyErr_SetNone(PyExc_StopIteration);
97 return NULL;
98 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000099
Antoine Pitrou93963562013-05-14 20:37:52 +0200100 if (f->f_lasti == -1) {
101 if (arg && arg != Py_None) {
102 PyErr_SetString(PyExc_TypeError,
103 "can't send non-None value to a "
104 "just-started generator");
105 return NULL;
106 }
107 } else {
108 /* Push arg onto the frame's value stack */
109 result = arg ? arg : Py_None;
110 Py_INCREF(result);
111 *(f->f_stacktop++) = result;
112 }
113
114 /* Generators always return to their most recent caller, not
115 * necessarily their creator. */
116 Py_XINCREF(tstate->frame);
117 assert(f->f_back == NULL);
118 f->f_back = tstate->frame;
119
120 gen->gi_running = 1;
121 result = PyEval_EvalFrameEx(f, exc);
122 gen->gi_running = 0;
123
124 /* Don't keep the reference to f_back any longer than necessary. It
125 * may keep a chain of frames alive or it could create a reference
126 * cycle. */
127 assert(f->f_back == tstate->frame);
128 Py_CLEAR(f->f_back);
129
130 /* If the generator just returned (as opposed to yielding), signal
131 * that the generator is exhausted. */
132 if (result && f->f_stacktop == NULL) {
133 if (result == Py_None) {
134 /* Delay exception instantiation if we can */
135 PyErr_SetNone(PyExc_StopIteration);
136 } else {
137 PyObject *e = PyObject_CallFunctionObjArgs(
138 PyExc_StopIteration, result, NULL);
139 if (e != NULL) {
140 PyErr_SetObject(PyExc_StopIteration, e);
141 Py_DECREF(e);
142 }
143 }
144 Py_CLEAR(result);
145 }
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400146 else if (!result) {
147 /* Check for __future__ generator_stop and conditionally turn
148 * a leaking StopIteration into RuntimeError (with its cause
149 * set appropriately). */
150 if ((((PyCodeObject *)gen->gi_code)->co_flags &
Yury Selivanov75445082015-05-11 22:57:16 -0400151 (CO_FUTURE_GENERATOR_STOP | CO_COROUTINE | CO_ITERABLE_COROUTINE))
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400152 && PyErr_ExceptionMatches(PyExc_StopIteration))
153 {
154 PyObject *exc, *val, *val2, *tb;
155 PyErr_Fetch(&exc, &val, &tb);
156 PyErr_NormalizeException(&exc, &val, &tb);
157 if (tb != NULL)
158 PyException_SetTraceback(val, tb);
159 Py_DECREF(exc);
160 Py_XDECREF(tb);
161 PyErr_SetString(PyExc_RuntimeError,
162 "generator raised StopIteration");
163 PyErr_Fetch(&exc, &val2, &tb);
164 PyErr_NormalizeException(&exc, &val2, &tb);
Yury Selivanov18c30a22015-05-10 15:09:46 -0400165 Py_INCREF(val);
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400166 PyException_SetCause(val2, val);
167 PyException_SetContext(val2, val);
168 PyErr_Restore(exc, val2, tb);
169 }
170 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200171
172 if (!result || f->f_stacktop == NULL) {
173 /* generator can't be rerun, so release the frame */
174 /* first clean reference cycle through stored exception traceback */
175 PyObject *t, *v, *tb;
176 t = f->f_exc_type;
177 v = f->f_exc_value;
178 tb = f->f_exc_traceback;
179 f->f_exc_type = NULL;
180 f->f_exc_value = NULL;
181 f->f_exc_traceback = NULL;
182 Py_XDECREF(t);
183 Py_XDECREF(v);
184 Py_XDECREF(tb);
Antoine Pitrou58720d62013-08-05 23:26:40 +0200185 gen->gi_frame->f_gen = NULL;
Antoine Pitrou93963562013-05-14 20:37:52 +0200186 gen->gi_frame = NULL;
187 Py_DECREF(f);
188 }
189
190 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000191}
192
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000193PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194"send(arg) -> send 'arg' into generator,\n\
195return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000196
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500197PyObject *
198_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000199{
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500200 return gen_send_ex(gen, arg, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000201}
202
203PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400204"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000205
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000206/*
207 * This helper function is used by gen_close and gen_throw to
208 * close a subiterator being delegated to by yield-from.
209 */
210
Antoine Pitrou93963562013-05-14 20:37:52 +0200211static int
212gen_close_iter(PyObject *yf)
213{
214 PyObject *retval = NULL;
215 _Py_IDENTIFIER(close);
216
217 if (PyGen_CheckExact(yf)) {
218 retval = gen_close((PyGenObject *)yf, NULL);
219 if (retval == NULL)
220 return -1;
221 } else {
222 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
223 if (meth == NULL) {
224 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
225 PyErr_WriteUnraisable(yf);
226 PyErr_Clear();
227 } else {
228 retval = PyObject_CallFunction(meth, "");
229 Py_DECREF(meth);
230 if (retval == NULL)
231 return -1;
232 }
233 }
234 Py_XDECREF(retval);
235 return 0;
236}
237
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500238static PyObject *
239gen_yf(PyGenObject *gen)
240{
Antoine Pitrou93963562013-05-14 20:37:52 +0200241 PyObject *yf = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500242 PyFrameObject *f = gen->gi_frame;
Antoine Pitrou93963562013-05-14 20:37:52 +0200243
244 if (f && f->f_stacktop) {
245 PyObject *bytecode = f->f_code->co_code;
246 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
247
248 if (code[f->f_lasti + 1] != YIELD_FROM)
249 return NULL;
250 yf = f->f_stacktop[-1];
251 Py_INCREF(yf);
252 }
253
254 return yf;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500255}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000256
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000257static PyObject *
258gen_close(PyGenObject *gen, PyObject *args)
259{
Antoine Pitrou93963562013-05-14 20:37:52 +0200260 PyObject *retval;
261 PyObject *yf = gen_yf(gen);
262 int err = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000263
Antoine Pitrou93963562013-05-14 20:37:52 +0200264 if (yf) {
265 gen->gi_running = 1;
266 err = gen_close_iter(yf);
267 gen->gi_running = 0;
268 Py_DECREF(yf);
269 }
270 if (err == 0)
271 PyErr_SetNone(PyExc_GeneratorExit);
272 retval = gen_send_ex(gen, Py_None, 1);
273 if (retval) {
274 Py_DECREF(retval);
275 PyErr_SetString(PyExc_RuntimeError,
276 "generator ignored GeneratorExit");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 return NULL;
278 }
Antoine Pitrou93963562013-05-14 20:37:52 +0200279 if (PyErr_ExceptionMatches(PyExc_StopIteration)
280 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
281 PyErr_Clear(); /* ignore these errors */
282 Py_INCREF(Py_None);
283 return Py_None;
284 }
285 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000286}
287
Antoine Pitrou93963562013-05-14 20:37:52 +0200288
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000289PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000290"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
291return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000292
293static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000294gen_throw(PyGenObject *gen, PyObject *args)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 PyObject *typ;
297 PyObject *tb = NULL;
298 PyObject *val = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500299 PyObject *yf = gen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000300 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
303 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000304
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000305 if (yf) {
306 PyObject *ret;
307 int err;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000308 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500309 gen->gi_running = 1;
Antoine Pitrou93963562013-05-14 20:37:52 +0200310 err = gen_close_iter(yf);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500311 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000312 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000313 if (err < 0)
314 return gen_send_ex(gen, Py_None, 1);
315 goto throw_here;
316 }
317 if (PyGen_CheckExact(yf)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500318 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000319 ret = gen_throw((PyGenObject *)yf, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500320 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000321 } else {
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000322 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000323 if (meth == NULL) {
324 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
325 Py_DECREF(yf);
326 return NULL;
327 }
328 PyErr_Clear();
329 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000330 goto throw_here;
331 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500332 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000333 ret = PyObject_CallObject(meth, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500334 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000335 Py_DECREF(meth);
336 }
337 Py_DECREF(yf);
338 if (!ret) {
339 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500340 /* Pop subiterator from stack */
341 ret = *(--gen->gi_frame->f_stacktop);
342 assert(ret == yf);
343 Py_DECREF(ret);
344 /* Termination repetition of YIELD_FROM */
345 gen->gi_frame->f_lasti++;
Nick Coghlanc40bc092012-06-17 15:15:49 +1000346 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000347 ret = gen_send_ex(gen, val, 0);
348 Py_DECREF(val);
349 } else {
350 ret = gen_send_ex(gen, Py_None, 1);
351 }
352 }
353 return ret;
354 }
355
356throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 /* First, check the traceback argument, replacing None with
358 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400359 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 else if (tb != NULL && !PyTraceBack_Check(tb)) {
363 PyErr_SetString(PyExc_TypeError,
364 "throw() third argument must be a traceback object");
365 return NULL;
366 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 Py_INCREF(typ);
369 Py_XINCREF(val);
370 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000371
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400372 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 else if (PyExceptionInstance_Check(typ)) {
376 /* Raising an instance. The value should be a dummy. */
377 if (val && val != Py_None) {
378 PyErr_SetString(PyExc_TypeError,
379 "instance exception may not have a separate value");
380 goto failed_throw;
381 }
382 else {
383 /* Normalize to raise <class>, <instance> */
384 Py_XDECREF(val);
385 val = typ;
386 typ = PyExceptionInstance_Class(typ);
387 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200388
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400389 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200390 /* Returns NULL if there's no traceback */
391 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 }
393 }
394 else {
395 /* Not something you can raise. throw() fails. */
396 PyErr_Format(PyExc_TypeError,
397 "exceptions must be classes or instances "
398 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000399 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 goto failed_throw;
401 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyErr_Restore(typ, val, tb);
404 return gen_send_ex(gen, Py_None, 1);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000405
406failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 /* Didn't use our arguments, so restore their original refcounts */
408 Py_DECREF(typ);
409 Py_XDECREF(val);
410 Py_XDECREF(tb);
411 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000412}
413
414
415static PyObject *
416gen_iternext(PyGenObject *gen)
417{
Yury Selivanov75445082015-05-11 22:57:16 -0400418 if (((PyCodeObject*)gen->gi_code)->co_flags & CO_COROUTINE) {
419 PyErr_SetString(PyExc_TypeError,
420 "coroutine-objects do not support iteration");
421 return NULL;
422 }
423
Antoine Pitrou667f5452014-07-08 18:43:23 -0400424 return gen_send_ex(gen, NULL, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000425}
426
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000427/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000428 * If StopIteration exception is set, fetches its 'value'
429 * attribute if any, otherwise sets pvalue to None.
430 *
431 * Returns 0 if no exception or StopIteration is set.
432 * If any other exception is set, returns -1 and leaves
433 * pvalue unchanged.
434 */
435
436int
Nick Coghlanc40bc092012-06-17 15:15:49 +1000437_PyGen_FetchStopIterationValue(PyObject **pvalue) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000438 PyObject *et, *ev, *tb;
439 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500440
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000441 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
442 PyErr_Fetch(&et, &ev, &tb);
Antoine Pitrou7403e912015-04-26 18:46:40 +0200443 if (ev) {
444 /* exception will usually be normalised already */
445 if (Py_TYPE(ev) == (PyTypeObject *) et
446 || PyObject_IsInstance(ev, PyExc_StopIteration)) {
447 value = ((PyStopIterationObject *)ev)->value;
448 Py_INCREF(value);
449 Py_DECREF(ev);
450 } else if (et == PyExc_StopIteration) {
451 /* avoid normalisation and take ev as value */
452 value = ev;
453 } else {
454 /* normalisation required */
455 PyErr_NormalizeException(&et, &ev, &tb);
456 if (!PyObject_IsInstance(ev, PyExc_StopIteration)) {
457 PyErr_Restore(et, ev, tb);
458 return -1;
459 }
460 value = ((PyStopIterationObject *)ev)->value;
461 Py_INCREF(value);
462 Py_DECREF(ev);
463 }
464 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000465 Py_XDECREF(et);
466 Py_XDECREF(tb);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000467 } else if (PyErr_Occurred()) {
468 return -1;
469 }
470 if (value == NULL) {
471 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100472 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000473 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000474 *pvalue = value;
475 return 0;
476}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000477
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000478static PyObject *
479gen_repr(PyGenObject *gen)
480{
Yury Selivanov75445082015-05-11 22:57:16 -0400481 if (PyGen_CheckCoroutineExact(gen)) {
482 return PyUnicode_FromFormat("<coroutine object %S at %p>",
483 gen->gi_qualname, gen);
484 }
485 else {
486 return PyUnicode_FromFormat("<generator object %S at %p>",
487 gen->gi_qualname, gen);
488 }
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000489}
490
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000491static PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200492gen_get_name(PyGenObject *op)
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000493{
Victor Stinner40ee3012014-06-16 15:59:28 +0200494 Py_INCREF(op->gi_name);
495 return op->gi_name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000496}
497
Victor Stinner40ee3012014-06-16 15:59:28 +0200498static int
499gen_set_name(PyGenObject *op, PyObject *value)
500{
501 PyObject *tmp;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000502
Victor Stinner40ee3012014-06-16 15:59:28 +0200503 /* Not legal to del gen.gi_name or to set it to anything
504 * other than a string object. */
505 if (value == NULL || !PyUnicode_Check(value)) {
506 PyErr_SetString(PyExc_TypeError,
507 "__name__ must be set to a string object");
508 return -1;
509 }
510 tmp = op->gi_name;
511 Py_INCREF(value);
512 op->gi_name = value;
513 Py_DECREF(tmp);
514 return 0;
515}
516
517static PyObject *
518gen_get_qualname(PyGenObject *op)
519{
520 Py_INCREF(op->gi_qualname);
521 return op->gi_qualname;
522}
523
Yury Selivanov75445082015-05-11 22:57:16 -0400524static PyObject *
525gen_get_iter(PyGenObject *gen)
526{
527 if (((PyCodeObject*)gen->gi_code)->co_flags & CO_COROUTINE) {
528 PyErr_SetString(PyExc_TypeError,
529 "coroutine-objects do not support iteration");
530 return NULL;
531 }
532
533 Py_INCREF(gen);
Yury Selivanovdf52e672015-05-11 23:23:05 -0400534 return (PyObject *)gen;
Yury Selivanov75445082015-05-11 22:57:16 -0400535}
536
Victor Stinner40ee3012014-06-16 15:59:28 +0200537static int
538gen_set_qualname(PyGenObject *op, PyObject *value)
539{
540 PyObject *tmp;
541
542 /* Not legal to del gen.__qualname__ or to set it to anything
543 * other than a string object. */
544 if (value == NULL || !PyUnicode_Check(value)) {
545 PyErr_SetString(PyExc_TypeError,
546 "__qualname__ must be set to a string object");
547 return -1;
548 }
549 tmp = op->gi_qualname;
550 Py_INCREF(value);
551 op->gi_qualname = value;
552 Py_DECREF(tmp);
553 return 0;
554}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000555
556static PyGetSetDef gen_getsetlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200557 {"__name__", (getter)gen_get_name, (setter)gen_set_name,
558 PyDoc_STR("name of the generator")},
559 {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname,
560 PyDoc_STR("qualified name of the generator")},
561 {NULL} /* Sentinel */
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000562};
563
Martin v. Löwise440e472004-06-01 15:22:42 +0000564static PyMemberDef gen_memberlist[] = {
Victor Stinner40ee3012014-06-16 15:59:28 +0200565 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
566 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
567 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000569};
570
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000571static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500572 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
574 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
575 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000576};
577
Martin v. Löwise440e472004-06-01 15:22:42 +0000578PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 PyVarObject_HEAD_INIT(&PyType_Type, 0)
580 "generator", /* tp_name */
581 sizeof(PyGenObject), /* tp_basicsize */
582 0, /* tp_itemsize */
583 /* methods */
584 (destructor)gen_dealloc, /* tp_dealloc */
585 0, /* tp_print */
586 0, /* tp_getattr */
587 0, /* tp_setattr */
Yury Selivanov75445082015-05-11 22:57:16 -0400588 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 (reprfunc)gen_repr, /* tp_repr */
590 0, /* tp_as_number */
591 0, /* tp_as_sequence */
592 0, /* tp_as_mapping */
593 0, /* tp_hash */
594 0, /* tp_call */
595 0, /* tp_str */
596 PyObject_GenericGetAttr, /* tp_getattro */
597 0, /* tp_setattro */
598 0, /* tp_as_buffer */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200599 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
600 Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 0, /* tp_doc */
602 (traverseproc)gen_traverse, /* tp_traverse */
603 0, /* tp_clear */
604 0, /* tp_richcompare */
605 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Yury Selivanov75445082015-05-11 22:57:16 -0400606 (getiterfunc)gen_get_iter, /* tp_iter */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 (iternextfunc)gen_iternext, /* tp_iternext */
608 gen_methods, /* tp_methods */
609 gen_memberlist, /* tp_members */
610 gen_getsetlist, /* tp_getset */
611 0, /* tp_base */
612 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 0, /* tp_descr_get */
615 0, /* tp_descr_set */
616 0, /* tp_dictoffset */
617 0, /* tp_init */
618 0, /* tp_alloc */
619 0, /* tp_new */
620 0, /* tp_free */
621 0, /* tp_is_gc */
622 0, /* tp_bases */
623 0, /* tp_mro */
624 0, /* tp_cache */
625 0, /* tp_subclasses */
626 0, /* tp_weaklist */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200627 0, /* tp_del */
628 0, /* tp_version_tag */
Antoine Pitrou58720d62013-08-05 23:26:40 +0200629 _PyGen_Finalize, /* tp_finalize */
Martin v. Löwise440e472004-06-01 15:22:42 +0000630};
631
632PyObject *
Victor Stinner40ee3012014-06-16 15:59:28 +0200633PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
Martin v. Löwise440e472004-06-01 15:22:42 +0000634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
636 if (gen == NULL) {
637 Py_DECREF(f);
638 return NULL;
639 }
640 gen->gi_frame = f;
Antoine Pitrou58720d62013-08-05 23:26:40 +0200641 f->f_gen = (PyObject *) gen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 Py_INCREF(f->f_code);
643 gen->gi_code = (PyObject *)(f->f_code);
644 gen->gi_running = 0;
645 gen->gi_weakreflist = NULL;
Victor Stinner40ee3012014-06-16 15:59:28 +0200646 if (name != NULL)
647 gen->gi_name = name;
648 else
649 gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name;
650 Py_INCREF(gen->gi_name);
651 if (qualname != NULL)
652 gen->gi_qualname = qualname;
653 else
654 gen->gi_qualname = gen->gi_name;
655 Py_INCREF(gen->gi_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 _PyObject_GC_TRACK(gen);
657 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000658}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000659
Victor Stinner40ee3012014-06-16 15:59:28 +0200660PyObject *
661PyGen_New(PyFrameObject *f)
662{
663 return PyGen_NewWithQualName(f, NULL, NULL);
664}
665
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000666int
667PyGen_NeedsFinalizing(PyGenObject *gen)
668{
Antoine Pitrou93963562013-05-14 20:37:52 +0200669 int i;
670 PyFrameObject *f = gen->gi_frame;
671
672 if (f == NULL || f->f_stacktop == NULL)
673 return 0; /* no frame or empty blockstack == no finalization */
674
675 /* Any block type besides a loop requires cleanup. */
676 for (i = 0; i < f->f_iblock; i++)
677 if (f->f_blockstack[i].b_type != SETUP_LOOP)
678 return 1;
679
680 /* No blocks except loops, it's safe to skip finalization. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000682}
Yury Selivanov75445082015-05-11 22:57:16 -0400683
684/*
685 * This helper function returns an awaitable for `o`:
686 * - `o` if `o` is a coroutine-object;
687 * - `type(o)->tp_as_async->am_await(o)`
688 *
689 * Raises a TypeError if it's not possible to return
690 * an awaitable and returns NULL.
691 */
692PyObject *
693_PyGen_GetAwaitableIter(PyObject *o)
694{
695 getawaitablefunc getter = NULL;
696 PyTypeObject *ot;
697
698 if (PyGen_CheckCoroutineExact(o)) {
699 /* Fast path. It's a central function for 'await'. */
700 Py_INCREF(o);
701 return o;
702 }
703
704 ot = Py_TYPE(o);
705 if (ot->tp_as_async != NULL) {
706 getter = ot->tp_as_async->am_await;
707 }
708 if (getter != NULL) {
709 PyObject *res = (*getter)(o);
710 if (res != NULL) {
711 if (!PyIter_Check(res)) {
712 PyErr_Format(PyExc_TypeError,
713 "__await__() returned non-iterator "
714 "of type '%.100s'",
715 Py_TYPE(res)->tp_name);
716 Py_CLEAR(res);
717 }
718 else {
719 if (PyGen_CheckCoroutineExact(res)) {
720 /* __await__ must return an *iterator*, not
721 a coroutine or another awaitable (see PEP 492) */
722 PyErr_SetString(PyExc_TypeError,
723 "__await__() returned a coroutine");
724 Py_CLEAR(res);
725 }
726 }
727 }
728 return res;
729 }
730
731 PyErr_Format(PyExc_TypeError,
732 "object %.100s can't be used in 'await' expression",
733 ot->tp_name);
734
735 return NULL;
736}