objgenerator.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. #include <stdlib.h>
  28. #include <assert.h>
  29. #include "py/runtime.h"
  30. #include "py/bc.h"
  31. #include "py/objstr.h"
  32. #include "py/objgenerator.h"
  33. #include "py/objfun.h"
  34. #include "py/stackctrl.h"
  35. // Instance of GeneratorExit exception - needed by generator.close()
  36. const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t*)&mp_const_empty_tuple_obj};
  37. /******************************************************************************/
  38. /* generator wrapper */
  39. typedef struct _mp_obj_gen_instance_t {
  40. mp_obj_base_t base;
  41. // mp_const_none: Not-running, no exception.
  42. // MP_OBJ_NULL: Running, no exception.
  43. // other: Not running, pending exception.
  44. mp_obj_t pend_exc;
  45. mp_code_state_t code_state;
  46. } mp_obj_gen_instance_t;
  47. 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) {
  48. // A generating function is just a bytecode function with type mp_type_gen_wrap
  49. mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in);
  50. // bytecode prelude: get state size and exception stack size
  51. const uint8_t *ip = self_fun->bytecode;
  52. MP_BC_PRELUDE_SIG_DECODE(ip);
  53. // allocate the generator object, with room for local stack and exception stack
  54. mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte,
  55. n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t));
  56. o->base.type = &mp_type_gen_instance;
  57. o->pend_exc = mp_const_none;
  58. o->code_state.fun_bc = self_fun;
  59. o->code_state.ip = 0;
  60. o->code_state.n_state = n_state;
  61. mp_setup_code_state(&o->code_state, n_args, n_kw, args);
  62. return MP_OBJ_FROM_PTR(o);
  63. }
  64. const mp_obj_type_t mp_type_gen_wrap = {
  65. { &mp_type_type },
  66. .name = MP_QSTR_generator,
  67. .call = gen_wrap_call,
  68. .unary_op = mp_generic_unary_op,
  69. #if MICROPY_PY_FUNCTION_ATTRS
  70. .attr = mp_obj_fun_bc_attr,
  71. #endif
  72. };
  73. /******************************************************************************/
  74. // native generator wrapper
  75. #if MICROPY_EMIT_NATIVE
  76. 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) {
  77. // The state for a native generating function is held in the same struct as a bytecode function
  78. mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in);
  79. // Determine start of prelude, and extract n_state from it
  80. uintptr_t prelude_offset = ((uintptr_t*)self_fun->bytecode)[0];
  81. #if MICROPY_EMIT_NATIVE_PRELUDE_AS_BYTES_OBJ
  82. // Prelude is in bytes object in const_table, at index prelude_offset
  83. mp_obj_str_t *prelude_bytes = MP_OBJ_TO_PTR(self_fun->const_table[prelude_offset]);
  84. prelude_offset = (const byte*)prelude_bytes->data - self_fun->bytecode;
  85. #endif
  86. const uint8_t *ip = self_fun->bytecode + prelude_offset;
  87. size_t n_state, n_exc_stack_unused, scope_flags, n_pos_args, n_kwonly_args, n_def_args;
  88. MP_BC_PRELUDE_SIG_DECODE_INTO(ip, n_state, n_exc_stack_unused, scope_flags, n_pos_args, n_kwonly_args, n_def_args);
  89. size_t n_exc_stack = 0;
  90. // Allocate the generator object, with room for local stack and exception stack
  91. mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte,
  92. n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t));
  93. o->base.type = &mp_type_gen_instance;
  94. // Parse the input arguments and set up the code state
  95. o->pend_exc = mp_const_none;
  96. o->code_state.fun_bc = self_fun;
  97. o->code_state.ip = (const byte*)prelude_offset;
  98. o->code_state.n_state = n_state;
  99. mp_setup_code_state(&o->code_state, n_args, n_kw, args);
  100. // Indicate we are a native function, which doesn't use this variable
  101. o->code_state.exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_SENTINEL;
  102. // Prepare the generator instance for execution
  103. uintptr_t start_offset = ((uintptr_t*)self_fun->bytecode)[1];
  104. o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void*)(self_fun->bytecode + start_offset));
  105. return MP_OBJ_FROM_PTR(o);
  106. }
  107. const mp_obj_type_t mp_type_native_gen_wrap = {
  108. { &mp_type_type },
  109. .name = MP_QSTR_generator,
  110. .call = native_gen_wrap_call,
  111. .unary_op = mp_generic_unary_op,
  112. #if MICROPY_PY_FUNCTION_ATTRS
  113. .attr = mp_obj_fun_bc_attr,
  114. #endif
  115. };
  116. #endif // MICROPY_EMIT_NATIVE
  117. /******************************************************************************/
  118. /* generator instance */
  119. STATIC void gen_instance_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  120. (void)kind;
  121. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  122. mp_printf(print, "<generator object '%q' at %p>", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self);
  123. }
  124. 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) {
  125. MP_STACK_CHECK();
  126. mp_check_self(mp_obj_is_type(self_in, &mp_type_gen_instance));
  127. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  128. if (self->code_state.ip == 0) {
  129. // Trying to resume already stopped generator
  130. *ret_val = MP_OBJ_STOP_ITERATION;
  131. return MP_VM_RETURN_NORMAL;
  132. }
  133. // Ensure the generator cannot be reentered during execution
  134. if (self->pend_exc == MP_OBJ_NULL) {
  135. mp_raise_ValueError("generator already executing");
  136. }
  137. #if MICROPY_PY_GENERATOR_PEND_THROW
  138. // If exception is pending (set using .pend_throw()), process it now.
  139. if (self->pend_exc != mp_const_none) {
  140. throw_value = self->pend_exc;
  141. }
  142. #endif
  143. // If the generator is started, allow sending a value.
  144. if (self->code_state.sp == self->code_state.state - 1) {
  145. if (send_value != mp_const_none) {
  146. mp_raise_TypeError("can't send non-None value to a just-started generator");
  147. }
  148. } else {
  149. *self->code_state.sp = send_value;
  150. }
  151. // Mark as running
  152. self->pend_exc = MP_OBJ_NULL;
  153. // Set up the correct globals context for the generator and execute it
  154. self->code_state.old_globals = mp_globals_get();
  155. mp_globals_set(self->code_state.fun_bc->globals);
  156. mp_vm_return_kind_t ret_kind;
  157. #if MICROPY_EMIT_NATIVE
  158. if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) {
  159. // A native generator, with entry point 2 words into the "bytecode" pointer
  160. typedef uintptr_t (*mp_fun_native_gen_t)(void*, mp_obj_t);
  161. mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void*)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t)));
  162. ret_kind = fun((void*)&self->code_state, throw_value);
  163. } else
  164. #endif
  165. {
  166. // A bytecode generator
  167. ret_kind = mp_execute_bytecode(&self->code_state, throw_value);
  168. }
  169. mp_globals_set(self->code_state.old_globals);
  170. // Mark as not running
  171. self->pend_exc = mp_const_none;
  172. switch (ret_kind) {
  173. case MP_VM_RETURN_NORMAL:
  174. default:
  175. // Explicitly mark generator as completed. If we don't do this,
  176. // subsequent next() may re-execute statements after last yield
  177. // again and again, leading to side effects.
  178. self->code_state.ip = 0;
  179. *ret_val = *self->code_state.sp;
  180. break;
  181. case MP_VM_RETURN_YIELD:
  182. *ret_val = *self->code_state.sp;
  183. #if MICROPY_PY_GENERATOR_PEND_THROW
  184. *self->code_state.sp = mp_const_none;
  185. #endif
  186. break;
  187. case MP_VM_RETURN_EXCEPTION: {
  188. self->code_state.ip = 0;
  189. *ret_val = self->code_state.state[0];
  190. // PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError
  191. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(*ret_val)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
  192. *ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, "generator raised StopIteration");
  193. }
  194. break;
  195. }
  196. }
  197. return ret_kind;
  198. }
  199. STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value) {
  200. mp_obj_t ret;
  201. switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
  202. case MP_VM_RETURN_NORMAL:
  203. default:
  204. // Optimize return w/o value in case generator is used in for loop
  205. if (ret == mp_const_none || ret == MP_OBJ_STOP_ITERATION) {
  206. return MP_OBJ_STOP_ITERATION;
  207. } else {
  208. nlr_raise(mp_obj_new_exception_args(&mp_type_StopIteration, 1, &ret));
  209. }
  210. case MP_VM_RETURN_YIELD:
  211. return ret;
  212. case MP_VM_RETURN_EXCEPTION:
  213. nlr_raise(ret);
  214. }
  215. }
  216. STATIC mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
  217. return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL);
  218. }
  219. STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
  220. mp_obj_t ret = gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL);
  221. if (ret == MP_OBJ_STOP_ITERATION) {
  222. nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
  223. } else {
  224. return ret;
  225. }
  226. }
  227. STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
  228. STATIC mp_obj_t gen_instance_throw(size_t n_args, const mp_obj_t *args) {
  229. // The signature of this function is: throw(type[, value[, traceback]])
  230. // CPython will pass all given arguments through the call chain and process them
  231. // at the point they are used (native generators will handle them differently to
  232. // user-defined generators with a throw() method). To save passing multiple
  233. // values, MicroPython instead does partial processing here to reduce it down to
  234. // one argument and passes that through:
  235. // - if only args[1] is given, or args[2] is given but is None, args[1] is
  236. // passed through (in the standard case it is an exception class or instance)
  237. // - if args[2] is given and not None it is passed through (in the standard
  238. // case it would be an exception instance and args[1] its corresponding class)
  239. // - args[3] is always ignored
  240. mp_obj_t exc = args[1];
  241. if (n_args > 2 && args[2] != mp_const_none) {
  242. exc = args[2];
  243. }
  244. mp_obj_t ret = gen_resume_and_raise(args[0], mp_const_none, exc);
  245. if (ret == MP_OBJ_STOP_ITERATION) {
  246. nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
  247. } else {
  248. return ret;
  249. }
  250. }
  251. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(gen_instance_throw_obj, 2, 4, gen_instance_throw);
  252. STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) {
  253. mp_obj_t ret;
  254. switch (mp_obj_gen_resume(self_in, mp_const_none, MP_OBJ_FROM_PTR(&mp_const_GeneratorExit_obj), &ret)) {
  255. case MP_VM_RETURN_YIELD:
  256. mp_raise_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit");
  257. // Swallow GeneratorExit (== successful close), and re-raise any other
  258. case MP_VM_RETURN_EXCEPTION:
  259. // ret should always be an instance of an exception class
  260. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
  261. return mp_const_none;
  262. }
  263. nlr_raise(ret);
  264. default:
  265. // The only choice left is MP_VM_RETURN_NORMAL which is successful close
  266. return mp_const_none;
  267. }
  268. }
  269. STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
  270. #if MICROPY_PY_GENERATOR_PEND_THROW
  271. STATIC mp_obj_t gen_instance_pend_throw(mp_obj_t self_in, mp_obj_t exc_in) {
  272. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  273. if (self->pend_exc == MP_OBJ_NULL) {
  274. mp_raise_ValueError("generator already executing");
  275. }
  276. mp_obj_t prev = self->pend_exc;
  277. self->pend_exc = exc_in;
  278. return prev;
  279. }
  280. STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_pend_throw_obj, gen_instance_pend_throw);
  281. #endif
  282. STATIC const mp_rom_map_elem_t gen_instance_locals_dict_table[] = {
  283. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&gen_instance_close_obj) },
  284. { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&gen_instance_send_obj) },
  285. { MP_ROM_QSTR(MP_QSTR_throw), MP_ROM_PTR(&gen_instance_throw_obj) },
  286. #if MICROPY_PY_GENERATOR_PEND_THROW
  287. { MP_ROM_QSTR(MP_QSTR_pend_throw), MP_ROM_PTR(&gen_instance_pend_throw_obj) },
  288. #endif
  289. };
  290. STATIC MP_DEFINE_CONST_DICT(gen_instance_locals_dict, gen_instance_locals_dict_table);
  291. const mp_obj_type_t mp_type_gen_instance = {
  292. { &mp_type_type },
  293. .name = MP_QSTR_generator,
  294. .print = gen_instance_print,
  295. .unary_op = mp_generic_unary_op,
  296. .getiter = mp_identity_getiter,
  297. .iternext = gen_instance_iternext,
  298. .locals_dict = (mp_obj_dict_t*)&gen_instance_locals_dict,
  299. };