blob: 6018e5b1a0c87f2d5b195f7c2d6ea663f2899ece [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);
15 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000016}
17
18static void
19gen_dealloc(PyGenObject *gen)
20{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 if (gen->gi_weakreflist != NULL)
26 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 _PyObject_GC_TRACK(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) {
31 /* Generator is paused, so we need to close */
32 Py_TYPE(gen)->tp_del(self);
33 if (self->ob_refcnt > 0)
34 return; /* resurrected. :( */
35 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 _PyObject_GC_UNTRACK(self);
38 Py_CLEAR(gen->gi_frame);
39 Py_CLEAR(gen->gi_code);
40 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +000041}
42
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000043
Martin v. Löwise440e472004-06-01 15:22:42 +000044static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000045gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
Martin v. Löwise440e472004-06-01 15:22:42 +000046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 PyThreadState *tstate = PyThreadState_GET();
48 PyFrameObject *f = gen->gi_frame;
49 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +000050
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -050051 if (gen->gi_running) {
52 PyErr_SetString(PyExc_ValueError,
53 "generator already executing");
54 return NULL;
55 }
Benjamin Petersonf50af112012-03-15 15:37:54 -050056 if (f == NULL || f->f_stacktop == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 /* Only set exception if called from send() */
58 if (arg && !exc)
59 PyErr_SetNone(PyExc_StopIteration);
60 return NULL;
61 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 if (f->f_lasti == -1) {
64 if (arg && arg != Py_None) {
65 PyErr_SetString(PyExc_TypeError,
66 "can't send non-None value to a "
67 "just-started generator");
68 return NULL;
69 }
70 } else {
71 /* Push arg onto the frame's value stack */
72 result = arg ? arg : Py_None;
73 Py_INCREF(result);
74 *(f->f_stacktop++) = result;
75 }
Martin v. Löwise440e472004-06-01 15:22:42 +000076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 /* Generators always return to their most recent caller, not
78 * necessarily their creator. */
79 Py_XINCREF(tstate->frame);
80 assert(f->f_back == NULL);
81 f->f_back = tstate->frame;
Martin v. Löwise440e472004-06-01 15:22:42 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 gen->gi_running = 1;
84 result = PyEval_EvalFrameEx(f, exc);
85 gen->gi_running = 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 /* Don't keep the reference to f_back any longer than necessary. It
88 * may keep a chain of frames alive or it could create a reference
89 * cycle. */
90 assert(f->f_back == tstate->frame);
91 Py_CLEAR(f->f_back);
Martin v. Löwise440e472004-06-01 15:22:42 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 /* If the generator just returned (as opposed to yielding), signal
94 * that the generator is exhausted. */
Nick Coghlan1f7ce622012-01-13 21:43:40 +100095 if (result && f->f_stacktop == NULL) {
96 if (result == Py_None) {
97 /* Delay exception instantiation if we can */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 PyErr_SetNone(PyExc_StopIteration);
Nick Coghlan1f7ce622012-01-13 21:43:40 +100099 } else {
Nick Coghlanc40bc092012-06-17 15:15:49 +1000100 PyObject *e = PyObject_CallFunctionObjArgs(
101 PyExc_StopIteration, result, NULL);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000102 if (e != NULL) {
103 PyErr_SetObject(PyExc_StopIteration, e);
104 Py_DECREF(e);
105 }
106 }
107 Py_CLEAR(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 if (!result || f->f_stacktop == NULL) {
111 /* generator can't be rerun, so release the frame */
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200112 /* first clean reference cycle through stored exception traceback */
113 PyObject *t, *v, *tb;
114 t = f->f_exc_type;
115 v = f->f_exc_value;
116 tb = f->f_exc_traceback;
117 f->f_exc_type = NULL;
118 f->f_exc_value = NULL;
119 f->f_exc_traceback = NULL;
120 Py_XDECREF(t);
121 Py_XDECREF(v);
122 Py_XDECREF(tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 gen->gi_frame = NULL;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000124 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 }
Martin v. Löwise440e472004-06-01 15:22:42 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000128}
129
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000130PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000131"send(arg) -> send 'arg' into generator,\n\
132return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000133
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500134PyObject *
135_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000136{
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500137 return gen_send_ex(gen, arg, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000138}
139
140PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400141"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000142
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000143/*
144 * This helper function is used by gen_close and gen_throw to
145 * close a subiterator being delegated to by yield-from.
146 */
147
148static int
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500149gen_close_iter(PyObject *yf)
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000150{
151 PyObject *retval = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500152
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000153 if (PyGen_CheckExact(yf)) {
154 retval = gen_close((PyGenObject *)yf, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500155 if (retval == NULL)
156 return -1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000157 } else {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500158 PyObject *meth = PyObject_GetAttrString(yf, "close");
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000159 if (meth == NULL) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500160 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000161 PyErr_WriteUnraisable(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000162 PyErr_Clear();
163 } else {
164 retval = PyObject_CallFunction(meth, "");
165 Py_DECREF(meth);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500166 if (retval == NULL)
167 return -1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000168 }
169 }
170 Py_XDECREF(retval);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500171 return 0;
172}
173
174static PyObject *
175gen_yf(PyGenObject *gen)
176{
177 PyObject *yf = NULL;
178 PyFrameObject *f = gen->gi_frame;
179
180 if (f) {
181 PyObject *bytecode = f->f_code->co_code;
182 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
183
184 if (code[f->f_lasti + 1] != YIELD_FROM)
185 return NULL;
186 yf = f->f_stacktop[-1];
187 Py_INCREF(yf);
188 }
189
190 return yf;
191}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000192
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000193static PyObject *
194gen_close(PyGenObject *gen, PyObject *args)
195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 PyObject *retval;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500197 PyObject *yf = gen_yf(gen);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000198 int err = 0;
199
200 if (yf) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500201 gen->gi_running = 1;
202 err = gen_close_iter(yf);
203 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000204 Py_DECREF(yf);
205 }
206 if (err == 0)
207 PyErr_SetNone(PyExc_GeneratorExit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 retval = gen_send_ex(gen, Py_None, 1);
209 if (retval) {
210 Py_DECREF(retval);
211 PyErr_SetString(PyExc_RuntimeError,
212 "generator ignored GeneratorExit");
213 return NULL;
214 }
215 if (PyErr_ExceptionMatches(PyExc_StopIteration)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500216 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyErr_Clear(); /* ignore these errors */
218 Py_INCREF(Py_None);
219 return Py_None;
220 }
221 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000222}
223
224static void
225gen_del(PyObject *self)
226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 PyObject *res;
228 PyObject *error_type, *error_value, *error_traceback;
229 PyGenObject *gen = (PyGenObject *)self;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
232 /* Generator isn't paused, so no need to close */
233 return;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 /* Temporarily resurrect the object. */
236 assert(self->ob_refcnt == 0);
237 self->ob_refcnt = 1;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 /* Save the current exception, if any. */
240 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 res = gen_close(gen, NULL);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (res == NULL)
245 PyErr_WriteUnraisable(self);
246 else
247 Py_DECREF(res);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Restore the saved exception. */
250 PyErr_Restore(error_type, error_value, error_traceback);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 /* Undo the temporary resurrection; can't use DECREF here, it would
253 * cause a recursive call.
254 */
255 assert(self->ob_refcnt > 0);
256 if (--self->ob_refcnt == 0)
257 return; /* this is the normal path out */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 /* close() resurrected it! Make it look like the original Py_DECREF
260 * never happened.
261 */
262 {
263 Py_ssize_t refcnt = self->ob_refcnt;
264 _Py_NewReference(self);
265 self->ob_refcnt = refcnt;
266 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000267 assert(PyType_IS_GC(Py_TYPE(self)) &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
271 * we need to undo that. */
272 _Py_DEC_REFTOTAL;
273 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
274 * chain, so no more to do there.
275 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
276 * _Py_NewReference bumped tp_allocs: both of those need to be
277 * undone.
278 */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000279#ifdef COUNT_ALLOCS
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000280 --(Py_TYPE(self)->tp_frees);
281 --(Py_TYPE(self)->tp_allocs);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000282#endif
283}
284
285
286
287PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000288"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
289return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000290
291static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000292gen_throw(PyGenObject *gen, PyObject *args)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 PyObject *typ;
295 PyObject *tb = NULL;
296 PyObject *val = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500297 PyObject *yf = gen_yf(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
300 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000301
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000302 if (yf) {
303 PyObject *ret;
304 int err;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000305 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500306 gen->gi_running = 1;
307 err = gen_close_iter(yf);
308 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000309 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000310 if (err < 0)
311 return gen_send_ex(gen, Py_None, 1);
312 goto throw_here;
313 }
314 if (PyGen_CheckExact(yf)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500315 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000316 ret = gen_throw((PyGenObject *)yf, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500317 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000318 } else {
319 PyObject *meth = PyObject_GetAttrString(yf, "throw");
320 if (meth == NULL) {
321 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
322 Py_DECREF(yf);
323 return NULL;
324 }
325 PyErr_Clear();
326 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000327 goto throw_here;
328 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500329 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000330 ret = PyObject_CallObject(meth, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500331 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000332 Py_DECREF(meth);
333 }
334 Py_DECREF(yf);
335 if (!ret) {
336 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500337 /* Pop subiterator from stack */
338 ret = *(--gen->gi_frame->f_stacktop);
339 assert(ret == yf);
340 Py_DECREF(ret);
341 /* Termination repetition of YIELD_FROM */
342 gen->gi_frame->f_lasti++;
Nick Coghlanc40bc092012-06-17 15:15:49 +1000343 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000344 ret = gen_send_ex(gen, val, 0);
345 Py_DECREF(val);
346 } else {
347 ret = gen_send_ex(gen, Py_None, 1);
348 }
349 }
350 return ret;
351 }
352
353throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 /* First, check the traceback argument, replacing None with
355 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400356 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400358 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 else if (tb != NULL && !PyTraceBack_Check(tb)) {
360 PyErr_SetString(PyExc_TypeError,
361 "throw() third argument must be a traceback object");
362 return NULL;
363 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 Py_INCREF(typ);
366 Py_XINCREF(val);
367 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000368
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400369 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 else if (PyExceptionInstance_Check(typ)) {
373 /* Raising an instance. The value should be a dummy. */
374 if (val && val != Py_None) {
375 PyErr_SetString(PyExc_TypeError,
376 "instance exception may not have a separate value");
377 goto failed_throw;
378 }
379 else {
380 /* Normalize to raise <class>, <instance> */
381 Py_XDECREF(val);
382 val = typ;
383 typ = PyExceptionInstance_Class(typ);
384 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200385
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400386 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200387 /* Returns NULL if there's no traceback */
388 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 }
390 }
391 else {
392 /* Not something you can raise. throw() fails. */
393 PyErr_Format(PyExc_TypeError,
394 "exceptions must be classes or instances "
395 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000396 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 goto failed_throw;
398 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 PyErr_Restore(typ, val, tb);
401 return gen_send_ex(gen, Py_None, 1);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000402
403failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 /* Didn't use our arguments, so restore their original refcounts */
405 Py_DECREF(typ);
406 Py_XDECREF(val);
407 Py_XDECREF(tb);
408 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000409}
410
411
412static PyObject *
413gen_iternext(PyGenObject *gen)
414{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000415 PyObject *val = NULL;
416 PyObject *ret;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500417 ret = gen_send_ex(gen, val, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000418 Py_XDECREF(val);
419 return ret;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000420}
421
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000422/*
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000423 * If StopIteration exception is set, fetches its 'value'
424 * attribute if any, otherwise sets pvalue to None.
425 *
426 * Returns 0 if no exception or StopIteration is set.
427 * If any other exception is set, returns -1 and leaves
428 * pvalue unchanged.
429 */
430
431int
Nick Coghlanc40bc092012-06-17 15:15:49 +1000432_PyGen_FetchStopIterationValue(PyObject **pvalue) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000433 PyObject *et, *ev, *tb;
434 PyObject *value = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500435
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000436 if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
437 PyErr_Fetch(&et, &ev, &tb);
438 Py_XDECREF(et);
439 Py_XDECREF(tb);
440 if (ev) {
441 value = ((PyStopIterationObject *)ev)->value;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100442 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000443 Py_DECREF(ev);
444 }
445 } else if (PyErr_Occurred()) {
446 return -1;
447 }
448 if (value == NULL) {
449 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100450 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000451 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000452 *pvalue = value;
453 return 0;
454}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000455
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000456static PyObject *
457gen_repr(PyGenObject *gen)
458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 return PyUnicode_FromFormat("<generator object %S at %p>",
460 ((PyCodeObject *)gen->gi_code)->co_name,
461 gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000462}
463
464
465static PyObject *
466gen_get_name(PyGenObject *gen)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name;
469 Py_INCREF(name);
470 return name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000471}
472
473
474PyDoc_STRVAR(gen__name__doc__,
475"Return the name of the generator's associated code object.");
476
477static PyGetSetDef gen_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 {"__name__", (getter)gen_get_name, NULL, gen__name__doc__},
479 {NULL}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000480};
481
482
Martin v. Löwise440e472004-06-01 15:22:42 +0000483static PyMemberDef gen_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
Benjamin Peterson657e9eb2012-03-07 18:17:03 -0600485 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
487 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000488};
489
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000490static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500491 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
493 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
494 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000495};
496
Martin v. Löwise440e472004-06-01 15:22:42 +0000497PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 PyVarObject_HEAD_INIT(&PyType_Type, 0)
499 "generator", /* tp_name */
500 sizeof(PyGenObject), /* tp_basicsize */
501 0, /* tp_itemsize */
502 /* methods */
503 (destructor)gen_dealloc, /* tp_dealloc */
504 0, /* tp_print */
505 0, /* tp_getattr */
506 0, /* tp_setattr */
507 0, /* tp_reserved */
508 (reprfunc)gen_repr, /* tp_repr */
509 0, /* tp_as_number */
510 0, /* tp_as_sequence */
511 0, /* tp_as_mapping */
512 0, /* tp_hash */
513 0, /* tp_call */
514 0, /* tp_str */
515 PyObject_GenericGetAttr, /* tp_getattro */
516 0, /* tp_setattro */
517 0, /* tp_as_buffer */
518 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
519 0, /* tp_doc */
520 (traverseproc)gen_traverse, /* tp_traverse */
521 0, /* tp_clear */
522 0, /* tp_richcompare */
523 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
524 PyObject_SelfIter, /* tp_iter */
525 (iternextfunc)gen_iternext, /* tp_iternext */
526 gen_methods, /* tp_methods */
527 gen_memberlist, /* tp_members */
528 gen_getsetlist, /* tp_getset */
529 0, /* tp_base */
530 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 0, /* tp_descr_get */
533 0, /* tp_descr_set */
534 0, /* tp_dictoffset */
535 0, /* tp_init */
536 0, /* tp_alloc */
537 0, /* tp_new */
538 0, /* tp_free */
539 0, /* tp_is_gc */
540 0, /* tp_bases */
541 0, /* tp_mro */
542 0, /* tp_cache */
543 0, /* tp_subclasses */
544 0, /* tp_weaklist */
545 gen_del, /* tp_del */
Martin v. Löwise440e472004-06-01 15:22:42 +0000546};
547
548PyObject *
549PyGen_New(PyFrameObject *f)
550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
552 if (gen == NULL) {
553 Py_DECREF(f);
554 return NULL;
555 }
556 gen->gi_frame = f;
557 Py_INCREF(f->f_code);
558 gen->gi_code = (PyObject *)(f->f_code);
559 gen->gi_running = 0;
560 gen->gi_weakreflist = NULL;
561 _PyObject_GC_TRACK(gen);
562 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000563}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000564
565int
566PyGen_NeedsFinalizing(PyGenObject *gen)
567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 int i;
569 PyFrameObject *f = gen->gi_frame;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000570
Benjamin Petersonf07c9a12011-07-03 17:23:22 -0500571 if (f == NULL || f->f_stacktop == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 return 0; /* no frame or empty blockstack == no finalization */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 /* Any block type besides a loop requires cleanup. */
Benjamin Petersonf07c9a12011-07-03 17:23:22 -0500575 for (i = 0; i < f->f_iblock; i++)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (f->f_blockstack[i].b_type != SETUP_LOOP)
577 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* No blocks except loops, it's safe to skip finalization. */
580 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000581}