blob: 2e74b8c9393833a4080082c0eaec3879f1443235 [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. */
Victor Stinner13105102013-12-13 02:17:29 +010079 f->f_tstate = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 Py_XINCREF(tstate->frame);
81 assert(f->f_back == NULL);
82 f->f_back = tstate->frame;
Martin v. Löwise440e472004-06-01 15:22:42 +000083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 gen->gi_running = 1;
85 result = PyEval_EvalFrameEx(f, exc);
86 gen->gi_running = 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 /* Don't keep the reference to f_back any longer than necessary. It
89 * may keep a chain of frames alive or it could create a reference
90 * cycle. */
91 assert(f->f_back == tstate->frame);
92 Py_CLEAR(f->f_back);
Victor Stinner13105102013-12-13 02:17:29 +010093 /* Clear the borrowed reference to the thread state */
94 f->f_tstate = NULL;
Martin v. Löwise440e472004-06-01 15:22:42 +000095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 /* If the generator just returned (as opposed to yielding), signal
97 * that the generator is exhausted. */
Nick Coghlan1f7ce622012-01-13 21:43:40 +100098 if (result && f->f_stacktop == NULL) {
99 if (result == Py_None) {
100 /* Delay exception instantiation if we can */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 PyErr_SetNone(PyExc_StopIteration);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000102 } else {
Nick Coghlanc40bc092012-06-17 15:15:49 +1000103 PyObject *e = PyObject_CallFunctionObjArgs(
104 PyExc_StopIteration, result, NULL);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000105 if (e != NULL) {
106 PyErr_SetObject(PyExc_StopIteration, e);
107 Py_DECREF(e);
108 }
109 }
110 Py_CLEAR(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 if (!result || f->f_stacktop == NULL) {
114 /* generator can't be rerun, so release the frame */
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200115 /* first clean reference cycle through stored exception traceback */
116 PyObject *t, *v, *tb;
117 t = f->f_exc_type;
118 v = f->f_exc_value;
119 tb = f->f_exc_traceback;
120 f->f_exc_type = NULL;
121 f->f_exc_value = NULL;
122 f->f_exc_traceback = NULL;
123 Py_XDECREF(t);
124 Py_XDECREF(v);
125 Py_XDECREF(tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 gen->gi_frame = NULL;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000127 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
Martin v. Löwise440e472004-06-01 15:22:42 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000131}
132
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000133PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134"send(arg) -> send 'arg' into generator,\n\
135return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000136
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500137PyObject *
138_PyGen_Send(PyGenObject *gen, PyObject *arg)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000139{
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500140 return gen_send_ex(gen, arg, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000141}
142
143PyDoc_STRVAR(close_doc,
Benjamin Petersonab3da292012-05-03 18:44:09 -0400144"close() -> raise GeneratorExit inside generator.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000145
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000146/*
147 * This helper function is used by gen_close and gen_throw to
148 * close a subiterator being delegated to by yield-from.
149 */
150
151static int
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500152gen_close_iter(PyObject *yf)
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000153{
154 PyObject *retval = NULL;
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000155 _Py_IDENTIFIER(close);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500156
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000157 if (PyGen_CheckExact(yf)) {
158 retval = gen_close((PyGenObject *)yf, NULL);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500159 if (retval == NULL)
160 return -1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000161 } else {
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000162 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000163 if (meth == NULL) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500164 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000165 PyErr_WriteUnraisable(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000166 PyErr_Clear();
167 } else {
168 retval = PyObject_CallFunction(meth, "");
169 Py_DECREF(meth);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500170 if (retval == NULL)
171 return -1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000172 }
173 }
174 Py_XDECREF(retval);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500175 return 0;
176}
177
178static PyObject *
179gen_yf(PyGenObject *gen)
180{
181 PyObject *yf = NULL;
182 PyFrameObject *f = gen->gi_frame;
183
Benjamin Petersonc9314d92013-04-10 17:00:56 -0400184 if (f && f->f_stacktop) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500185 PyObject *bytecode = f->f_code->co_code;
186 unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode);
187
188 if (code[f->f_lasti + 1] != YIELD_FROM)
189 return NULL;
190 yf = f->f_stacktop[-1];
191 Py_INCREF(yf);
192 }
193
194 return yf;
195}
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000196
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000197static PyObject *
198gen_close(PyGenObject *gen, PyObject *args)
199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 PyObject *retval;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500201 PyObject *yf = gen_yf(gen);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000202 int err = 0;
203
204 if (yf) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500205 gen->gi_running = 1;
206 err = gen_close_iter(yf);
207 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000208 Py_DECREF(yf);
209 }
210 if (err == 0)
211 PyErr_SetNone(PyExc_GeneratorExit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 retval = gen_send_ex(gen, Py_None, 1);
213 if (retval) {
214 Py_DECREF(retval);
215 PyErr_SetString(PyExc_RuntimeError,
216 "generator ignored GeneratorExit");
217 return NULL;
218 }
219 if (PyErr_ExceptionMatches(PyExc_StopIteration)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500220 || PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 PyErr_Clear(); /* ignore these errors */
222 Py_INCREF(Py_None);
223 return Py_None;
224 }
225 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000226}
227
228static void
229gen_del(PyObject *self)
230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 PyObject *res;
232 PyObject *error_type, *error_value, *error_traceback;
233 PyGenObject *gen = (PyGenObject *)self;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
236 /* Generator isn't paused, so no need to close */
237 return;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 /* Temporarily resurrect the object. */
240 assert(self->ob_refcnt == 0);
241 self->ob_refcnt = 1;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 /* Save the current exception, if any. */
244 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 res = gen_close(gen, NULL);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (res == NULL)
249 PyErr_WriteUnraisable(self);
250 else
251 Py_DECREF(res);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 /* Restore the saved exception. */
254 PyErr_Restore(error_type, error_value, error_traceback);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 /* Undo the temporary resurrection; can't use DECREF here, it would
257 * cause a recursive call.
258 */
259 assert(self->ob_refcnt > 0);
260 if (--self->ob_refcnt == 0)
261 return; /* this is the normal path out */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* close() resurrected it! Make it look like the original Py_DECREF
264 * never happened.
265 */
266 {
267 Py_ssize_t refcnt = self->ob_refcnt;
268 _Py_NewReference(self);
269 self->ob_refcnt = refcnt;
270 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000271 assert(PyType_IS_GC(Py_TYPE(self)) &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
275 * we need to undo that. */
276 _Py_DEC_REFTOTAL;
277 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
278 * chain, so no more to do there.
279 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
280 * _Py_NewReference bumped tp_allocs: both of those need to be
281 * undone.
282 */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000283#ifdef COUNT_ALLOCS
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000284 --(Py_TYPE(self)->tp_frees);
285 --(Py_TYPE(self)->tp_allocs);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000286#endif
287}
288
289
290
291PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000292"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
293return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000294
295static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000296gen_throw(PyGenObject *gen, PyObject *args)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 PyObject *typ;
299 PyObject *tb = NULL;
300 PyObject *val = NULL;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500301 PyObject *yf = gen_yf(gen);
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000302 _Py_IDENTIFIER(throw);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
305 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000306
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000307 if (yf) {
308 PyObject *ret;
309 int err;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000310 if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500311 gen->gi_running = 1;
312 err = gen_close_iter(yf);
313 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000314 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000315 if (err < 0)
316 return gen_send_ex(gen, Py_None, 1);
317 goto throw_here;
318 }
319 if (PyGen_CheckExact(yf)) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500320 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000321 ret = gen_throw((PyGenObject *)yf, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500322 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000323 } else {
Nick Coghlan5b0dac12012-06-17 15:45:11 +1000324 PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000325 if (meth == NULL) {
326 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
327 Py_DECREF(yf);
328 return NULL;
329 }
330 PyErr_Clear();
331 Py_DECREF(yf);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000332 goto throw_here;
333 }
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500334 gen->gi_running = 1;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000335 ret = PyObject_CallObject(meth, args);
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500336 gen->gi_running = 0;
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000337 Py_DECREF(meth);
338 }
339 Py_DECREF(yf);
340 if (!ret) {
341 PyObject *val;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500342 /* Pop subiterator from stack */
343 ret = *(--gen->gi_frame->f_stacktop);
344 assert(ret == yf);
345 Py_DECREF(ret);
346 /* Termination repetition of YIELD_FROM */
347 gen->gi_frame->f_lasti++;
Nick Coghlanc40bc092012-06-17 15:15:49 +1000348 if (_PyGen_FetchStopIterationValue(&val) == 0) {
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000349 ret = gen_send_ex(gen, val, 0);
350 Py_DECREF(val);
351 } else {
352 ret = gen_send_ex(gen, Py_None, 1);
353 }
354 }
355 return ret;
356 }
357
358throw_here:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 /* First, check the traceback argument, replacing None with
360 NULL. */
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400361 if (tb == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 tb = NULL;
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400363 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 else if (tb != NULL && !PyTraceBack_Check(tb)) {
365 PyErr_SetString(PyExc_TypeError,
366 "throw() third argument must be a traceback object");
367 return NULL;
368 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 Py_INCREF(typ);
371 Py_XINCREF(val);
372 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000373
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400374 if (PyExceptionClass_Check(typ))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyErr_NormalizeException(&typ, &val, &tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 else if (PyExceptionInstance_Check(typ)) {
378 /* Raising an instance. The value should be a dummy. */
379 if (val && val != Py_None) {
380 PyErr_SetString(PyExc_TypeError,
381 "instance exception may not have a separate value");
382 goto failed_throw;
383 }
384 else {
385 /* Normalize to raise <class>, <instance> */
386 Py_XDECREF(val);
387 val = typ;
388 typ = PyExceptionInstance_Class(typ);
389 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200390
Benjamin Peterson9d9141f2011-10-19 16:57:40 -0400391 if (tb == NULL)
Antoine Pitrou551ba202011-10-18 16:40:50 +0200392 /* Returns NULL if there's no traceback */
393 tb = PyException_GetTraceback(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 }
395 }
396 else {
397 /* Not something you can raise. throw() fails. */
398 PyErr_Format(PyExc_TypeError,
399 "exceptions must be classes or instances "
400 "deriving from BaseException, not %s",
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000401 Py_TYPE(typ)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 goto failed_throw;
403 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 PyErr_Restore(typ, val, tb);
406 return gen_send_ex(gen, Py_None, 1);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000407
408failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 /* Didn't use our arguments, so restore their original refcounts */
410 Py_DECREF(typ);
411 Py_XDECREF(val);
412 Py_XDECREF(tb);
413 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000414}
415
416
417static PyObject *
418gen_iternext(PyGenObject *gen)
419{
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000420 PyObject *val = NULL;
421 PyObject *ret;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500422 ret = gen_send_ex(gen, val, 0);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000423 Py_XDECREF(val);
424 return ret;
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);
443 Py_XDECREF(et);
444 Py_XDECREF(tb);
445 if (ev) {
446 value = ((PyStopIterationObject *)ev)->value;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100447 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000448 Py_DECREF(ev);
449 }
450 } else if (PyErr_Occurred()) {
451 return -1;
452 }
453 if (value == NULL) {
454 value = Py_None;
Amaury Forgeot d'Arce557da82012-01-13 21:06:12 +0100455 Py_INCREF(value);
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000456 }
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000457 *pvalue = value;
458 return 0;
459}
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000460
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000461static PyObject *
462gen_repr(PyGenObject *gen)
463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 return PyUnicode_FromFormat("<generator object %S at %p>",
465 ((PyCodeObject *)gen->gi_code)->co_name,
466 gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000467}
468
469
470static PyObject *
471gen_get_name(PyGenObject *gen)
472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name;
474 Py_INCREF(name);
475 return name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000476}
477
478
479PyDoc_STRVAR(gen__name__doc__,
480"Return the name of the generator's associated code object.");
481
482static PyGetSetDef gen_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 {"__name__", (getter)gen_get_name, NULL, gen__name__doc__},
484 {NULL}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000485};
486
487
Martin v. Löwise440e472004-06-01 15:22:42 +0000488static PyMemberDef gen_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
Benjamin Peterson657e9eb2012-03-07 18:17:03 -0600490 {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
492 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000493};
494
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000495static PyMethodDef gen_methods[] = {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500496 {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
498 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
499 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000500};
501
Martin v. Löwise440e472004-06-01 15:22:42 +0000502PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 PyVarObject_HEAD_INIT(&PyType_Type, 0)
504 "generator", /* tp_name */
505 sizeof(PyGenObject), /* tp_basicsize */
506 0, /* tp_itemsize */
507 /* methods */
508 (destructor)gen_dealloc, /* tp_dealloc */
509 0, /* tp_print */
510 0, /* tp_getattr */
511 0, /* tp_setattr */
512 0, /* tp_reserved */
513 (reprfunc)gen_repr, /* tp_repr */
514 0, /* tp_as_number */
515 0, /* tp_as_sequence */
516 0, /* tp_as_mapping */
517 0, /* tp_hash */
518 0, /* tp_call */
519 0, /* tp_str */
520 PyObject_GenericGetAttr, /* tp_getattro */
521 0, /* tp_setattro */
522 0, /* tp_as_buffer */
523 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
524 0, /* tp_doc */
525 (traverseproc)gen_traverse, /* tp_traverse */
526 0, /* tp_clear */
527 0, /* tp_richcompare */
528 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
529 PyObject_SelfIter, /* tp_iter */
530 (iternextfunc)gen_iternext, /* tp_iternext */
531 gen_methods, /* tp_methods */
532 gen_memberlist, /* tp_members */
533 gen_getsetlist, /* tp_getset */
534 0, /* tp_base */
535 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 0, /* tp_descr_get */
538 0, /* tp_descr_set */
539 0, /* tp_dictoffset */
540 0, /* tp_init */
541 0, /* tp_alloc */
542 0, /* tp_new */
543 0, /* tp_free */
544 0, /* tp_is_gc */
545 0, /* tp_bases */
546 0, /* tp_mro */
547 0, /* tp_cache */
548 0, /* tp_subclasses */
549 0, /* tp_weaklist */
550 gen_del, /* tp_del */
Martin v. Löwise440e472004-06-01 15:22:42 +0000551};
552
553PyObject *
554PyGen_New(PyFrameObject *f)
555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
557 if (gen == NULL) {
558 Py_DECREF(f);
559 return NULL;
560 }
561 gen->gi_frame = f;
562 Py_INCREF(f->f_code);
563 gen->gi_code = (PyObject *)(f->f_code);
564 gen->gi_running = 0;
565 gen->gi_weakreflist = NULL;
566 _PyObject_GC_TRACK(gen);
567 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000568}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000569
570int
571PyGen_NeedsFinalizing(PyGenObject *gen)
572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 int i;
574 PyFrameObject *f = gen->gi_frame;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000575
Benjamin Petersonf07c9a12011-07-03 17:23:22 -0500576 if (f == NULL || f->f_stacktop == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 return 0; /* no frame or empty blockstack == no finalization */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* Any block type besides a loop requires cleanup. */
Benjamin Petersonf07c9a12011-07-03 17:23:22 -0500580 for (i = 0; i < f->f_iblock; i++)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (f->f_blockstack[i].b_type != SETUP_LOOP)
582 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* No blocks except loops, it's safe to skip finalization. */
585 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000586}