objgenerator.c 10 KB

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