objgenerator.c 9.41 KB
Newer Older
1
2
3
4
5
6
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
7
 * Copyright (c) 2014 Paul Sokolovsky
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

28
29
30
#include <stdlib.h>
#include <assert.h>

31
#include "mpconfig.h"
32
33
#include "nlr.h"
#include "misc.h"
34
#include "qstr.h"
35
36
37
#include "obj.h"
#include "runtime.h"
#include "bc.h"
38
#include "objgenerator.h"
39
#include "objfun.h"
40
41
42
43
44
45
46
47
48

/******************************************************************************/
/* generator wrapper                                                          */

typedef struct _mp_obj_gen_wrap_t {
    mp_obj_base_t base;
    mp_obj_t *fun;
} mp_obj_gen_wrap_t;

49
50
51
52
53
typedef struct _mp_obj_gen_instance_t {
    mp_obj_base_t base;
    mp_obj_dict_t *globals;
    mp_code_state code_state;
} mp_obj_gen_instance_t;
54

55
STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
56
    mp_obj_gen_wrap_t *self = self_in;
57
    mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t*)self->fun;
58
    assert(MP_OBJ_IS_TYPE(self_fun, &mp_type_fun_bc));
Damien George's avatar
Damien George committed
59

60
61
    const byte *bytecode = self_fun->bytecode;
    // get code info size, and skip the line number table
62
    mp_uint_t code_info_size = bytecode[0] | (bytecode[1] << 8) | (bytecode[2] << 16) | (bytecode[3] << 24);
63
64
65
    bytecode += code_info_size;

    // bytecode prelude: get state size and exception stack size
66
67
    mp_uint_t n_state = bytecode[0] | (bytecode[1] << 8);
    mp_uint_t n_exc_stack = bytecode[2] | (bytecode[3] << 8);
68
69
70
71
72
73
74
75
76
77
78
79
    bytecode += 4;

    // allocate the generator object, with room for local stack and exception stack
    mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte,
        n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t));
    o->base.type = &mp_type_gen_instance;

    o->globals = self_fun->globals;
    o->code_state.n_state = n_state;
    o->code_state.ip = bytecode;
    mp_setup_code_state(&o->code_state, self_fun, n_args, n_kw, args);
    return o;
80
81
}

82
const mp_obj_type_t mp_type_gen_wrap = {
83
    { &mp_type_type },
84
    .name = MP_QSTR_generator,
85
    .call = gen_wrap_call,
86
87
};

88
mp_obj_t mp_obj_new_gen_wrap(mp_obj_t fun) {
89
    mp_obj_gen_wrap_t *o = m_new_obj(mp_obj_gen_wrap_t);
90
    o->base.type = &mp_type_gen_wrap;
91
92
93
94
95
96
97
    o->fun = fun;
    return o;
}

/******************************************************************************/
/* generator instance                                                         */

98
void gen_instance_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
99
    mp_obj_gen_instance_t *self = self_in;
100
    print(env, "<generator object '%s' at %p>", mp_obj_code_get_name(self->code_state.code_info), self_in);
101
102
}

103
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) {
104
    assert(MP_OBJ_IS_TYPE(self_in, &mp_type_gen_instance));
105
    mp_obj_gen_instance_t *self = self_in;
106
    if (self->code_state.ip == 0) {
107
        *ret_val = MP_OBJ_STOP_ITERATION;
108
        return MP_VM_RETURN_NORMAL;
109
    }
110
    if (self->code_state.sp == self->code_state.state - 1) {
111
        if (send_value != mp_const_none) {
112
            nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "can't send non-None value to a just-started generator"));
113
114
        }
    } else {
115
        *self->code_state.sp = send_value;
116
    }
117
118
    mp_obj_dict_t *old_globals = mp_globals_get();
    mp_globals_set(self->globals);
119
    mp_vm_return_kind_t ret_kind = mp_execute_bytecode(&self->code_state, throw_value);
120
    mp_globals_set(old_globals);
121

122
    switch (ret_kind) {
123
124
125
126
127
128
        case MP_VM_RETURN_NORMAL:
            // Explicitly mark generator as completed. If we don't do this,
            // subsequent next() may re-execute statements after last yield
            // again and again, leading to side effects.
            // TODO: check how return with value behaves under such conditions
            // in CPython.
129
130
            self->code_state.ip = 0;
            *ret_val = *self->code_state.sp;
131
            break;
132
133

        case MP_VM_RETURN_YIELD:
134
            *ret_val = *self->code_state.sp;
135
            break;
136
137

        case MP_VM_RETURN_EXCEPTION:
138
139
            self->code_state.ip = 0;
            *ret_val = self->code_state.state[self->code_state.n_state - 1];
140
            break;
141
142
143

        default:
            assert(0);
144
145
            *ret_val = mp_const_none;
            break;
146
    }
