1 /*
2 * This file is part of the MicroPython project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013-2019 Damien P. George
7 * Copyright (c) 2014-2017 Paul Sokolovsky
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 */
27
28 #include <stdlib.h>
29 #include <assert.h>
30
31 #include "py/runtime.h"
32 #include "py/bc.h"
33 #include "py/objstr.h"
34 #include "py/objgenerator.h"
35 #include "py/objfun.h"
36 #include "py/stackctrl.h"
37
38 // Instance of GeneratorExit exception - needed by generator.close()
39 const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t *)&mp_const_empty_tuple_obj};
40
41 /******************************************************************************/
42 /* generator wrapper */
43
44 typedef struct _mp_obj_gen_instance_t {
45 mp_obj_base_t base;
46 // mp_const_none: Not-running, no exception.
47 // MP_OBJ_NULL: Running, no exception.
48 // other: Not running, pending exception.
49 mp_obj_t pend_exc;
50 mp_code_state_t code_state;
51 } mp_obj_gen_instance_t;
52
gen_wrap_call(mp_obj_t self_in,size_t n_args,size_t n_kw,const mp_obj_t * args)53 STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
54 // A generating function is just a bytecode function with type mp_type_gen_wrap
55 mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in);
56
57 // bytecode prelude: get state size and exception stack size
58 const uint8_t *ip = self_fun->bytecode;
59 MP_BC_PRELUDE_SIG_DECODE(ip);
60
61 // allocate the generator object, with room for local stack and exception stack
62 mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte,
63 n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t));
64 o->base.type = &mp_type_gen_instance;
65
66 o->pend_exc = mp_const_none;
67 o->code_state.fun_bc = self_fun;
68 o->code_state.ip = 0;
69 o->code_state.n_state = n_state;
70 mp_setup_code_state(&o->code_state, n_args, n_kw, args);
71 return MP_OBJ_FROM_PTR(o);
72 }
73
74 const mp_obj_type_t mp_type_gen_wrap = {
75 { &mp_type_type },
76 .flags = MP_TYPE_FLAG_BINDS_SELF,
77 .name = MP_QSTR_generator,
78 .call = gen_wrap_call,
79 .unary_op = mp_generic_unary_op,
80 #if MICROPY_PY_FUNCTION_ATTRS
81 .attr = mp_obj_fun_bc_attr,
82 #endif
83 };
84
85 /******************************************************************************/
86 // native generator wrapper
87
88 #if MICROPY_EMIT_NATIVE
89
native_gen_wrap_call(mp_obj_t self_in,size_t n_args,size_t n_kw,const mp_obj_t * args)90 STATIC mp_obj_t native_gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
91 // The state for a native generating function is held in the same struct as a bytecode function
92 mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in);
93
94 // Determine start of prelude, and extract n_state from it
95 uintptr_t prelude_offset = ((uintptr_t *)self_fun->bytecode)[0];
96 #if MICROPY_EMIT_NATIVE_PRELUDE_AS_BYTES_OBJ
97 // Prelude is in bytes object in const_table, at index prelude_offset
98 mp_obj_str_t *prelude_bytes = MP_OBJ_TO_PTR(self_fun->const_table[prelude_offset]);
99 prelude_offset = (const byte *)prelude_bytes->data - self_fun->bytecode;
100 #endif
101 const uint8_t *ip = self_fun->bytecode + prelude_offset;
102 size_t n_state, n_exc_stack_unused, scope_flags, n_pos_args, n_kwonly_args, n_def_args;
103 MP_BC_PRELUDE_SIG_DECODE_INTO(ip, n_state, n_exc_stack_unused, scope_flags, n_pos_args, n_kwonly_args, n_def_args);
104 size_t n_exc_stack = 0;
105
106 // Allocate the generator object, with room for local stack and exception stack
107 mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte,
108 n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t));
109 o->base.type = &mp_type_gen_instance;
110
111 // Parse the input arguments and set up the code state
112 o->pend_exc = mp_const_none;
113 o->code_state.fun_bc = self_fun;
114 o->code_state.ip = (const byte *)prelude_offset;
115 o->code_state.n_state = n_state;
116 mp_setup_code_state(&o->code_state, n_args, n_kw, args);
117
118 // Indicate we are a native function, which doesn't use this variable
119 o->code_state.exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_SENTINEL;
120
121 // Prepare the generator instance for execution
122 uintptr_t start_offset = ((uintptr_t *)self_fun->bytecode)[1];
123 o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void *)(self_fun->bytecode + start_offset));
124
125 return MP_OBJ_FROM_PTR(o);
126 }
127
128 const mp_obj_type_t mp_type_native_gen_wrap = {
129 { &mp_type_type },
130 .flags = MP_TYPE_FLAG_BINDS_SELF,
131 .name = MP_QSTR_generator,
132 .call = native_gen_wrap_call,
133 .unary_op = mp_generic_unary_op,
134 #if MICROPY_PY_FUNCTION_ATTRS
135 .attr = mp_obj_fun_bc_attr,
136 #endif
137 };
138
139 #endif // MICROPY_EMIT_NATIVE
140
141 /******************************************************************************/
142 /* generator instance */
143
gen_instance_print(const mp_print_t * print,mp_obj_t self_in,mp_print_kind_t kind)144 STATIC void gen_instance_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
145 (void)kind;
146 mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
147 mp_printf(print, "<generator object '%q' at %p>", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self);
148 }
149
mp_obj_gen_resume(mp_obj_t self_in,mp_obj_t send_value,mp_obj_t throw_value,mp_obj_t * ret_val)150 mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value, mp_obj_t *ret_val) {
151 MP_STACK_CHECK();
152 mp_check_self(mp_obj_is_type(self_in, &mp_type_gen_instance));
153 mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
154 if (self->code_state.ip == 0) {
155 // Trying to resume an already stopped generator.
156 // This is an optimised "raise StopIteration(None)".
157 *ret_val = mp_const_none;
158 return MP_VM_RETURN_NORMAL;
159 }
160
161 // Ensure the generator cannot be reentered during execution
162 if (self->pend_exc == MP_OBJ_NULL) {
163 mp_raise_ValueError(MP_ERROR_TEXT("generator already executing"));
164 }
165
166 #if MICROPY_PY_GENERATOR_PEND_THROW
167 // If exception is pending (set using .pend_throw()), process it now.
168 if (self->pend_exc != mp_const_none) {
169 throw_value = self->pend_exc;
170 }
171 #endif
172
173 // If the generator is started, allow sending a value.
174 if (self->code_state.sp == self->code_state.state - 1) {
175 if (send_value != mp_const_none) {
176 mp_raise_TypeError(MP_ERROR_TEXT("can't send non-None value to a just-started generator"));
177 }
178 } else {
179 *self->code_state.sp = send_value;
180 }
181
182 // Mark as running
183 self->pend_exc = MP_OBJ_NULL;
184
185 // Set up the correct globals context for the generator and execute it
186 self->code_state.old_globals = mp_globals_get();
187 mp_globals_set(self->code_state.fun_bc->globals);
188
189 mp_vm_return_kind_t ret_kind;
190
191 #if MICROPY_EMIT_NATIVE
192 if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) {
193 // A native generator, with entry point 2 words into the "bytecode" pointer
194 typedef uintptr_t (*mp_fun_native_gen_t)(void *, mp_obj_t);
195 mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void *)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t)));
196 ret_kind = fun((void *)&self->code_state, throw_value);
197 } else
198 #endif
199 {
200 // A bytecode generator
201 ret_kind = mp_execute_bytecode(&self->code_state, throw_value);
202 }
203
204 mp_globals_set(self->code_state.old_globals);
205
206 // Mark as not running
207 self->pend_exc = mp_const_none;
208
209 switch (ret_kind) {
210 case MP_VM_RETURN_NORMAL:
211 default:
212 // Explicitly mark generator as completed. If we don't do this,
213 // subsequent next() may re-execute statements after last yield
214 // again and again, leading to side effects.
215 self->code_state.ip = 0;
216 // This is an optimised "raise StopIteration(*ret_val)".
217 *ret_val = *self->code_state.sp;
218 break;
219
220 case MP_VM_RETURN_YIELD:
221 *ret_val = *self->code_state.sp;
222 #if MICROPY_PY_GENERATOR_PEND_THROW
223 *self->code_state.sp = mp_const_none;
224 #endif
225 break;
226
227 case MP_VM_RETURN_EXCEPTION: {
228 self->code_state.ip = 0;
229 *ret_val = self->code_state.state[0];
230 // PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError
231 if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(*ret_val)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
232 *ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("generator raised StopIteration"));
233 }
234 break;
235 }
236 }
237
238 return ret_kind;
239 }
240
gen_resume_and_raise(mp_obj_t self_in,mp_obj_t send_value,mp_obj_t throw_value,bool raise_stop_iteration)241 STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value, bool raise_stop_iteration) {
242 mp_obj_t ret;
243 switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
244 case MP_VM_RETURN_NORMAL:
245 default:
246 // A normal return is a StopIteration, either raise it or return
247 // MP_OBJ_STOP_ITERATION as an optimisation.
248 if (ret == mp_const_none) {
249 ret = MP_OBJ_NULL;
250 }
251 if (raise_stop_iteration) {
252 mp_raise_StopIteration(ret);
253 } else {
254 return mp_make_stop_iteration(ret);
255 }
256
257 case MP_VM_RETURN_YIELD:
258 return ret;
259
260 case MP_VM_RETURN_EXCEPTION:
261 nlr_raise(ret);
262 }
263 }
264
gen_instance_iternext(mp_obj_t self_in)265 STATIC mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
266 return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL, false);
267 }
268
gen_instance_send(mp_obj_t self_in,mp_obj_t send_value)269 STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
270 return gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL, true);
271 }
272 STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
273
gen_instance_throw(size_t n_args,const mp_obj_t * args)274 STATIC mp_obj_t gen_instance_throw(size_t n_args, const mp_obj_t *args) {
275 // The signature of this function is: throw(type[, value[, traceback]])
276 // CPython will pass all given arguments through the call chain and process them
277 // at the point they are used (native generators will handle them differently to
278 // user-defined generators with a throw() method). To save passing multiple
279 // values, MicroPython instead does partial processing here to reduce it down to
280 // one argument and passes that through:
281 // - if only args[1] is given, or args[2] is given but is None, args[1] is
282 // passed through (in the standard case it is an exception class or instance)
283 // - if args[2] is given and not None it is passed through (in the standard
284 // case it would be an exception instance and args[1] its corresponding class)
285 // - args[3] is always ignored
286
287 mp_obj_t exc = args[1];
288 if (n_args > 2 && args[2] != mp_const_none) {
289 exc = args[2];
290 }
291
292 return gen_resume_and_raise(args[0], mp_const_none, exc, true);
293 }
294 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(gen_instance_throw_obj, 2, 4, gen_instance_throw);
295
gen_instance_close(mp_obj_t self_in)296 STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) {
297 mp_obj_t ret;
298 switch (mp_obj_gen_resume(self_in, mp_const_none, MP_OBJ_FROM_PTR(&mp_const_GeneratorExit_obj), &ret)) {
299 case MP_VM_RETURN_YIELD:
300 mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("generator ignored GeneratorExit"));
301
302 // Swallow GeneratorExit (== successful close), and re-raise any other
303 case MP_VM_RETURN_EXCEPTION:
304 // ret should always be an instance of an exception class
305 if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
306 return mp_const_none;
307 }
308 nlr_raise(ret);
309
310 default:
311 // The only choice left is MP_VM_RETURN_NORMAL which is successful close
312 return mp_const_none;
313 }
314 }
315 STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
316
317 #if MICROPY_PY_GENERATOR_PEND_THROW
gen_instance_pend_throw(mp_obj_t self_in,mp_obj_t exc_in)318 STATIC mp_obj_t gen_instance_pend_throw(mp_obj_t self_in, mp_obj_t exc_in) {
319 mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
320 if (self->pend_exc == MP_OBJ_NULL) {
321 mp_raise_ValueError(MP_ERROR_TEXT("generator already executing"));
322 }
323 mp_obj_t prev = self->pend_exc;
324 self->pend_exc = exc_in;
325 return prev;
326 }
327 STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_pend_throw_obj, gen_instance_pend_throw);
328 #endif
329
330 STATIC const mp_rom_map_elem_t gen_instance_locals_dict_table[] = {
331 { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&gen_instance_close_obj) },
332 { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&gen_instance_send_obj) },
333 { MP_ROM_QSTR(MP_QSTR_throw), MP_ROM_PTR(&gen_instance_throw_obj) },
334 #if MICROPY_PY_GENERATOR_PEND_THROW
335 { MP_ROM_QSTR(MP_QSTR_pend_throw), MP_ROM_PTR(&gen_instance_pend_throw_obj) },
336 #endif
337 };
338
339 STATIC MP_DEFINE_CONST_DICT(gen_instance_locals_dict, gen_instance_locals_dict_table);
340
341 const mp_obj_type_t mp_type_gen_instance = {
342 { &mp_type_type },
343 .name = MP_QSTR_generator,
344 .print = gen_instance_print,
345 .unary_op = mp_generic_unary_op,
346 .getiter = mp_identity_getiter,
347 .iternext = gen_instance_iternext,
348 .locals_dict = (mp_obj_dict_t *)&gen_instance_locals_dict,
349 };
350