blob: 8b84e2e41aedf74a6f891a520261f28d1521cce3 [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"
5#include "genobject.h"
6#include "ceval.h"
7#include "structmember.h"
8
9static int
10gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
11{
12 return visit((PyObject *)gen->gi_frame, arg);
13}
14
15static void
16gen_dealloc(PyGenObject *gen)
17{
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000018 PyObject *self = (PyObject *) gen;
19
Martin v. Löwise440e472004-06-01 15:22:42 +000020 _PyObject_GC_UNTRACK(gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000021
Martin v. Löwise440e472004-06-01 15:22:42 +000022 if (gen->gi_weakreflist != NULL)
23 PyObject_ClearWeakRefs((PyObject *) gen);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000024
25
26 _PyObject_GC_TRACK(self);
27
28 if (gen->gi_frame->f_stacktop!=NULL) {
29 /* Generator is paused, so we need to close */
30 gen->ob_type->tp_del(self);
31 if (self->ob_refcnt > 0)
32 return; /* resurrected. :( */
33 }
34
35 _PyObject_GC_UNTRACK(self);
36 Py_XDECREF(gen->gi_frame);
Martin v. Löwise440e472004-06-01 15:22:42 +000037 PyObject_GC_Del(gen);
38}
39
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000040
Martin v. Löwise440e472004-06-01 15:22:42 +000041static PyObject *
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000042gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
Martin v. Löwise440e472004-06-01 15:22:42 +000043{
44 PyThreadState *tstate = PyThreadState_GET();
45 PyFrameObject *f = gen->gi_frame;
46 PyObject *result;
47
48 if (gen->gi_running) {
49 PyErr_SetString(PyExc_ValueError,
50 "generator already executing");
51 return NULL;
52 }
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000053 if ((PyObject *)f == Py_None || f->f_stacktop == NULL) {
54 /* Only set exception if called from send() */
55 if (arg && !exc) PyErr_SetNone(PyExc_StopIteration);
Martin v. Löwise440e472004-06-01 15:22:42 +000056 return NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000057 }
58
59 if (f->f_lasti == -1) {
60 if (arg && arg != Py_None) {
61 PyErr_SetString(PyExc_TypeError,
62 "can't send non-None value to a just-started generator");
63 return NULL;
64 }
65 } else {
66 /* Push arg onto the frame's value stack */
67 result = arg ? arg : Py_None;
68 Py_INCREF(result);
69 *(f->f_stacktop++) = result;
70 }
Martin v. Löwise440e472004-06-01 15:22:42 +000071
72 /* Generators always return to their most recent caller, not
73 * necessarily their creator. */
74 Py_XINCREF(tstate->frame);
75 assert(f->f_back == NULL);
76 f->f_back = tstate->frame;
77
78 gen->gi_running = 1;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000079 result = PyEval_EvalFrameEx(f, exc);
Martin v. Löwise440e472004-06-01 15:22:42 +000080 gen->gi_running = 0;
81
82 /* Don't keep the reference to f_back any longer than necessary. It
83 * may keep a chain of frames alive or it could create a reference
84 * cycle. */
Phillip J. Eby00148222005-08-13 03:29:00 +000085 assert(f->f_back == tstate->frame);
Raymond Hettinger75ccea32004-09-01 07:02:44 +000086 Py_CLEAR(f->f_back);
Martin v. Löwise440e472004-06-01 15:22:42 +000087
88 /* If the generator just returned (as opposed to yielding), signal
89 * that the generator is exhausted. */
90 if (result == Py_None && f->f_stacktop == NULL) {
91 Py_DECREF(result);
92 result = NULL;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000093 /* Set exception if not called by gen_iternext() */
94 if (arg) PyErr_SetNone(PyExc_StopIteration);
95 }
96
97 if (!result || f->f_stacktop == NULL) {
98 /* generator can't be rerun, so release the frame */
99 Py_DECREF(f);
100 gen->gi_frame = (PyFrameObject *)Py_None;
101 Py_INCREF(Py_None);
Martin v. Löwise440e472004-06-01 15:22:42 +0000102 }
103
104 return result;
105}
106
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000107PyDoc_STRVAR(send_doc,
108"send(arg) -> send 'arg' into generator, return next yielded value or raise StopIteration.");
109
110static PyObject *
111gen_send(PyGenObject *gen, PyObject *arg)
112{
113 return gen_send_ex(gen, arg, 0);
114}
115
116PyDoc_STRVAR(close_doc,
117"close(arg) -> raise GeneratorExit inside generator.");
118
119static PyObject *
120gen_close(PyGenObject *gen, PyObject *args)
121{
122 PyObject *retval;
123 PyErr_SetNone(PyExc_GeneratorExit);
124 retval = gen_send_ex(gen, Py_None, 1);
125 if (retval) {
126 Py_DECREF(retval);
127 PyErr_SetString(PyExc_RuntimeError,
128 "generator ignored GeneratorExit");
129 return NULL;
130 }
131 if ( PyErr_ExceptionMatches(PyExc_StopIteration)
132 || PyErr_ExceptionMatches(PyExc_GeneratorExit) )
133 {
134 PyErr_Clear(); /* ignore these errors */
135 Py_INCREF(Py_None);
136 return Py_None;
137 }
138 return NULL;
139}
140
141static void
142gen_del(PyObject *self)
143{
144 PyObject *res;
145 PyObject *error_type, *error_value, *error_traceback;
146 PyGenObject *gen = (PyGenObject *)self;
147
148 if ((PyObject *)gen->gi_frame == Py_None || gen->gi_frame->f_stacktop==NULL)
149 /* Generator isn't paused, so no need to close */
150 return;
151
152 /* Temporarily resurrect the object. */
153 assert(self->ob_refcnt == 0);
154 self->ob_refcnt = 1;
155
156 /* Save the current exception, if any. */
157 PyErr_Fetch(&error_type, &error_value, &error_traceback);
158
159 res = gen_close((PyGenObject *)self, NULL);
160
161 if (res == NULL)
162 PyErr_WriteUnraisable((PyObject *)self);
163 else
164 Py_DECREF(res);
165
166 /* Restore the saved exception. */
167 PyErr_Restore(error_type, error_value, error_traceback);
168
169 /* Undo the temporary resurrection; can't use DECREF here, it would
170 * cause a recursive call.
171 */
172 assert(self->ob_refcnt > 0);
173 if (--self->ob_refcnt == 0)
174 return; /* this is the normal path out */
175
176 /* close() resurrected it! Make it look like the original Py_DECREF
177 * never happened.
178 */
179 {
180 int refcnt = self->ob_refcnt;
181 _Py_NewReference(self);
182 self->ob_refcnt = refcnt;
183 }
184 assert(!PyType_IS_GC(self->ob_type) ||
185 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
186
187 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
188 * we need to undo that. */
189 _Py_DEC_REFTOTAL;
190 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
191 * chain, so no more to do there.
192 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
193 * _Py_NewReference bumped tp_allocs: both of those need to be
194 * undone.
195 */
196#ifdef COUNT_ALLOCS
197 --self->ob_type->tp_frees;
198 --self->ob_type->tp_allocs;
199#endif
200}
201
202
203
204PyDoc_STRVAR(throw_doc,
205"throw(typ[,val[,tb]]) -> raise exception in generator, return next yielded value or raise StopIteration.");
206
207static PyObject *
208gen_throw(PyGenObject *gen, PyObject *args)
209{
210 PyObject *typ;
211 PyObject *tb = NULL;
212 PyObject *val = NULL;
213
214 if (!PyArg_ParseTuple(args, "O|OO:throw", &typ, &val, &tb))
215 return NULL;
216
Armin Rigo967aa8b2006-02-14 15:50:44 +0000217 /* First, check the traceback argument, replacing None with
218 NULL. */
219 if (tb == Py_None) {
220 Py_DECREF(tb);
221 tb = NULL;
222 }
223 else if (tb != NULL && !PyTraceBack_Check(tb)) {
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000224 PyErr_SetString(PyExc_TypeError,
225 "throw() third argument must be a traceback object");
226 return NULL;
227 }
228
229 Py_INCREF(typ);
230 Py_XINCREF(val);
231 Py_XINCREF(tb);
232
233 if (PyClass_Check(typ)) {
234 PyErr_NormalizeException(&typ, &val, &tb);
235 }
236
237 else if (PyInstance_Check(typ)) {
238 /* Raising an instance. The value should be a dummy. */
239 if (val && val != Py_None) {
240 PyErr_SetString(PyExc_TypeError,
241 "instance exception may not have a separate value");
242 goto failed_throw;
243 }
244 else {
245 /* Normalize to raise <class>, <instance> */
Armin Rigo967aa8b2006-02-14 15:50:44 +0000246 Py_XDECREF(val);
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000247 val = typ;
248 typ = (PyObject*) ((PyInstanceObject*)typ)->in_class;
249 Py_INCREF(typ);
250 }
251 }
252 else {
Armin Rigo967aa8b2006-02-14 15:50:44 +0000253 /* Not something you can raise. throw() fails. */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000254 PyErr_Format(PyExc_TypeError,
255 "exceptions must be classes, or instances, not %s",
256 typ->ob_type->tp_name);
257 goto failed_throw;
258 }
259
260 PyErr_Restore(typ,val,tb);
261 return gen_send_ex(gen, Py_None, 1);
262
263failed_throw:
264 /* Didn't use our arguments, so restore their original refcounts */
265 Py_DECREF(typ);
266 Py_XDECREF(val);
267 Py_XDECREF(tb);
268 return NULL;
269}
270
271
272static PyObject *
273gen_iternext(PyGenObject *gen)
274{
275 return gen_send_ex(gen, NULL, 0);
276}
277
278
Martin v. Löwise440e472004-06-01 15:22:42 +0000279static PyMemberDef gen_memberlist[] = {
280 {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), RO},
281 {"gi_running", T_INT, offsetof(PyGenObject, gi_running), RO},
282 {NULL} /* Sentinel */
283};
284
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000285static PyMethodDef gen_methods[] = {
286 {"send",(PyCFunction)gen_send, METH_O, send_doc},
287 {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
288 {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
289 {NULL, NULL} /* Sentinel */
290};
291
Martin v. Löwise440e472004-06-01 15:22:42 +0000292PyTypeObject PyGen_Type = {
293 PyObject_HEAD_INIT(&PyType_Type)
294 0, /* ob_size */
295 "generator", /* tp_name */
296 sizeof(PyGenObject), /* tp_basicsize */
297 0, /* tp_itemsize */
298 /* methods */
299 (destructor)gen_dealloc, /* tp_dealloc */
300 0, /* tp_print */
301 0, /* tp_getattr */
302 0, /* tp_setattr */
303 0, /* tp_compare */
304 0, /* tp_repr */
305 0, /* tp_as_number */
306 0, /* tp_as_sequence */
307 0, /* tp_as_mapping */
308 0, /* tp_hash */
309 0, /* tp_call */
310 0, /* tp_str */
311 PyObject_GenericGetAttr, /* tp_getattro */
312 0, /* tp_setattro */
313 0, /* tp_as_buffer */
314 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
315 0, /* tp_doc */
316 (traverseproc)gen_traverse, /* tp_traverse */
317 0, /* tp_clear */
318 0, /* tp_richcompare */
319 offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
Raymond Hettinger6c7a00f2004-06-12 05:17:55 +0000320 PyObject_SelfIter, /* tp_iter */
Martin v. Löwise440e472004-06-01 15:22:42 +0000321 (iternextfunc)gen_iternext, /* tp_iternext */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000322 gen_methods, /* tp_methods */
Martin v. Löwise440e472004-06-01 15:22:42 +0000323 gen_memberlist, /* tp_members */
324 0, /* tp_getset */
325 0, /* tp_base */
326 0, /* tp_dict */
Phillip J. Eby0d6615f2005-08-02 00:46:46 +0000327
328 0, /* tp_descr_get */
329 0, /* tp_descr_set */
330 0, /* tp_dictoffset */
331 0, /* tp_init */
332 0, /* tp_alloc */
333 0, /* tp_new */
334 0, /* tp_free */
335 0, /* tp_is_gc */
336 0, /* tp_bases */
337 0, /* tp_mro */
338 0, /* tp_cache */
339 0, /* tp_subclasses */
340 0, /* tp_weaklist */
341 gen_del, /* tp_del */
Martin v. Löwise440e472004-06-01 15:22:42 +0000342};
343
344PyObject *
345PyGen_New(PyFrameObject *f)
346{
347 PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
348 if (gen == NULL) {
349 Py_DECREF(f);
350 return NULL;
351 }
352 gen->gi_frame = f;
353 gen->gi_running = 0;
354 gen->gi_weakreflist = NULL;
355 _PyObject_GC_TRACK(gen);
356 return (PyObject *)gen;
357}