objgenerator.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 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/objgenerator.h"
  32. #include "py/objfun.h"
  33. #include "py/stackctrl.h"
  34. /******************************************************************************/
  35. /* generator wrapper */
  36. typedef struct _mp_obj_gen_instance_t {
  37. mp_obj_base_t base;
  38. mp_obj_dict_t *globals;
  39. mp_code_state_t code_state;
  40. } mp_obj_gen_instance_t;
  41. 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) {
  42. // A generating function is just a bytecode function with type mp_type_gen_wrap
  43. mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in);
  44. // bytecode prelude: get state size and exception stack size
  45. size_t n_state = mp_decode_uint_value(self_fun->bytecode);
  46. size_t n_exc_stack = mp_decode_uint_value(mp_decode_uint_skip(self_fun->bytecode));
  47. // allocate the generator object, with room for local stack and exception stack
  48. mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte,
  49. n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t));
  50. o->base.type = &mp_type_gen_instance;
  51. o->globals = self_fun->globals;
  52. o->code_state.fun_bc = self_fun;
  53. o->code_state.ip = 0;
  54. mp_setup_code_state(&o->code_state, n_args, n_kw, args);
  55. return MP_OBJ_FROM_PTR(o);
  56. }
  57. const mp_obj_type_t mp_type_gen_wrap = {
  58. { &mp_type_type },
  59. .name = MP_QSTR_generator,
  60. .call = gen_wrap_call,
  61. .unary_op = mp_generic_unary_op,
  62. #if MICROPY_PY_FUNCTION_ATTRS
  63. .attr = mp_obj_fun_bc_attr,
  64. #endif
  65. };
  66. /******************************************************************************/
  67. // native generator wrapper
  68. #if MICROPY_EMIT_NATIVE
  69. 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) {
  70. // The state for a native generating function is held in the same struct as a bytecode function
  71. mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in);
  72. // Determine start of prelude, and extract n_state from it
  73. uintptr_t prelude_offset = ((uintptr_t*)self_fun->bytecode)[0];
  74. size_t n_state = mp_decode_uint_value(self_fun->bytecode + prelude_offset);
  75. size_t n_exc_stack = 0;
  76. // Allocate the generator object, with room for local stack and exception stack
  77. mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte,
  78. n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t));
  79. o->base.type = &mp_type_gen_instance;
  80. // Parse the input arguments and set up the code state
  81. o->globals = self_fun->globals;
  82. o->code_state.fun_bc = self_fun;
  83. o->code_state.ip = (const byte*)prelude_offset;
  84. mp_setup_code_state(&o->code_state, n_args, n_kw, args);
  85. // Indicate we are a native function, which doesn't use this variable
  86. o->code_state.exc_sp = NULL;
  87. // Prepare the generator instance for execution
  88. uintptr_t start_offset = ((uintptr_t*)self_fun->bytecode)[1];
  89. o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void*)(self_fun->bytecode + start_offset));
  90. return MP_OBJ_FROM_PTR(o);
  91. }
  92. const mp_obj_type_t mp_type_native_gen_wrap = {
  93. { &mp_type_type },
  94. .name = MP_QSTR_generator,
  95. .call = native_gen_wrap_call,
  96. .unary_op = mp_generic_unary_op,
  97. #if MICROPY_PY_FUNCTION_ATTRS
  98. .attr = mp_obj_fun_bc_attr,
  99. #endif
  100. };
  101. #endif // MICROPY_EMIT_NATIVE
  102. /******************************************************************************/
  103. /* generator instance */
  104. STATIC void gen_instance_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  105. (void)kind;
  106. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  107. mp_printf(print, "<generator object '%q' at %p>", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self);
  108. }
  109. 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) {
  110. MP_STACK_CHECK();
  111. mp_check_self(mp_obj_is_type(self_in, &mp_type_gen_instance));
  112. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  113. if (self->code_state.ip == 0) {
  114. // Trying to resume already stopped generator
  115. *ret_val = MP_OBJ_STOP_ITERATION;
  116. return MP_VM_RETURN_NORMAL;
  117. }
  118. if (self->code_state.sp == self->code_state.state - 1) {
  119. if (send_value != mp_const_none) {
  120. mp_raise_TypeError("can't send non-None value to a just-started generator");
  121. }
  122. } else {
  123. #if MICROPY_PY_GENERATOR_PEND_THROW
  124. // If exception is pending (set using .pend_throw()), process it now.
  125. if (*self->code_state.sp != mp_const_none) {
  126. throw_value = *self->code_state.sp;
  127. *self->code_state.sp = MP_OBJ_NULL;
  128. } else
  129. #endif
  130. {
  131. *self->code_state.sp = send_value;
  132. }
  133. }
  134. // We set self->globals=NULL while executing, for a sentinel to ensure the generator
  135. // cannot be reentered during execution
  136. if (self->globals == NULL) {
  137. mp_raise_ValueError("generator already executing");
  138. }
  139. // Set up the correct globals context for the generator and execute it
  140. self->code_state.old_globals = mp_globals_get();
  141. mp_globals_set(self->globals);
  142. self->globals = NULL;
  143. mp_vm_return_kind_t ret_kind;
  144. #if MICROPY_EMIT_NATIVE
  145. if (self->code_state.exc_sp == NULL) {
  146. // A native generator, with entry point 2 words into the "bytecode" pointer
  147. typedef uintptr_t (*mp_fun_native_gen_t)(void*, mp_obj_t);
  148. mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void*)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t)));
  149. ret_kind = fun((void*)&self->code_state, throw_value);
  150. } else
  151. #endif
  152. {
  153. // A bytecode generator
  154. ret_kind = mp_execute_bytecode(&self->code_state, throw_value);
  155. }
  156. self->globals = mp_globals_get();
  157. mp_globals_set(self->code_state.old_globals);
  158. switch (ret_kind) {
  159. case MP_VM_RETURN_NORMAL:
  160. default:
  161. // Explicitly mark generator as completed. If we don't do this,
  162. // subsequent next() may re-execute statements after last yield
  163. // again and again, leading to side effects.
  164. self->code_state.ip = 0;
  165. *ret_val = *self->code_state.sp;
  166. break;
  167. case MP_VM_RETURN_YIELD:
  168. *ret_val = *self->code_state.sp;
  169. #if MICROPY_PY_GENERATOR_PEND_THROW
  170. *self->code_state.sp = mp_const_none;
  171. #endif
  172. break;
  173. case MP_VM_RETURN_EXCEPTION: {
  174. self->code_state.ip = 0;
  175. *ret_val = self->code_state.state[0];
  176. // PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError
  177. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(*ret_val)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
  178. *ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, "generator raised StopIteration");
  179. }
  180. break;
  181. }
  182. }
  183. return ret_kind;
  184. }
  185. STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value) {
  186. mp_obj_t ret;
  187. switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
  188. case MP_VM_RETURN_NORMAL:
  189. default:
  190. // Optimize return w/o value in case generator is used in for loop
  191. if (ret == mp_const_none || ret == MP_OBJ_STOP_ITERATION) {
  192. return MP_OBJ_STOP_ITERATION;
  193. } else {
  194. nlr_raise(mp_obj_new_exception_args(&mp_type_StopIteration, 1, &ret));
  195. }
  196. case MP_VM_RETURN_YIELD:
  197. return ret;
  198. case MP_VM_RETURN_EXCEPTION:
  199. nlr_raise(ret);
  200. }
  201. }
  202. STATIC mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
  203. return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL);
  204. }
  205. STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
  206. mp_obj_t ret = gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL);
  207. if (ret == MP_OBJ_STOP_ITERATION) {
  208. nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
  209. } else {
  210. return ret;
  211. }
  212. }
  213. STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
  214. STATIC mp_obj_t gen_instance_close(mp_obj_t self_in);
  215. STATIC mp_obj_t gen_instance_throw(size_t n_args, const mp_obj_t *args) {
  216. mp_obj_t exc = (n_args == 2) ? args[1] : args[2];
  217. mp_obj_t ret = gen_resume_and_raise(args[0], mp_const_none, exc);
  218. if (ret == MP_OBJ_STOP_ITERATION) {
  219. nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
  220. } else {
  221. return ret;
  222. }
  223. }
  224. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(gen_instance_throw_obj, 2, 4, gen_instance_throw);
  225. STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) {
  226. mp_obj_t ret;
  227. switch (mp_obj_gen_resume(self_in, mp_const_none, MP_OBJ_FROM_PTR(&mp_const_GeneratorExit_obj), &ret)) {
  228. case MP_VM_RETURN_YIELD:
  229. mp_raise_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit");
  230. // Swallow GeneratorExit (== successful close), and re-raise any other
  231. case MP_VM_RETURN_EXCEPTION:
  232. // ret should always be an instance of an exception class
  233. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
  234. return mp_const_none;
  235. }
  236. nlr_raise(ret);
  237. default:
  238. // The only choice left is MP_VM_RETURN_NORMAL which is successful close
  239. return mp_const_none;
  240. }
  241. }
  242. STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
  243. STATIC mp_obj_t gen_instance_pend_throw(mp_obj_t self_in, mp_obj_t exc_in) {
  244. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  245. if (self->code_state.sp == self->code_state.state - 1) {
  246. mp_raise_TypeError("can't pend throw to just-started generator");
  247. }
  248. mp_obj_t prev = *self->code_state.sp;
  249. *self->code_state.sp = exc_in;
  250. return prev;
  251. }
  252. STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_pend_throw_obj, gen_instance_pend_throw);
  253. STATIC const mp_rom_map_elem_t gen_instance_locals_dict_table[] = {
  254. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&gen_instance_close_obj) },
  255. { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&gen_instance_send_obj) },
  256. { MP_ROM_QSTR(MP_QSTR_throw), MP_ROM_PTR(&gen_instance_throw_obj) },
  257. #if MICROPY_PY_GENERATOR_PEND_THROW
  258. { MP_ROM_QSTR(MP_QSTR_pend_throw), MP_ROM_PTR(&gen_instance_pend_throw_obj) },
  259. #endif
  260. };
  261. STATIC MP_DEFINE_CONST_DICT(gen_instance_locals_dict, gen_instance_locals_dict_table);
  262. const mp_obj_type_t mp_type_gen_instance = {
  263. { &mp_type_type },
  264. .name = MP_QSTR_generator,
  265. .print = gen_instance_print,
  266. .unary_op = mp_generic_unary_op,
  267. .getiter = mp_identity_getiter,
  268. .iternext = gen_instance_iternext,
  269. .locals_dict = (mp_obj_dict_t*)&gen_instance_locals_dict,
  270. };