objgenerator.c 14 KB

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