objgenerator.c 9.58 KB
Newer Older
1
2
3
4
5
6
#include <stdlib.h>
#include <assert.h>

#include "nlr.h"
#include "misc.h"
#include "mpconfig.h"
7
#include "qstr.h"
8
9
10
#include "obj.h"
#include "runtime.h"
#include "bc.h"
11
#include "objgenerator.h"
12
13
14
15
16
17
18
19
20

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

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

21
22
mp_obj_t mp_obj_new_gen_instance(const byte *bytecode, uint n_args, const mp_obj_t *args, uint n_args2, const mp_obj_t *args2);

23
STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
24
25
    mp_obj_gen_wrap_t *self = self_in;
    mp_obj_t self_fun = self->fun;
26
    assert(MP_OBJ_IS_TYPE(self_fun, &mp_type_fun_bc));
27
28
    int bc_n_args;
    const byte *bc_code;
29
    mp_obj_fun_bc_get(self_fun, &bc_n_args, &bc_code);
Damien George's avatar
Damien George committed
30

31
32
    const mp_obj_t *args1, *args2;
    uint len1, len2;
33
34
35
    if (!mp_obj_fun_prepare_simple_args(self_fun, n_args, n_kw, args, &len1, &args1, &len2, &args2)) {
        assert(0);
    }
36
37

    return mp_obj_new_gen_instance(bc_code, len1, args1, len2, args2);
38
39
}

40
const mp_obj_type_t mp_type_gen_wrap = {
41
    { &mp_type_type },
42
    .name = MP_QSTR_generator,
43
    .call = gen_wrap_call,
44
45
};

46
mp_obj_t mp_obj_new_gen_wrap(mp_obj_t fun) {
47
    mp_obj_gen_wrap_t *o = m_new_obj(mp_obj_gen_wrap_t);
48
    o->base.type = &mp_type_gen_wrap;
49
50
51
52
53
54
55
56
57
    o->fun = fun;
    return o;
}

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

typedef struct _mp_obj_gen_instance_t {
    mp_obj_base_t base;
58
    const byte *code_info;
59
60
    const byte *ip;
    mp_obj_t *sp;
61
    // bit 0 is saved currently_in_except_block value
62
    mp_exc_stack_t *exc_sp;
63
    uint n_state;
64
65
66
    // Variable-length
    mp_obj_t state[0];
    // Variable-length, never accessed by name, only as (void*)(state + n_state)
67
    mp_exc_stack_t exc_state[0];
68
69
} mp_obj_gen_instance_t;

70
void gen_instance_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
71
72
73
74
75
76
77
    print(env, "<generator object 'fun-name' at %p>", self_in);
}

mp_obj_t gen_instance_getiter(mp_obj_t self_in) {
    return self_in;
}

78
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) {
79
    assert(MP_OBJ_IS_TYPE(self_in, &mp_type_gen_instance));
80
    mp_obj_gen_instance_t *self = self_in;
81
    if (self->ip == 0) {
82
83
        *ret_val = MP_OBJ_NULL;
        return MP_VM_RETURN_NORMAL;
84
    }
85
86
    if (self->sp == self->state - 1) {
        if (send_value != mp_const_none) {
87
            nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "can't send non-None value to a just-started generator"));
88
89
90
91
        }
    } else {
        *self->sp = send_value;
    }
92
    mp_vm_return_kind_t ret_kind = mp_execute_byte_code_2(self->code_info, &self->ip,
93
        &self->state[self->n_state - 1], &self->sp, (mp_exc_stack_t*)(self->state + self->n_state),
94
        &self->exc_sp, throw_value);
95

96
    switch (ret_kind) {
97
98
99
100
101
102
103
        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.
            self->ip = 0;
104
105
            *ret_val = *self->sp;
            break;
106
107

        case MP_VM_RETURN_YIELD:
108
109
            *ret_val = *self->sp;
            break;
110
111
112

        case MP_VM_RETURN_EXCEPTION:
            self->ip = 0;
113
114
            *ret_val = self->state[self->n_state - 1];
            break;
115
116
117

        default:
            assert(0);
118
119
            *ret_val = mp_const_none;
            break;
120
    }
121
122

    return ret_kind;
123
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
127
    mp_obj_t ret;
    switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
128
129
        case MP_VM_RETURN_NORMAL:
            // Optimize return w/o value in case generator is used in for loop
130
            if (ret == mp_const_none || ret == MP_OBJ_NULL) {
131
                return MP_OBJ_NULL;
132
            } else {
133
                nlr_raise(mp_obj_new_exception_args(&mp_type_StopIteration, 1, &ret));
134
135
136
            }

        case MP_VM_RETURN_YIELD:
137
            if (throw_value != MP_OBJ_NULL && mp_obj_is_subclass_fast(mp_obj_get_type(throw_value), &mp_type_GeneratorExit)) {
138
                nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit"));
139
            }
