objgenerator.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 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. *self->code_state.sp = send_value;
  94. }
  95. mp_obj_dict_t *old_globals = mp_globals_get();
  96. mp_globals_set(self->globals);
  97. mp_vm_return_kind_t ret_kind = mp_execute_bytecode(&self->code_state, throw_value);
  98. mp_globals_set(old_globals);
  99. switch (ret_kind) {
  100. case MP_VM_RETURN_NORMAL:
  101. default:
  102. // Explicitly mark generator as completed. If we don't do this,
  103. // subsequent next() may re-execute statements after last yield
  104. // again and again, leading to side effects.
  105. // TODO: check how return with value behaves under such conditions
  106. // in CPython.
  107. self->code_state.ip = 0;
  108. *ret_val = *self->code_state.sp;
  109. break;
  110. case MP_VM_RETURN_YIELD:
  111. *ret_val = *self->code_state.sp;
  112. if (*ret_val == MP_OBJ_STOP_ITERATION) {
  113. self->code_state.ip = 0;
  114. }
  115. break;
  116. case MP_VM_RETURN_EXCEPTION: {
  117. size_t n_state = mp_decode_uint_value(self->code_state.fun_bc->bytecode);
  118. self->code_state.ip = 0;
  119. *ret_val = self->code_state.state[n_state - 1];
  120. break;
  121. }
  122. }
  123. return ret_kind;
  124. }
  125. STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value) {
  126. mp_obj_t ret;
  127. switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
  128. case MP_VM_RETURN_NORMAL:
  129. default:
  130. // Optimize return w/o value in case generator is used in for loop
  131. if (ret == mp_const_none || ret == MP_OBJ_STOP_ITERATION) {
  132. return MP_OBJ_STOP_ITERATION;
  133. } else {
  134. nlr_raise(mp_obj_new_exception_args(&mp_type_StopIteration, 1, &ret));
  135. }
  136. case MP_VM_RETURN_YIELD:
  137. return ret;
  138. case MP_VM_RETURN_EXCEPTION:
  139. // TODO: Optimization of returning MP_OBJ_STOP_ITERATION is really part
  140. // of mp_iternext() protocol, but this function is called by other methods
  141. // too, which may not handled MP_OBJ_STOP_ITERATION.
  142. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
  143. mp_obj_t val = mp_obj_exception_get_value(ret);
  144. if (val == mp_const_none) {
  145. return MP_OBJ_STOP_ITERATION;
  146. }
  147. }
  148. nlr_raise(ret);
  149. }
  150. }
  151. STATIC mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
  152. return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL);
  153. }
  154. STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
  155. mp_obj_t ret = gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL);
  156. if (ret == MP_OBJ_STOP_ITERATION) {
  157. nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
  158. } else {
  159. return ret;
  160. }
  161. }
  162. STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
  163. STATIC mp_obj_t gen_instance_close(mp_obj_t self_in);
  164. STATIC mp_obj_t gen_instance_throw(size_t n_args, const mp_obj_t *args) {
  165. mp_obj_t exc = (n_args == 2) ? args[1] : args[2];
  166. mp_obj_t ret = gen_resume_and_raise(args[0], mp_const_none, exc);
  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_VAR_BETWEEN(gen_instance_throw_obj, 2, 4, gen_instance_throw);
  174. STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) {
  175. mp_obj_t ret;
  176. switch (mp_obj_gen_resume(self_in, mp_const_none, MP_OBJ_FROM_PTR(&mp_const_GeneratorExit_obj), &ret)) {
  177. case MP_VM_RETURN_YIELD:
  178. mp_raise_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit");
  179. // Swallow StopIteration & GeneratorExit (== successful close), and re-raise any other
  180. case MP_VM_RETURN_EXCEPTION:
  181. // ret should always be an instance of an exception class
  182. if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit)) ||
  183. mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
  184. return mp_const_none;
  185. }
  186. nlr_raise(ret);
  187. default:
  188. // The only choice left is MP_VM_RETURN_NORMAL which is successful close
  189. return mp_const_none;
  190. }
  191. }
  192. STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
  193. STATIC const mp_rom_map_elem_t gen_instance_locals_dict_table[] = {
  194. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&gen_instance_close_obj) },
  195. { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&gen_instance_send_obj) },
  196. { MP_ROM_QSTR(MP_QSTR_throw), MP_ROM_PTR(&gen_instance_throw_obj) },
  197. };
  198. STATIC MP_DEFINE_CONST_DICT(gen_instance_locals_dict, gen_instance_locals_dict_table);
  199. const mp_obj_type_t mp_type_gen_instance = {
  200. { &mp_type_type },
  201. .name = MP_QSTR_generator,
  202. .print = gen_instance_print,
  203. .unary_op = mp_generic_unary_op,
  204. .getiter = mp_identity_getiter,
  205. .iternext = gen_instance_iternext,
  206. .locals_dict = (mp_obj_dict_t*)&gen_instance_locals_dict,
  207. };