objgenerator.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. /* generator instance */
  68. STATIC void gen_instance_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  69. (void)kind;
  70. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  71. mp_printf(print, "<generator object '%q' at %p>", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self);
  72. }
  73. 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) {
  74. MP_STACK_CHECK();
  75. mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_gen_instance));
  76. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  77. if (self->code_state.ip == 0) {
  78. // Trying to resume already stopped generator
  79. *ret_val = MP_OBJ_STOP_ITERATION;
  80. return MP_VM_RETURN_NORMAL;
  81. }
  82. if (self->code_state.sp == self->code_state.state - 1) {
  83. if (send_value != mp_const_none) {
  84. mp_raise_TypeError("can't send non-None value to a just-started generator");
  85. }
  86. } else {
  87. #if MICROPY_PY_GENERATOR_PEND_THROW
  88. // If exception is pending (set using .pend_throw()), process it now.
  89. if (*self->code_state.sp != mp_const_none) {
  90. throw_value = *self->code_state.sp;
  91. *self->code_state.sp = MP_OBJ_NULL;
  92. } else
  93. #endif
  94. {
  95. *self->code_state.sp = send_value;
  96. }
  97. }
  98. // We set self->globals=NULL while executing, for a sentinel to ensure the generator
  99. // cannot be reentered during execution
  100. if (self->globals == NULL) {
  101. mp_raise_ValueError("generator already executing");
  102. }
  103. // Set up the correct globals context for the generator and execute it
  104. self->code_state.old_globals = mp_globals_get();
  105. mp_globals_set(self->globals);
  106. self->globals = NULL;
  107. mp_vm_return_kind_t ret_kind = mp_execute_bytecode(&self->code_state, throw_value);
  108. self->globals = mp_globals_get();
  109. mp_globals_set(self->code_state.old_globals);
  110. switch (ret_kind) {
  111. case MP_VM_RETURN_NORMAL:
  112. default:
  113. // Explicitly mark generator as completed. If we don't do this,
  114. // subsequent next() may re-execute statements after last yield
  115. // again and again, leading to side effects.
  116. // TODO: check how return with value behaves under such conditions
  117. // in CPython.
  118. self->code_state.ip = 0;
  119. *ret_val = *self->code_state.sp;
  120. break;
  121. case MP_VM_RETURN_YIELD:
  122. *ret_val = *self->code_state.sp;
  123. #if MICROPY_PY_GENERATOR_PEND_THROW
  124. *self->code_state.sp = mp_const_none;
  125. #endif
  126. break;
  127. case MP_VM_RETURN_EXCEPTION: {
  128. size_t n_state = mp_decode_uint_value(self->code_state.fun_bc->bytecode);
  129. self->code_state.ip = 0;
  130. *ret_val = self->code_state.state[n_state - 1];
  131. break;
  132. }
  133. }
  134. return ret_kind;
  135. }
  136. STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value) {
  137. mp_obj_t ret;
  138. switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
  139. case MP_VM_RETURN_NORMAL:
  140. default:
  141. // Optimize return w/o value in case generator is used in for loop
  142. if (ret == mp_const_none || ret == MP_OBJ_STOP_ITERATION) {
  143. return MP_OBJ_STOP_ITERATION;
  144. } else {
  145. nlr_raise(mp_obj_new_exception_args(&mp_type_StopIteration, 1, &ret));
  146. }
  147. case MP_VM_RETURN_YIELD:
  148. return ret;
  149. case MP_VM_RETURN_EXCEPTION:
  150. // TODO: Optimization of returning MP_OBJ_STOP_ITERATION is really part
  151. // of mp_iternext() protocol, but this function is called by other methods
  152. // too, which may not handled MP_OBJ_STOP_ITERATION.
  153. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
  154. mp_obj_t val = mp_obj_exception_get_value(ret);
  155. if (val == mp_const_none) {
  156. return MP_OBJ_STOP_ITERATION;
  157. }
  158. }
  159. nlr_raise(ret);
  160. }
  161. }
  162. STATIC mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
  163. return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL);
  164. }
  165. STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
  166. mp_obj_t ret = gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL);
  167. if (ret == MP_OBJ_STOP_ITERATION) {
  168. nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
  169. } else {
  170. return ret;
  171. }
  172. }
  173. STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
  174. STATIC mp_obj_t gen_instance_close(mp_obj_t self_in);
  175. STATIC mp_obj_t gen_instance_throw(size_t n_args, const mp_obj_t *args) {
  176. mp_obj_t exc = (n_args == 2) ? args[1] : args[2];
  177. mp_obj_t ret = gen_resume_and_raise(args[0], mp_const_none, exc);
  178. if (ret == MP_OBJ_STOP_ITERATION) {
  179. nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
  180. } else {
  181. return ret;
  182. }
  183. }
  184. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(gen_instance_throw_obj, 2, 4, gen_instance_throw);
  185. STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) {
  186. mp_obj_t ret;
  187. switch (mp_obj_gen_resume(self_in, mp_const_none, MP_OBJ_FROM_PTR(&mp_const_GeneratorExit_obj), &ret)) {
  188. case MP_VM_RETURN_YIELD:
  189. mp_raise_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit");
  190. // Swallow StopIteration & GeneratorExit (== successful close), and re-raise any other
  191. case MP_VM_RETURN_EXCEPTION:
  192. // ret should always be an instance of an exception class
  193. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit)) ||
  194. mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
  195. return mp_const_none;
  196. }
  197. nlr_raise(ret);
  198. default:
  199. // The only choice left is MP_VM_RETURN_NORMAL which is successful close
  200. return mp_const_none;
  201. }
  202. }
  203. STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
  204. STATIC mp_obj_t gen_instance_pend_throw(mp_obj_t self_in, mp_obj_t exc_in) {
  205. mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in);
  206. if (self->code_state.sp == self->code_state.state - 1) {
  207. mp_raise_TypeError("can't pend throw to just-started generator");
  208. }
  209. mp_obj_t prev = *self->code_state.sp;
  210. *self->code_state.sp = exc_in;
  211. return prev;
  212. }
  213. STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_pend_throw_obj, gen_instance_pend_throw);
  214. STATIC const mp_rom_map_elem_t gen_instance_locals_dict_table[] = {
  215. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&gen_instance_close_obj) },
  216. { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&gen_instance_send_obj) },
  217. { MP_ROM_QSTR(MP_QSTR_throw), MP_ROM_PTR(&gen_instance_throw_obj) },
  218. #if MICROPY_PY_GENERATOR_PEND_THROW
  219. { MP_ROM_QSTR(MP_QSTR_pend_throw), MP_ROM_PTR(&gen_instance_pend_throw_obj) },
  220. #endif
  221. };
  222. STATIC MP_DEFINE_CONST_DICT(gen_instance_locals_dict, gen_instance_locals_dict_table);
  223. const mp_obj_type_t mp_type_gen_instance = {
  224. { &mp_type_type },
  225. .name = MP_QSTR_generator,
  226. .print = gen_instance_print,
  227. .unary_op = mp_generic_unary_op,
  228. .getiter = mp_identity_getiter,
  229. .iternext = gen_instance_iternext,
  230. .locals_dict = (mp_obj_dict_t*)&gen_instance_locals_dict,
  231. };