Branch data Line data Source code
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 : :
53 : 1308 : 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 : 1308 : 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 : 1308 : const uint8_t *ip = self_fun->bytecode;
59 [ + + ]: 2656 : MP_BC_PRELUDE_SIG_DECODE(ip);
60 : :
61 : : // allocate the generator object, with room for local stack and exception stack
62 : 1308 : mp_obj_gen_instance_t *o = mp_obj_malloc_var(mp_obj_gen_instance_t, byte,
63 : : n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t),
64 : : &mp_type_gen_instance);
65 : :
66 : 1308 : o->pend_exc = mp_const_none;
67 : 1308 : o->code_state.fun_bc = self_fun;
68 : 1308 : o->code_state.n_state = n_state;
69 : 1308 : mp_setup_code_state(&o->code_state, n_args, n_kw, args);
70 : 1308 : return MP_OBJ_FROM_PTR(o);
71 : : }
72 : :
73 : : #if MICROPY_PY_FUNCTION_ATTRS
74 : : #define GEN_WRAP_TYPE_ATTR attr, mp_obj_fun_bc_attr,
75 : : #else
76 : : #define GEN_WRAP_TYPE_ATTR
77 : : #endif
78 : :
79 : : MP_DEFINE_CONST_OBJ_TYPE(
80 : : mp_type_gen_wrap,
81 : : MP_QSTR_generator,
82 : : MP_TYPE_FLAG_BINDS_SELF,
83 : : GEN_WRAP_TYPE_ATTR
84 : : call, gen_wrap_call
85 : : );
86 : :
87 : : /******************************************************************************/
88 : : // native generator wrapper
89 : :
90 : : #if MICROPY_EMIT_NATIVE
91 : :
92 : : // Based on mp_obj_gen_instance_t.
93 : : typedef struct _mp_obj_gen_instance_native_t {
94 : : mp_obj_base_t base;
95 : : mp_obj_t pend_exc;
96 : : mp_code_state_native_t code_state;
97 : : } mp_obj_gen_instance_native_t;
98 : :
99 : 1093 : 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) {
100 : : // The state for a native generating function is held in the same struct as a bytecode function
101 : 1093 : mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in);
102 : :
103 : : // Determine start of prelude.
104 : 1093 : uintptr_t prelude_ptr_index = ((uintptr_t *)self_fun->bytecode)[0];
105 : 1093 : const uint8_t *prelude_ptr;
106 [ + + ]: 1093 : if (prelude_ptr_index == 0) {
107 : 1073 : prelude_ptr = (void *)self_fun->child_table;
108 : : } else {
109 : 20 : prelude_ptr = (void *)self_fun->child_table[prelude_ptr_index];
110 : : }
111 : :
112 : : // Extract n_state from the prelude.
113 : 1093 : const uint8_t *ip = prelude_ptr;
114 [ + + ]: 2226 : MP_BC_PRELUDE_SIG_DECODE(ip);
115 : :
116 : : // Allocate the generator object, with room for local stack (exception stack not needed).
117 : 1093 : mp_obj_gen_instance_native_t *o = mp_obj_malloc_var(mp_obj_gen_instance_native_t, byte, n_state * sizeof(mp_obj_t), &mp_type_gen_instance);
118 : :
119 : : // Parse the input arguments and set up the code state
120 : 1093 : o->pend_exc = mp_const_none;
121 : 1093 : o->code_state.fun_bc = self_fun;
122 : 1093 : o->code_state.ip = prelude_ptr;
123 : 1093 : o->code_state.n_state = n_state;
124 : 1093 : o->code_state.sp = &o->code_state.state[0] - 1;
125 : 1093 : mp_setup_code_state_native(&o->code_state, n_args, n_kw, args);
126 : :
127 : : // Indicate we are a native function, which doesn't use this variable
128 : 1093 : o->code_state.exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_SENTINEL;
129 : :
130 : : // Prepare the generator instance for execution
131 : 1093 : uintptr_t start_offset = ((uintptr_t *)self_fun->bytecode)[1];
132 : 1093 : o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void *)(self_fun->bytecode + start_offset));
133 : :
134 : 1093 : return MP_OBJ_FROM_PTR(o);
135 : : }
136 : :
137 : : #if MICROPY_PY_FUNCTION_ATTRS
138 : : #define NATIVE_GEN_WRAP_TYPE_ATTR , attr, mp_obj_fun_bc_attr
139 : : #else
140 : : #define NATIVE_GEN_WRAP_TYPE_ATTR
141 : : #endif
142 : :
143 : : MP_DEFINE_CONST_OBJ_TYPE(
144 : : mp_type_native_gen_wrap,
145 : : MP_QSTR_generator,
146 : : MP_TYPE_FLAG_BINDS_SELF,
147 : : call, native_gen_wrap_call
148 : : NATIVE_GEN_WRAP_TYPE_ATTR
149 : : );
150 : :
151 : : #endif // MICROPY_EMIT_NATIVE
152 : :
153 : : /******************************************************************************/
154 : : /* generator instance */
155 : :
156 : 4 : STATIC void gen_instance_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
157 : 4 : (void)kind;
158 : 4 : mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
159 : 4 : mp_printf(print, "<generator object '%q' at %p>", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self);
160 : 4 : }
161 : :
162 : 183332 : 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) {
163 : 183332 : MP_STACK_CHECK();
164 : 183321 : mp_check_self(mp_obj_is_type(self_in, &mp_type_gen_instance));
165 : 183321 : mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
166 [ + + ]: 183321 : if (self->code_state.ip == 0) {
167 : : // Trying to resume an already stopped generator.
168 : : // This is an optimised "raise StopIteration(None)".
169 : 65 : *ret_val = mp_const_none;
170 : 65 : return MP_VM_RETURN_NORMAL;
171 : : }
172 : :
173 : : // Ensure the generator cannot be reentered during execution
174 [ + + ]: 183256 : if (self->pend_exc == MP_OBJ_NULL) {
175 : 8 : mp_raise_ValueError(MP_ERROR_TEXT("generator already executing"));
176 : : }
177 : :
178 : : #if MICROPY_PY_GENERATOR_PEND_THROW
179 : : // If exception is pending (set using .pend_throw()), process it now.
180 [ + + ]: 183248 : if (self->pend_exc != mp_const_none) {
181 : 16 : throw_value = self->pend_exc;
182 : : }
183 : : #endif
184 : :
185 : : // If the generator is started, allow sending a value.
186 : 183248 : void *state_start = self->code_state.state - 1;
187 : : #if MICROPY_EMIT_NATIVE
188 : 183248 : if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) {
189 : 183248 : state_start = ((mp_obj_gen_instance_native_t *)self)->code_state.state - 1;
190 : : }
191 : : #endif
192 [ + + ]: 183248 : if (self->code_state.sp == state_start) {
193 [ + + ]: 2375 : if (send_value != mp_const_none) {
194 : 4 : mp_raise_TypeError(MP_ERROR_TEXT("can't send non-None value to a just-started generator"));
195 : : }
196 : : } else {
197 : 180873 : *self->code_state.sp = send_value;
198 : : }
199 : :
200 : : // Mark as running
201 : 183244 : self->pend_exc = MP_OBJ_NULL;
202 : :
203 : : // Set up the correct globals context for the generator and execute it
204 : 183244 : self->code_state.old_globals = mp_globals_get();
205 : 183241 : mp_globals_set(self->code_state.fun_bc->context->module.globals);
206 : :
207 : 183240 : mp_vm_return_kind_t ret_kind;
208 : :
209 : : #if MICROPY_EMIT_NATIVE
210 [ + + ]: 183240 : if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) {
211 : : // A native generator, with entry point 2 words into the "bytecode" pointer
212 : 102482 : typedef uintptr_t (*mp_fun_native_gen_t)(void *, mp_obj_t);
213 : 102482 : mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void *)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t)));
214 : 102482 : ret_kind = fun((void *)&self->code_state, throw_value);
215 : : } else
216 : : #endif
217 : : {
218 : : // A bytecode generator
219 : 80758 : ret_kind = mp_execute_bytecode(&self->code_state, throw_value);
220 : : }
221 : :
222 : 183246 : mp_globals_set(self->code_state.old_globals);
223 : :
224 : : // Mark as not running
225 : 183248 : self->pend_exc = mp_const_none;
226 : :
227 [ + + + ]: 183248 : switch (ret_kind) {
228 : 1139 : case MP_VM_RETURN_NORMAL:
229 : : default:
230 : : // Explicitly mark generator as completed. If we don't do this,
231 : : // subsequent next() may re-execute statements after last yield
232 : : // again and again, leading to side effects.
233 : 1139 : self->code_state.ip = 0;
234 : : // This is an optimised "raise StopIteration(*ret_val)".
235 : 1139 : *ret_val = *self->code_state.sp;
236 : 1139 : break;
237 : :
238 : 181014 : case MP_VM_RETURN_YIELD:
239 : 181014 : *ret_val = *self->code_state.sp;
240 : : #if MICROPY_PY_GENERATOR_PEND_THROW
241 : 181014 : *self->code_state.sp = mp_const_none;
242 : : #endif
243 : 181014 : break;
244 : :
245 : 1095 : case MP_VM_RETURN_EXCEPTION: {
246 : 1095 : self->code_state.ip = 0;
247 : : #if MICROPY_EMIT_NATIVE
248 [ + + ]: 1095 : if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) {
249 : 528 : *ret_val = ((mp_obj_gen_instance_native_t *)self)->code_state.state[0];
250 : : } else
251 : : #endif
252 : : {
253 : 567 : *ret_val = self->code_state.state[0];
254 : : }
255 : : // PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError
256 [ + + ]: 1095 : if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(*ret_val)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
257 : 8 : *ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("generator raised StopIteration"));
258 : : }
259 : : break;
260 : : }
261 : : }
262 : :
263 : : return ret_kind;
264 : : }
265 : :
266 : 182043 : 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) {
267 : 182043 : mp_obj_t ret;
268 [ + + + ]: 182043 : switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
269 : 792 : case MP_VM_RETURN_NORMAL:
270 : : default:
271 : : // A normal return is a StopIteration, either raise it or return
272 : : // MP_OBJ_STOP_ITERATION as an optimisation.
273 [ + + ]: 792 : if (ret == mp_const_none) {
274 : 723 : ret = MP_OBJ_NULL;
275 : : }
276 [ + + ]: 792 : if (raise_stop_iteration) {
277 : 306 : mp_raise_StopIteration(ret);
278 : : } else {
279 : 486 : return mp_make_stop_iteration(ret);
280 : : }
281 : :
282 : 180668 : case MP_VM_RETURN_YIELD:
283 : 180668 : return ret;
284 : :
285 : 573 : case MP_VM_RETURN_EXCEPTION:
286 : 573 : nlr_raise(ret);
287 : : }
288 : : }
289 : :
290 : 29614 : STATIC mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
291 : 29614 : return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL, false);
292 : : }
293 : :
294 : 152207 : STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
295 : 152207 : return gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL, true);
296 : : }
297 : : STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
298 : :
299 : 220 : STATIC mp_obj_t gen_instance_throw(size_t n_args, const mp_obj_t *args) {
300 : : // The signature of this function is: throw(type[, value[, traceback]])
301 : : // CPython will pass all given arguments through the call chain and process them
302 : : // at the point they are used (native generators will handle them differently to
303 : : // user-defined generators with a throw() method). To save passing multiple
304 : : // values, MicroPython instead does partial processing here to reduce it down to
305 : : // one argument and passes that through:
306 : : // - if only args[1] is given, or args[2] is given but is None, args[1] is
307 : : // passed through (in the standard case it is an exception class or instance)
308 : : // - if args[2] is given and not None it is passed through (in the standard
309 : : // case it would be an exception instance and args[1] its corresponding class)
310 : : // - args[3] is always ignored
311 : :
312 : 220 : mp_obj_t exc = args[1];
313 [ + + + + ]: 220 : if (n_args > 2 && args[2] != mp_const_none) {
314 : 8 : exc = args[2];
315 : : }
316 : :
317 : 220 : return gen_resume_and_raise(args[0], mp_const_none, exc, true);
318 : : }
319 : : STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(gen_instance_throw_obj, 2, 4, gen_instance_throw);
320 : :
321 : 40 : STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) {
322 : 40 : mp_obj_t ret;
323 [ + + + ]: 40 : switch (mp_obj_gen_resume(self_in, mp_const_none, MP_OBJ_FROM_PTR(&mp_const_GeneratorExit_obj), &ret)) {
324 : : case MP_VM_RETURN_YIELD:
325 : 2 : mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("generator ignored GeneratorExit"));
326 : :
327 : : // Swallow GeneratorExit (== successful close), and re-raise any other
328 : 34 : case MP_VM_RETURN_EXCEPTION:
329 : : // ret should always be an instance of an exception class
330 [ + + ]: 34 : if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
331 : : return mp_const_none;
332 : : }
333 : 4 : nlr_raise(ret);
334 : :
335 : : default:
336 : : // The only choice left is MP_VM_RETURN_NORMAL which is successful close
337 : : return mp_const_none;
338 : : }
339 : : }
340 : : STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
341 : :
342 : : #if MICROPY_PY_GENERATOR_PEND_THROW
343 : 36 : STATIC mp_obj_t gen_instance_pend_throw(mp_obj_t self_in, mp_obj_t exc_in) {
344 : 36 : mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
345 [ + + ]: 36 : if (self->pend_exc == MP_OBJ_NULL) {
346 : 4 : mp_raise_ValueError(MP_ERROR_TEXT("generator already executing"));
347 : : }
348 : 32 : mp_obj_t prev = self->pend_exc;
349 : 32 : self->pend_exc = exc_in;
350 : 32 : return prev;
351 : : }
352 : : STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_pend_throw_obj, gen_instance_pend_throw);
353 : : #endif
354 : :
355 : : STATIC const mp_rom_map_elem_t gen_instance_locals_dict_table[] = {
356 : : { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&gen_instance_close_obj) },
357 : : { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&gen_instance_send_obj) },
358 : : { MP_ROM_QSTR(MP_QSTR_throw), MP_ROM_PTR(&gen_instance_throw_obj) },
359 : : #if MICROPY_PY_GENERATOR_PEND_THROW
360 : : { MP_ROM_QSTR(MP_QSTR_pend_throw), MP_ROM_PTR(&gen_instance_pend_throw_obj) },
361 : : #endif
362 : : };
363 : :
364 : : STATIC MP_DEFINE_CONST_DICT(gen_instance_locals_dict, gen_instance_locals_dict_table);
365 : :
366 : : MP_DEFINE_CONST_OBJ_TYPE(
367 : : mp_type_gen_instance,
368 : : MP_QSTR_generator,
369 : : MP_TYPE_FLAG_ITER_IS_ITERNEXT,
370 : : print, gen_instance_print,
371 : : iter, gen_instance_iternext,
372 : : locals_dict, &gen_instance_locals_dict
373 : : );
|