objgenerator.c 9.25 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
STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
22
23
    mp_obj_gen_wrap_t *self = self_in;
    mp_obj_t self_fun = self->fun;
24
    assert(MP_OBJ_IS_TYPE(self_fun, &mp_type_fun_bc));
25
26
    int bc_n_args;
    const byte *bc_code;
27
    mp_obj_fun_bc_get(self_fun, &bc_n_args, &bc_code);
28
    if (n_args != bc_n_args) {
29
        nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "function takes %d positional arguments but %d were given", bc_n_args, n_args));
30
    }
31
    if (n_kw != 0) {
32
        nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "function does not take keyword arguments"));
33
    }
Damien George's avatar
Damien George committed
34

35
    return mp_obj_new_gen_instance(bc_code, n_args, args);
36
37
}

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

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

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

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

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

mp_obj_t gen_instance_getiter(mp_obj_t self_in) {
    return self_in;
}

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

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

        case MP_VM_RETURN_YIELD:
106
107
            *ret_val = *self->sp;
            break;
108
109
110

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

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

    return ret_kind;
121
122
123
}

STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value) {
124
125
    mp_obj_t ret;
    switch (mp_obj_gen_resume(self_in, send_value, throw_value, &ret)) {
126
127
128
        case MP_VM_RETURN_NORMAL:
            // Optimize return w/o value in case generator is used in for loop
            if (ret == mp_const_none) {
129
                return MP_OBJ_NULL;
130
            } else {
131
                nlr_jump(mp_obj_new_exception_args(&mp_type_StopIteration, 1, &ret));
132
133
134
            }

        case MP_VM_RETURN_YIELD:
135
            return ret;
136
137

        case MP_VM_RETURN_EXCEPTION:
138
139
140
141
142
143
144
145
            // 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 {
                nlr_jump(ret);
            }
146

147
148
149
        default:
            assert(0);
            return mp_const_none;
150
151
    }
}
152
153

mp_obj_t gen_instance_iternext(mp_obj_t self_in) {
154
    return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL);
155
156
}

157
STATIC mp_obj_t gen_instance_send(mp_obj_t self_in, mp_obj_t send_value) {
158
    mp_obj_t ret = gen_resume_and_raise(self_in, send_value, MP_OBJ_NULL);
159
    if (ret == MP_OBJ_NULL) {
160
161
162
        nlr_jump(mp_obj_new_exception(&mp_type_StopIteration));
    } else {
        return ret;
163
    }
164
}
165

166
STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send);
167

168
STATIC mp_obj_t gen_instance_close(mp_obj_t self_in);
169
STATIC mp_obj_t gen_instance_throw(uint n_args, const mp_obj_t *args) {
170
    mp_obj_t exc = (n_args == 2) ? args[1] : args[2];
Damien George's avatar
Damien George committed
171
    exc = mp_make_raise_obj(exc);
172
173
174
175
176
177
178
179
180
    if (mp_obj_is_subclass_fast(mp_obj_get_type(exc), &mp_type_GeneratorExit)) {
        // Throwing GeneratorExit is equivalent of calling close aka
        // GeneratorExit should be handled specially
        // TODO: Calling .close() will throw new exception instance, not one
        // given to throw, which is not ok.
        return gen_instance_close(args[0]);
    }

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

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

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

196
197
198
199
200
201
202
203
204
205
206
        // 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;
            }
            nlr_jump(ret);

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

STATIC MP_DEFINE_CONST_FUN_OBJ_1(gen_instance_close_obj, gen_instance_close);
212

213
214
215
216
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 },
217
};
218

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
225
226
    .print = gen_instance_print,
    .getiter = gen_instance_getiter,
    .iternext = gen_instance_iternext,
227
    .locals_dict = (mp_obj_t)&gen_instance_locals_dict,
228
229
};

230
mp_obj_t mp_obj_new_gen_instance(const byte *bytecode, int n_args, const mp_obj_t *args) {
231
    const byte *code_info = bytecode;
232
233
234
235
    // 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;

236
237
238
239
    // 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;
240
241
242
243
244
245
246
247

    // bytecode prelude: initialise closed over variables
    // TODO
    // for now we just make sure there are no cells variables
    // need to work out how to implement closed over variables in generators
    assert(bytecode[0] == 0);
    bytecode += 1;

248
    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));
249
    o->base.type = &mp_type_gen_instance;
250
    o->code_info = code_info;
251
    o->ip = bytecode;
252
    o->sp = &o->state[0] - 1; // sp points to top of stack, which starts off 1 below the state
253
    o->exc_sp = (mp_exc_stack_t*)(o->state + n_state) - 1;
254
    o->n_state = n_state;
255

256
    // copy args to end of state array, in reverse (that's how mp_execute_byte_code_2 needs it)
257
    for (int i = 0; i < n_args; i++) {
258
        o->state[n_state - 1 - i] = args[i];
259
260
    }

261
262
    return o;
}