140
            return ret;
141
142

        case MP_VM_RETURN_EXCEPTION:
143
144
145
146
147
148
            // TODO: Optimization of returning MP_OBJ_NULL is really part
            // of mp_iternext() protocol, but this function is called by other methods
            // too, which may not handled MP_OBJ_NULL.
            if (mp_obj_is_subclass_fast(mp_obj_get_type(ret), &mp_type_StopIteration)) {
                return MP_OBJ_NULL;
            } else {
149
                nlr_raise(ret);
150
            }
151

152
153
154
        default:
            assert(0);
            return mp_const_none;
155
156
    }
}
157
158

mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
159
    return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL);
160
161
}

162
STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
163
    mp_obj_t ret = gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL);
164
    if (ret == MP_OBJ_NULL) {
165
        nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
166
167
    } else {
        return ret;
168
    }
169
}
170

171
STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
172

173
STATIC mp_obj_t gen_instance_close(mp_obj_t self_in);
174
STATIC mp_obj_t gen_instance_throw(uint n_args, const mp_obj_t *args) {
175
    mp_obj_t exc = (n_args == 2) ? args[1] : args[2];
Damien George's avatar
Damien George committed
176
    exc = mp_make_raise_obj(exc);
177
178

    mp_obj_t ret = gen_resume_and_raise(args[0], mp_const_none, exc);
179
    if (ret == MP_OBJ_NULL) {
180
        nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
181
182
183
184
185
186
187
    } else {
        return ret;
    }
}

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

188
STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) {
189
    mp_obj_t ret;
190
    switch (mp_obj_gen_resume(self_in, mp_const_none, (mp_obj_t)&mp_const_GeneratorExit_obj, &ret)) {
191
        case MP_VM_RETURN_YIELD:
192
            nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit"));
193

194
195
196
197
198
199
200
        // 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;
            }
201
            nlr_raise(ret);
202
203
204

        default:
            // The only choice left is MP_VM_RETURN_NORMAL which is successful close
205
206
207
208
209
            return mp_const_none;
    }
}

STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
210

211
212
213
214
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 },
215
};
216

217
218
STATIC MP_DEFINE_CONST_DICT(gen_instance_locals_dict, gen_instance_locals_dict_table);

219
const mp_obj_type_t mp_type_gen_instance = {
220
    { &mp_type_type },
221
    .name = MP_QSTR_generator,
222
223
224
    .print = gen_instance_print,
    .getiter = gen_instance_getiter,
    .iternext = gen_instance_iternext,
225
    .locals_dict = (mp_obj_t)&gen_instance_locals_dict,
226
227
};

228
mp_obj_t mp_obj_new_gen_instance(const byte *bytecode, uint n_args, const mp_obj_t *args, uint n_args2, const mp_obj_t *args2) {
229
    const byte *code_info = bytecode;
230
231
232
233
    // get code info size, and skip the line number table
    machine_uint_t code_info_size = bytecode[0] | (bytecode[1] << 8) | (bytecode[2] << 16) | (bytecode[3] << 24);
    bytecode += code_info_size;

234
235
236
237
    // bytecode prelude: get state size and exception stack size
    machine_uint_t n_state = bytecode[0] | (bytecode[1] << 8);
    machine_uint_t n_exc_stack = bytecode[2] | (bytecode[3] << 8);
    bytecode += 4;
238

239
    // allocate the generator object, with room for local stack and exception stack
240
    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));
241
    o->base.type = &mp_type_gen_instance;
242
    o->code_info = code_info;
243
    o->sp = &o->state[0] - 1; // sp points to top of stack, which starts off 1 below the state
244
    o->exc_sp = (mp_exc_stack_t*)(o->state + n_state) - 1;
245
    o->n_state = n_state;
246

247
    // copy args to end of state array, in reverse (that's how mp_execute_byte_code_2 needs it)
248
    for (uint i = 0; i < n_args; i++) {
249
        o->state[n_state - 1 - i] = args[i];
250
    }
251
252
253
    for (uint i = 0; i < n_args2; i++) {
        o->state[n_state - 1 - n_args - i] = args2[i];
    }
254

255
256
257
258
259
260
261
262
263
264
265
266
267
    // bytecode prelude: initialise closed over variables
    for (uint n_local = *bytecode++; n_local > 0; n_local--) {
        uint local_num = *bytecode++;
        if (local_num < n_args + n_args2) {
            o->state[n_state - 1 - local_num] = mp_obj_new_cell(o->state[n_state - 1 - local_num]);
        } else {
            o->state[n_state - 1 - local_num] = mp_obj_new_cell(MP_OBJ_NULL);
        }
    }

    // set ip to start of actual byte code
    o->ip = bytecode;

268
269
    return o;
}