blob: 49e2adeaa060f3daf8a6ad9697354d1ad4ac2371 [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
8static int
9gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
10{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 Py_VISIT((PyObject *)gen->gi_frame);
12 Py_VISIT(gen->gi_code);
13 return 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000014}
15
16static void
17gen_dealloc(PyGenObject *gen)
18{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019 PyObject *self = (PyObject *) gen;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000023 if (gen->gi_weakreflist != NULL)
24 PyObject_ClearWeakRefs(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 _PyObject_GC_TRACK(self);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) {
29 /* Generator is paused, so we need to close */
30 Py_TYPE(gen)->tp_del(self);
31 if (self->ob_refcnt > 0)
32 return; /* resurrected. :( */
33 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 _PyObject_GC_UNTRACK(self);
36 Py_CLEAR(gen->gi_frame);
37 Py_CLEAR(gen->gi_code);
38 PyObject_GC_Del(gen);
Martin v. Löwise440e472004-06-01 15:22:42 +000039}
40
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000041
Martin v. Löwise440e472004-06-01 15:22:42 +000042static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000043gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
Martin v. Löwise440e472004-06-01 15:22:42 +000044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 PyThreadState *tstate = PyThreadState_GET();
46 PyFrameObject *f = gen->gi_frame;
47 PyObject *result;
Martin v. Löwise440e472004-06-01 15:22:42 +000048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 if (gen->gi_running) {
50 PyErr_SetString(PyExc_ValueError,
51 "generator already executing");
52 return NULL;
53 }
54 if (f==NULL || f->f_stacktop == NULL) {
55 /* Only set exception if called from send() */
56 if (arg && !exc)
57 PyErr_SetNone(PyExc_StopIteration);
58 return NULL;
59 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 if (f->f_lasti == -1) {
62 if (arg && arg != Py_None) {
63 PyErr_SetString(PyExc_TypeError,
64 "can't send non-None value to a "
65 "just-started generator");
66 return NULL;
67 }
68 } else {
69 /* Push arg onto the frame's value stack */
70 result = arg ? arg : Py_None;
71 Py_INCREF(result);
72 *(f->f_stacktop++) = result;
73 }
Martin v. Löwise440e472004-06-01 15:22:42 +000074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 /* Generators always return to their most recent caller, not
76 * necessarily their creator. */
77 Py_XINCREF(tstate->frame);
78 assert(f->f_back == NULL);
79 f->f_back = tstate->frame;
Martin v. Löwise440e472004-06-01 15:22:42 +000080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 gen->gi_running = 1;
82 result = PyEval_EvalFrameEx(f, exc);
83 gen->gi_running = 0;
Martin v. Löwise440e472004-06-01 15:22:42 +000084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 /* Don't keep the reference to f_back any longer than necessary. It
86 * may keep a chain of frames alive or it could create a reference
87 * cycle. */
88 assert(f->f_back == tstate->frame);
89 Py_CLEAR(f->f_back);
Martin v. Löwise440e472004-06-01 15:22:42 +000090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 /* If the generator just returned (as opposed to yielding), signal
92 * that the generator is exhausted. */
93 if (result == Py_None && f->f_stacktop == NULL) {
94 Py_DECREF(result);
95 result = NULL;
96 /* Set exception if not called by gen_iternext() */
97 if (arg)
98 PyErr_SetNone(PyExc_StopIteration);
99 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 if (!result || f->f_stacktop == NULL) {
102 /* generator can't be rerun, so release the frame */
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200103 /* first clean reference cycle through stored exception traceback */
104 PyObject *t, *v, *tb;
105 t = f->f_exc_type;
106 v = f->f_exc_value;
107 tb = f->f_exc_traceback;
108 f->f_exc_type = NULL;
109 f->f_exc_value = NULL;
110 f->f_exc_traceback = NULL;
111 Py_XDECREF(t);
112 Py_XDECREF(v);
113 Py_XDECREF(tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 Py_DECREF(f);
115 gen->gi_frame = NULL;
116 }
Martin v. Löwise440e472004-06-01 15:22:42 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 return result;
Martin v. Löwise440e472004-06-01 15:22:42 +0000119}
120
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000121PyDoc_STRVAR(send_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000122"send(arg) -> send 'arg' into generator,\n\
123return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000124
125static PyObject *
126gen_send(PyGenObject *gen, PyObject *arg)
127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 return gen_send_ex(gen, arg, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000129}
130
131PyDoc_STRVAR(close_doc,
132"close(arg) -> raise GeneratorExit inside generator.");
133
134static PyObject *
135gen_close(PyGenObject *gen, PyObject *args)
136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 PyObject *retval;
138 PyErr_SetNone(PyExc_GeneratorExit);
139 retval = gen_send_ex(gen, Py_None, 1);
140 if (retval) {
141 Py_DECREF(retval);
142 PyErr_SetString(PyExc_RuntimeError,
143 "generator ignored GeneratorExit");
144 return NULL;
145 }
146 if (PyErr_ExceptionMatches(PyExc_StopIteration)
147 || PyErr_ExceptionMatches(PyExc_GeneratorExit))
148 {
149 PyErr_Clear(); /* ignore these errors */
150 Py_INCREF(Py_None);
151 return Py_None;
152 }
153 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000154}
155
156static void
157gen_del(PyObject *self)
158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 PyObject *res;
160 PyObject *error_type, *error_value, *error_traceback;
161 PyGenObject *gen = (PyGenObject *)self;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
164 /* Generator isn't paused, so no need to close */
165 return;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 /* Temporarily resurrect the object. */
168 assert(self->ob_refcnt == 0);
169 self->ob_refcnt = 1;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* Save the current exception, if any. */
172 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 res = gen_close(gen, NULL);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (res == NULL)
177 PyErr_WriteUnraisable(self);
178 else
179 Py_DECREF(res);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 /* Restore the saved exception. */
182 PyErr_Restore(error_type, error_value, error_traceback);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 /* Undo the temporary resurrection; can't use DECREF here, it would
185 * cause a recursive call.
186 */
187 assert(self->ob_refcnt > 0);
188 if (--self->ob_refcnt == 0)
189 return; /* this is the normal path out */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 /* close() resurrected it! Make it look like the original Py_DECREF
192 * never happened.
193 */
194 {
195 Py_ssize_t refcnt = self->ob_refcnt;
196 _Py_NewReference(self);
197 self->ob_refcnt = refcnt;
198 }
199 assert(PyType_IS_GC(self->ob_type) &&
200 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
203 * we need to undo that. */
204 _Py_DEC_REFTOTAL;
205 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
206 * chain, so no more to do there.
207 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
208 * _Py_NewReference bumped tp_allocs: both of those need to be
209 * undone.
210 */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000211#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 --self->ob_type->tp_frees;
213 --self->ob_type->tp_allocs;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000214#endif
215}
216
217
218
219PyDoc_STRVAR(throw_doc,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220"throw(typ[,val[,tb]]) -> raise exception in generator,\n\
221return next yielded value or raise StopIteration.");
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000222
223static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000224gen_throw(PyGenObject *gen, PyObject *args)
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyObject *typ;
227 PyObject *tb = NULL;
228 PyObject *val = NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
231 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 /* First, check the traceback argument, replacing None with
234 NULL. */
235 if (tb == Py_None)
236 tb = NULL;
237 else if (tb != NULL && !PyTraceBack_Check(tb)) {
238 PyErr_SetString(PyExc_TypeError,
239 "throw() third argument must be a traceback object");
240 return NULL;
241 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 Py_INCREF(typ);
244 Py_XINCREF(val);
245 Py_XINCREF(tb);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (PyExceptionClass_Check(typ)) {
248 PyErr_NormalizeException(&typ, &val, &tb);
249 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 else if (PyExceptionInstance_Check(typ)) {
252 /* Raising an instance. The value should be a dummy. */
253 if (val && val != Py_None) {
254 PyErr_SetString(PyExc_TypeError,
255 "instance exception may not have a separate value");
256 goto failed_throw;
257 }
258 else {
259 /* Normalize to raise <class>, <instance> */
260 Py_XDECREF(val);
261 val = typ;
262 typ = PyExceptionInstance_Class(typ);
263 Py_INCREF(typ);
Antoine Pitrou551ba202011-10-18 16:40:50 +0200264
265 if (tb == NULL) {
266 /* Returns NULL if there's no traceback */
267 tb = PyException_GetTraceback(val);
268 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 }
270 }
271 else {
272 /* Not something you can raise. throw() fails. */
273 PyErr_Format(PyExc_TypeError,
274 "exceptions must be classes or instances "
275 "deriving from BaseException, not %s",
276 typ->ob_type->tp_name);
277 goto failed_throw;
278 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyErr_Restore(typ, val, tb);
281 return gen_send_ex(gen, Py_None, 1);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000282
283failed_throw:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* Didn't use our arguments, so restore their original refcounts */
285 Py_DECREF(typ);
286 Py_XDECREF(val);
287 Py_XDECREF(tb);
288 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000289}
290
291
292static PyObject *
293gen_iternext(PyGenObject *gen)
294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 return gen_send_ex(gen, NULL, 0);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000296}
297
298
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000299static PyObject *
300gen_repr(PyGenObject *gen)
301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return PyUnicode_FromFormat("<generator object %S at %p>",
303 ((PyCodeObject *)gen->gi_code)->co_name,
304 gen);
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000305}
306
307
308static PyObject *
309gen_get_name(PyGenObject *gen)
310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name;
312 Py_INCREF(name);
313 return name;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000314}
315
316
317PyDoc_STRVAR(gen__name__doc__,
318"Return the name of the generator's associated code object.");
319
320static PyGetSetDef gen_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 {"__name__", (getter)gen_get_name, NULL, gen__name__doc__},
322 {NULL}
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000323};
324
325
Martin v. Löwise440e472004-06-01 15:22:42 +0000326static PyMemberDef gen_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY},
328 {"gi_running", T_INT, offsetof(PyGenObject, gi_running), READONLY},
329 {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY},
330 {NULL} /* Sentinel */
Martin v. Löwise440e472004-06-01 15:22:42 +0000331};
332
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000333static PyMethodDef gen_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 {"send",(PyCFunction)gen_send, METH_O, send_doc},
335 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
336 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
337 {NULL, NULL} /* Sentinel */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000338};
339
Martin v. Löwise440e472004-06-01 15:22:42 +0000340PyTypeObject PyGen_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 PyVarObject_HEAD_INIT(&PyType_Type, 0)
342 "generator", /* tp_name */
343 sizeof(PyGenObject), /* tp_basicsize */
344 0, /* tp_itemsize */
345 /* methods */
346 (destructor)gen_dealloc, /* tp_dealloc */
347 0, /* tp_print */
348 0, /* tp_getattr */
349 0, /* tp_setattr */
350 0, /* tp_reserved */
351 (reprfunc)gen_repr, /* tp_repr */
352 0, /* tp_as_number */
353 0, /* tp_as_sequence */
354 0, /* tp_as_mapping */
355 0, /* tp_hash */
356 0, /* tp_call */
357 0, /* tp_str */
358 PyObject_GenericGetAttr, /* tp_getattro */
359 0, /* tp_setattro */
360 0, /* tp_as_buffer */
361 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
362 0, /* tp_doc */
363 (traverseproc)gen_traverse, /* tp_traverse */
364 0, /* tp_clear */
365 0, /* tp_richcompare */
366 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
367 PyObject_SelfIter, /* tp_iter */
368 (iternextfunc)gen_iternext, /* tp_iternext */
369 gen_methods, /* tp_methods */
370 gen_memberlist, /* tp_members */
371 gen_getsetlist, /* tp_getset */
372 0, /* tp_base */
373 0, /* tp_dict */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 0, /* tp_descr_get */
376 0, /* tp_descr_set */
377 0, /* tp_dictoffset */
378 0, /* tp_init */
379 0, /* tp_alloc */
380 0, /* tp_new */
381 0, /* tp_free */
382 0, /* tp_is_gc */
383 0, /* tp_bases */
384 0, /* tp_mro */
385 0, /* tp_cache */
386 0, /* tp_subclasses */
387 0, /* tp_weaklist */
388 gen_del, /* tp_del */
Martin v. Löwise440e472004-06-01 15:22:42 +0000389};
390
391PyObject *
392PyGen_New(PyFrameObject *f)
393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
395 if (gen == NULL) {
396 Py_DECREF(f);
397 return NULL;
398 }
399 gen->gi_frame = f;
400 Py_INCREF(f->f_code);
401 gen->gi_code = (PyObject *)(f->f_code);
402 gen->gi_running = 0;
403 gen->gi_weakreflist = NULL;
404 _PyObject_GC_TRACK(gen);
405 return (PyObject *)gen;
Martin v. Löwise440e472004-06-01 15:22:42 +0000406}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000407
408int
409PyGen_NeedsFinalizing(PyGenObject *gen)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 int i;
412 PyFrameObject *f = gen->gi_frame;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0)
415 return 0; /* no frame or empty blockstack == no finalization */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 /* Any block type besides a loop requires cleanup. */
418 i = f->f_iblock;
419 while (--i >= 0) {
420 if (f->f_blockstack[i].b_type != SETUP_LOOP)
421 return 1;
422 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 /* No blocks except loops, it's safe to skip finalization. */
425 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000426}