objgenerator.c 14 KB

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