objgenerator.c 14 KB

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