147
148

    return ret_kind;
149
150
151
}

STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value) {
152
153
    mp_obj_t ret;
    switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
154
155
        case MP_VM_RETURN_NORMAL:
            // Optimize return w/o value in case generator is used in for loop
156
157
            if (ret == mp_const_none || ret == MP_OBJ_STOP_ITERATION) {
                return MP_OBJ_STOP_ITERATION;
158
            } else {
159
                nlr_raise(mp_obj_new_exception_args(&mp_type_StopIteration, 1, &ret));
160
161
162
            }

        case MP_VM_RETURN_YIELD:
163
            if (throw_value != MP_OBJ_NULL && mp_obj_is_subclass_fast(mp_obj_get_type(throw_value), &mp_type_GeneratorExit)) {
164
                nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit"));
165
            }
166
            return ret;
167
168

        case MP_VM_RETURN_EXCEPTION:
169
            // TODO: Optimization of returning MP_OBJ_STOP_ITERATION is really part
170
            // of mp_iternext() protocol, but this function is called by other methods
171
            // too, which may not handled MP_OBJ_STOP_ITERATION.
172
            if (mp_obj_is_subclass_fast(mp_obj_get_type(ret), &mp_type_StopIteration)) {
173
                return MP_OBJ_STOP_ITERATION;
174
            } else {
175
                nlr_raise(ret);
176
            }
177

178
179
180
        default:
            assert(0);
            return mp_const_none;
181
182
    }
}
183
184

mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
185
    return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL);
186
187
}

188
STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
189
    mp_obj_t ret = gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL);
190
    if (ret == MP_OBJ_STOP_ITERATION) {
191
        nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
192
193
    } else {
        return ret;
194
    }
195
}
196

197
STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
198

199
STATIC mp_obj_t gen_instance_close(mp_obj_t self_in);
200
STATIC mp_obj_t gen_instance_throw(mp_uint_t n_args, const mp_obj_t *args) {
201
    mp_obj_t exc = (n_args == 2) ? args[1] : args[2];
Damien George's avatar
Damien George committed
202
    exc = mp_make_raise_obj(exc);
203
204

    mp_obj_t ret = gen_resume_and_raise(args[0], mp_const_none, exc);
205
    if (ret == MP_OBJ_STOP_ITERATION) {
206
        nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
207
208
209
210
211
212
213
    } else {
        return ret;
    }
}

STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(gen_instance_throw_obj, 2, 4, gen_instance_throw);

214
STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) {
215
    mp_obj_t ret;
216
    switch (mp_obj_gen_resume(self_in, mp_const_none, (mp_obj_t)&mp_const_GeneratorExit_obj, &ret)) {
217
        case MP_VM_RETURN_YIELD:
218
            nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit"));
219

220
221
222
223
224
225
226
        // Swallow StopIteration & GeneratorExit (== successful close), and re-raise any other
        case MP_VM_RETURN_EXCEPTION:
            // ret should always be an instance of an exception class
            if (mp_obj_is_subclass_fast(mp_obj_get_type(ret), &mp_type_GeneratorExit) ||
                mp_obj_is_subclass_fast(mp_obj_get_type(ret), &mp_type_StopIteration)) {
                return mp_const_none;
            }
227
            nlr_raise(ret);
228
229
230

        default:
            // The only choice left is MP_VM_RETURN_NORMAL which is successful close
231
232
233
234
235
            return mp_const_none;
    }
}

STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
236

237
238
239
240
STATIC const mp_map_elem_t gen_instance_locals_dict_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&gen_instance_close_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_send), (mp_obj_t)&gen_instance_send_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_throw), (mp_obj_t)&gen_instance_throw_obj },
241
};
242

243
244
STATIC MP_DEFINE_CONST_DICT(gen_instance_locals_dict, gen_instance_locals_dict_table);

245
const mp_obj_type_t mp_type_gen_instance = {
246
    { &mp_type_type },
247
    .name = MP_QSTR_generator,
248
    .print = gen_instance_print,
Paul Sokolovsky's avatar
Paul Sokolovsky committed
249
    .getiter = mp_identity,
250
    .iternext = gen_instance_iternext,
251
    .locals_dict = (mp_obj_t)&gen_instance_locals_dict,
252
};