vm.c 55.9 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.
 */

Damien's avatar
Damien committed
28
#include <stdio.h>
29
#include <string.h>
Damien's avatar
Damien committed
30
31
#include <assert.h>

32
#include "py/mpstate.h"
33
34
#include "py/nlr.h"
#include "py/emitglue.h"
35
#include "py/objtype.h"
36
37
38
#include "py/runtime.h"
#include "py/bc0.h"
#include "py/bc.h"
Damien's avatar
Damien committed
39

40
#if 0
41
#define TRACE(ip) printf("sp=" INT_FMT " ", sp - code_state->sp); mp_bytecode_print2(ip, 1);
42
43
44
#else
#define TRACE(ip)
#endif
45

Paul Sokolovsky's avatar
Paul Sokolovsky committed
46
47
48
49
50
51
52
// Value stack grows up (this makes it incompatible with native C stack, but
// makes sure that arguments to functions are in natural order arg1..argN
// (Python semantics mandates left-to-right evaluation order, including for
// function arguments). Stack pointer is pre-incremented and points at the
// top element.
// Exception stack also grows up, top element is also pointed at.

53
// Exception stack unwind reasons (WHY_* in CPython-speak)
54
55
// TODO perhaps compress this to RETURN=0, JUMP>0, with number of unwinds
// left to do encoded in the JUMP number
56
57
typedef enum {
    UNWIND_RETURN = 1,
58
    UNWIND_JUMP,
59
60
} mp_unwind_reason_t;

61
62
#define DECODE_UINT \
    mp_uint_t unum = 0; \
63
64
    do { \
        unum = (unum << 7) + (*ip & 0x7f); \
65
66
67
    } while ((*ip++ & 0x80) != 0)
#define DECODE_ULABEL mp_uint_t ulab = (ip[0] | (ip[1] << 8)); ip += 2
#define DECODE_SLABEL mp_uint_t slab = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2
68
#define DECODE_QSTR qstr qst = 0; \
69
70
    do { \
        qst = (qst << 7) + (*ip & 0x7f); \
71
    } while ((*ip++ & 0x80) != 0)
72
#define DECODE_PTR \
73
    ip = (byte*)(((mp_uint_t)ip + sizeof(mp_uint_t) - 1) & (~(sizeof(mp_uint_t) - 1))); /* align ip */ \
74
75
    void *ptr = (void*)*(mp_uint_t*)ip; \
    ip += sizeof(mp_uint_t)
76
77
#define PUSH(val) *++sp = (val)
#define POP() (*sp--)
78
79
#define TOP() (*sp)
#define SET_TOP(val) *sp = (val)
Damien's avatar
Damien committed
80

81
82
83
84
85
86
#if MICROPY_PY_SYS_EXC_INFO
#define CLEAR_SYS_EXC_INFO() MP_STATE_VM(cur_exception) = MP_OBJ_NULL;
#else
#define CLEAR_SYS_EXC_INFO()
#endif

87
#define PUSH_EXC_BLOCK(with_or_finally) do { \
88
89
    DECODE_ULABEL; /* except labels are always forward */ \
    ++exc_sp; \
90
    exc_sp->handler = ip + ulab; \
91
    exc_sp->val_sp = MP_TAGPTR_MAKE(sp, ((with_or_finally) << 1) | currently_in_except_block); \
Damien George's avatar
Damien George committed
92
    exc_sp->prev_exc = MP_OBJ_NULL; \
93
94
    currently_in_except_block = 0; /* in a try block now */ \
} while (0)
95

96
#define POP_EXC_BLOCK() \
97
    currently_in_except_block = MP_TAGPTR_TAG0(exc_sp->val_sp); /* restore previous state */ \
98
99
    exc_sp--; /* pop back to previous exception handler */ \
    CLEAR_SYS_EXC_INFO() /* just clear sys.exc_info(), not compliant, but it shouldn't be used in 1st place */
100

101
102
// fastn has items in reverse order (fastn[0] is local[0], fastn[-1] is local[1], etc)
// sp points to bottom of stack which grows up
103
104
105
106
// returns:
//  MP_VM_RETURN_NORMAL, sp valid, return value in *sp
//  MP_VM_RETURN_YIELD, ip, sp valid, yielded value in *sp
//  MP_VM_RETURN_EXCEPTION, exception in fastn[0]
107
mp_vm_return_kind_t mp_execute_bytecode(mp_code_state *code_state, volatile mp_obj_t inject_exc) {
108
109
#define SELECTIVE_EXC_IP (0)
#if SELECTIVE_EXC_IP
110
#define MARK_EXC_IP_SELECTIVE() { code_state->ip = ip; } /* stores ip 1 byte past last opcode */
111
112
113
#define MARK_EXC_IP_GLOBAL()
#else
#define MARK_EXC_IP_SELECTIVE()
114
#define MARK_EXC_IP_GLOBAL() { code_state->ip = ip; } /* stores ip pointing to last opcode */
115
#endif
116
#if MICROPY_OPT_COMPUTED_GOTO
117
    #include "py/vmentrytable.h"
118
    #define DISPATCH() do { \
119
        TRACE(ip); \
120
        MARK_EXC_IP_GLOBAL(); \
121
        goto *entry_table[*ip++]; \
122
    } while (0)
123
    #define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check
124
125
    #define ENTRY(op) entry_##op
    #define ENTRY_DEFAULT entry_default
126
#else
127
    #define DISPATCH() break
128
    #define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check
129
130
    #define ENTRY(op) case op
    #define ENTRY_DEFAULT default
131
132
#endif

133
134
135
136
    // nlr_raise needs to be implemented as a goto, so that the C compiler's flow analyser
    // sees that it's possible for us to jump from the dispatch loop to the exception
    // handler.  Without this, the code may have a different stack layout in the dispatch
    // loop and the exception handler, leading to very obscure bugs.
137
    #define RAISE(o) do { nlr_pop(); nlr.ret_val = o; goto exception_handler; } while (0)
Damien's avatar
Damien committed
138

139
140
141
#if MICROPY_STACKLESS
run_code_state: ;
#endif
142
    // Pointers which are constant for particular invocation of mp_execute_bytecode()
143
144
    mp_obj_t * /*const*/ fastn = &code_state->state[code_state->n_state - 1];
    mp_exc_stack_t * /*const*/ exc_stack = (mp_exc_stack_t*)(code_state->state + code_state->n_state);
145

146
    // variables that are visible to the exception handler (declared volatile)
147
    volatile bool currently_in_except_block = MP_TAGPTR_TAG0(code_state->exc_sp); // 0 or 1, to detect nested exceptions
148
    mp_exc_stack_t *volatile exc_sp = MP_TAGPTR_PTR(code_state->exc_sp); // stack grows up, exc_sp points to top of stack
Damien's avatar
Damien committed
149

150
    // outer exception handling loop
Damien's avatar
Damien committed
151
    for (;;) {
152
        nlr_buf_t nlr;
153
outer_dispatch_loop:
154
        if (nlr_push(&nlr) == 0) {
155
            // local variables that are not visible to the exception handler
156
157
            const byte *ip = code_state->ip;
            mp_obj_t *sp = code_state->sp;
158
            mp_obj_t obj_shared;
159

160
161
162
            // If we have exception to inject, now that we finish setting up
            // execution context, raise it. This works as if RAISE_VARARGS
            // bytecode was executed.
163
164
165
            // Injecting exc into yield from generator is a special case,
            // handled by MP_BC_YIELD_FROM itself
            if (inject_exc != MP_OBJ_NULL && *ip != MP_BC_YIELD_FROM) {
166
                mp_obj_t exc = inject_exc;
167
                inject_exc = MP_OBJ_NULL;
168
169
                exc = mp_make_raise_obj(exc);
                RAISE(exc);
170
            }
171

172
173
            // loop to execute byte code
            for (;;) {
174
dispatch_loop:
175
#if MICROPY_OPT_COMPUTED_GOTO
176
177
                DISPATCH();
#else
178
                TRACE(ip);
179
                MARK_EXC_IP_GLOBAL();
180
                switch (*ip++) {
181
#endif
182

183
184
185
                ENTRY(MP_BC_LOAD_CONST_FALSE):
                    PUSH(mp_const_false);
                    DISPATCH();
186

187
188
189
                ENTRY(MP_BC_LOAD_CONST_NONE):
                    PUSH(mp_const_none);
                    DISPATCH();
190

191
192
193
                ENTRY(MP_BC_LOAD_CONST_TRUE):
                    PUSH(mp_const_true);
                    DISPATCH();
194

195
                ENTRY(MP_BC_LOAD_CONST_SMALL_INT): {
196
                    mp_int_t num = 0;
197
198
199
200
201
202
203
204
205
206
                    if ((ip[0] & 0x40) != 0) {
                        // Number is negative
                        num--;
                    }
                    do {
                        num = (num << 7) | (*ip & 0x7f);
                    } while ((*ip++ & 0x80) != 0);
                    PUSH(MP_OBJ_NEW_SMALL_INT(num));
                    DISPATCH();
                }
207

208
                ENTRY(MP_BC_LOAD_CONST_BYTES): {
209
210
211
                    DECODE_QSTR;
                    PUSH(mp_load_const_bytes(qst));
                    DISPATCH();
212
                }
213

214
                ENTRY(MP_BC_LOAD_CONST_STRING): {
215
216
217
                    DECODE_QSTR;
                    PUSH(mp_load_const_str(qst));
                    DISPATCH();
218
                }
219

220
221
222
223
224
225
                ENTRY(MP_BC_LOAD_CONST_OBJ): {
                    DECODE_PTR;
                    PUSH(ptr);
                    DISPATCH();
                }

226
227
228
229
                ENTRY(MP_BC_LOAD_NULL):
                    PUSH(MP_OBJ_NULL);
                    DISPATCH();

230
                ENTRY(MP_BC_LOAD_FAST_N): {
231
                    DECODE_UINT;
232
                    obj_shared = fastn[-unum];
233
                    load_check:
234
235
                    if (obj_shared == MP_OBJ_NULL) {
                        local_name_error: {
236
                            MARK_EXC_IP_SELECTIVE();
237
238
239
                            mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NameError, "local variable referenced before assignment");
                            RAISE(obj);
                        }
240
                    }
241
                    PUSH(obj_shared);
242
                    DISPATCH();
243
                }
244

245
                ENTRY(MP_BC_LOAD_DEREF): {
246
                    DECODE_UINT;
247
                    obj_shared = mp_obj_cell_get(fastn[-unum]);
248
                    goto load_check;
249
                }
250

251
                #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
252
                ENTRY(MP_BC_LOAD_NAME): {
253
                    MARK_EXC_IP_SELECTIVE();
254
255
256
                    DECODE_QSTR;
                    PUSH(mp_load_name(qst));
                    DISPATCH();
257
                }
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
                #else
                ENTRY(MP_BC_LOAD_NAME): {
                    MARK_EXC_IP_SELECTIVE();
                    DECODE_QSTR;
                    mp_obj_t key = MP_OBJ_NEW_QSTR(qst);
                    mp_uint_t x = *ip;
                    if (x < MP_STATE_CTX(dict_locals)->map.alloc && MP_STATE_CTX(dict_locals)->map.table[x].key == key) {
                        PUSH(MP_STATE_CTX(dict_locals)->map.table[x].value);
                    } else {
                        mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_CTX(dict_locals)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
                        if (elem != NULL) {
                            *(byte*)ip = (elem - &MP_STATE_CTX(dict_locals)->map.table[0]) & 0xff;
                            PUSH(elem->value);
                        } else {
                            PUSH(mp_load_name(MP_OBJ_QSTR_VALUE(key)));
                        }
                    }
                    ip++;
                    DISPATCH();
                }
                #endif
279

280
                #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
281
                ENTRY(MP_BC_LOAD_GLOBAL): {
282
                    MARK_EXC_IP_SELECTIVE();
283
284
285
                    DECODE_QSTR;
                    PUSH(mp_load_global(qst));
                    DISPATCH();
286
                }
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
                #else
                ENTRY(MP_BC_LOAD_GLOBAL): {
                    MARK_EXC_IP_SELECTIVE();
                    DECODE_QSTR;
                    mp_obj_t key = MP_OBJ_NEW_QSTR(qst);
                    mp_uint_t x = *ip;
                    if (x < MP_STATE_CTX(dict_globals)->map.alloc && MP_STATE_CTX(dict_globals)->map.table[x].key == key) {
                        PUSH(MP_STATE_CTX(dict_globals)->map.table[x].value);
                    } else {
                        mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_CTX(dict_globals)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
                        if (elem != NULL) {
                            *(byte*)ip = (elem - &MP_STATE_CTX(dict_globals)->map.table[0]) & 0xff;
                            PUSH(elem->value);
                        } else {
                            PUSH(mp_load_global(MP_OBJ_QSTR_VALUE(key)));
                        }
                    }
                    ip++;
                    DISPATCH();
                }
                #endif
308

309
                #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
310
                ENTRY(MP_BC_LOAD_ATTR): {
311
                    MARK_EXC_IP_SELECTIVE();
312
313
314
                    DECODE_QSTR;
                    SET_TOP(mp_load_attr(TOP(), qst));
                    DISPATCH();
315
                }
316
317
318
319
320
                #else
                ENTRY(MP_BC_LOAD_ATTR): {
                    MARK_EXC_IP_SELECTIVE();
                    DECODE_QSTR;
                    mp_obj_t top = TOP();
321
                    if (mp_obj_get_type(top)->attr == mp_obj_instance_attr) {
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
                        mp_obj_instance_t *self = top;
                        mp_uint_t x = *ip;
                        mp_obj_t key = MP_OBJ_NEW_QSTR(qst);
                        mp_map_elem_t *elem;
                        if (x < self->members.alloc && self->members.table[x].key == key) {
                            elem = &self->members.table[x];
                        } else {
                            elem = mp_map_lookup(&self->members, key, MP_MAP_LOOKUP);
                            if (elem != NULL) {
                                *(byte*)ip = elem - &self->members.table[0];
                            } else {
                                goto load_attr_cache_fail;
                            }
                        }
                        SET_TOP(elem->value);
                        ip++;
                        DISPATCH();
                    }
                load_attr_cache_fail:
                    SET_TOP(mp_load_attr(top, qst));
                    ip++;
                    DISPATCH();
                }
                #endif
346

347
                ENTRY(MP_BC_LOAD_METHOD): {
348
                    MARK_EXC_IP_SELECTIVE();
349
350
351
352
                    DECODE_QSTR;
                    mp_load_method(*sp, qst, sp);
                    sp += 1;
                    DISPATCH();
353
                }
354
355

                ENTRY(MP_BC_LOAD_BUILD_CLASS):
356
                    MARK_EXC_IP_SELECTIVE();
357
358
359
                    PUSH(mp_load_build_class());
                    DISPATCH();

360
                ENTRY(MP_BC_LOAD_SUBSCR): {
361
                    MARK_EXC_IP_SELECTIVE();
362
363
                    mp_obj_t index = POP();
                    SET_TOP(mp_obj_subscr(TOP(), index, MP_OBJ_SENTINEL));
364
                    DISPATCH();
365
                }
366

367
                ENTRY(MP_BC_STORE_FAST_N): {
368
369
370
                    DECODE_UINT;
                    fastn[-unum] = POP();
                    DISPATCH();
371
                }
372

373
                ENTRY(MP_BC_STORE_DEREF): {
374
375
376
                    DECODE_UINT;
                    mp_obj_cell_set(fastn[-unum], POP());
                    DISPATCH();
377
                }
378

379
                ENTRY(MP_BC_STORE_NAME): {
380
                    MARK_EXC_IP_SELECTIVE();
381
382
383
                    DECODE_QSTR;
                    mp_store_name(qst, POP());
                    DISPATCH();
384
                }
385

386
                ENTRY(MP_BC_STORE_GLOBAL): {
387
                    MARK_EXC_IP_SELECTIVE();
388
389
390
                    DECODE_QSTR;
                    mp_store_global(qst, POP());
                    DISPATCH();
391
                }
392

393
                #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
394
                ENTRY(MP_BC_STORE_ATTR): {
395
                    MARK_EXC_IP_SELECTIVE();
396
397
398
399
                    DECODE_QSTR;
                    mp_store_attr(sp[0], qst, sp[-1]);
                    sp -= 2;
                    DISPATCH();
400
                }
401
                #else
402
403
404
                // This caching code works with MICROPY_PY_BUILTINS_PROPERTY and/or
                // MICROPY_PY_DESCRIPTORS enabled because if the attr exists in
                // self->members then it can't be a property or have descriptors.  A
405
406
407
408
409
410
                // consequence of this is that we can't use MP_MAP_LOOKUP_ADD_IF_NOT_FOUND
                // in the fast-path below, because that store could override a property.
                ENTRY(MP_BC_STORE_ATTR): {
                    MARK_EXC_IP_SELECTIVE();
                    DECODE_QSTR;
                    mp_obj_t top = TOP();
411
                    if (mp_obj_get_type(top)->attr == mp_obj_instance_attr && sp[-1] != MP_OBJ_NULL) {
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
                        mp_obj_instance_t *self = top;
                        mp_uint_t x = *ip;
                        mp_obj_t key = MP_OBJ_NEW_QSTR(qst);
                        mp_map_elem_t *elem;
                        if (x < self->members.alloc && self->members.table[x].key == key) {
                            elem = &self->members.table[x];
                        } else {
                            elem = mp_map_lookup(&self->members, key, MP_MAP_LOOKUP);
                            if (elem != NULL) {
                                *(byte*)ip = elem - &self->members.table[0];
                            } else {
                                goto store_attr_cache_fail;
                            }
                        }
                        elem->value = sp[-1];
                        sp -= 2;
                        ip++;
                        DISPATCH();
                    }
                store_attr_cache_fail:
                    mp_store_attr(sp[0], qst, sp[-1]);
                    sp -= 2;
                    ip++;
                    DISPATCH();
                }
                #endif
438
439

                ENTRY(MP_BC_STORE_SUBSCR):
440
                    MARK_EXC_IP_SELECTIVE();
441
                    mp_obj_subscr(sp[-1], sp[0], sp[-2]);
442
443
444
                    sp -= 3;
                    DISPATCH();

445
                ENTRY(MP_BC_DELETE_FAST): {
446
                    MARK_EXC_IP_SELECTIVE();
447
448
449
450
451
452
                    DECODE_UINT;
                    if (fastn[-unum] == MP_OBJ_NULL) {
                        goto local_name_error;
                    }
                    fastn[-unum] = MP_OBJ_NULL;
                    DISPATCH();
453
                }
454

455
                ENTRY(MP_BC_DELETE_DEREF): {
456
                    MARK_EXC_IP_SELECTIVE();
457
458
459
460
461
462
                    DECODE_UINT;
                    if (mp_obj_cell_get(fastn[-unum]) == MP_OBJ_NULL) {
                        goto local_name_error;
                    }
                    mp_obj_cell_set(fastn[-unum], MP_OBJ_NULL);
                    DISPATCH();
463
                }
464

465
                ENTRY(MP_BC_DELETE_NAME): {
466
                    MARK_EXC_IP_SELECTIVE();
467
468
469
                    DECODE_QSTR;
                    mp_delete_name(qst);
                    DISPATCH();
470
                }
471

472
                ENTRY(MP_BC_DELETE_GLOBAL): {
473
                    MARK_EXC_IP_SELECTIVE();
474
475
476
                    DECODE_QSTR;
                    mp_delete_global(qst);
                    DISPATCH();
477
                }
478

479
480
481
                ENTRY(MP_BC_DUP_TOP): {
                    mp_obj_t top = TOP();
                    PUSH(top);
482
                    DISPATCH();
483
                }
484
485
486
487
488
489
490
491
492
493
494

                ENTRY(MP_BC_DUP_TOP_TWO):
                    sp += 2;
                    sp[0] = sp[-2];
                    sp[-1] = sp[-3];
                    DISPATCH();

                ENTRY(MP_BC_POP_TOP):
                    sp -= 1;
                    DISPATCH();

495
496
                ENTRY(MP_BC_ROT_TWO): {
                    mp_obj_t top = sp[0];
497
                    sp[0] = sp[-1];
498
                    sp[-1] = top;
499
                    DISPATCH();
500
                }
501

502
503
                ENTRY(MP_BC_ROT_THREE): {
                    mp_obj_t top = sp[0];
504
505
                    sp[0] = sp[-1];
                    sp[-1] = sp[-2];
506
                    sp[-2] = top;
507
                    DISPATCH();
508
                }
509

510
                ENTRY(MP_BC_JUMP): {
511
                    DECODE_SLABEL;
512
                    ip += slab;
513
                    DISPATCH_WITH_PEND_EXC_CHECK();
514
                }
515

516
                ENTRY(MP_BC_POP_JUMP_IF_TRUE): {
517
518
                    DECODE_SLABEL;
                    if (mp_obj_is_true(POP())) {
519
                        ip += slab;
520
                    }
521
                    DISPATCH_WITH_PEND_EXC_CHECK();
522
                }
Damien's avatar
Damien committed
523

524
                ENTRY(MP_BC_POP_JUMP_IF_FALSE): {
525
526
                    DECODE_SLABEL;
                    if (!mp_obj_is_true(POP())) {
527
                        ip += slab;
528
                    }
529
                    DISPATCH_WITH_PEND_EXC_CHECK();
530
                }
Damien's avatar
Damien committed
531

532
                ENTRY(MP_BC_JUMP_IF_TRUE_OR_POP): {
533
534
                    DECODE_SLABEL;
                    if (mp_obj_is_true(TOP())) {
535
                        ip += slab;
536
537
538
                    } else {
                        sp--;
                    }
539
                    DISPATCH_WITH_PEND_EXC_CHECK();
540
                }
541

542
                ENTRY(MP_BC_JUMP_IF_FALSE_OR_POP): {
543
544
545
546
                    DECODE_SLABEL;
                    if (mp_obj_is_true(TOP())) {
                        sp--;
                    } else {
547
                        ip += slab;
548
                    }
549
                    DISPATCH_WITH_PEND_EXC_CHECK();
550
                }
551

552
                ENTRY(MP_BC_SETUP_WITH): {
553
                    MARK_EXC_IP_SELECTIVE();
554
                    // stack: (..., ctx_mgr)
555
                    mp_obj_t obj = TOP();
556
557
558
559
                    mp_load_method(obj, MP_QSTR___exit__, sp);
                    mp_load_method(obj, MP_QSTR___enter__, sp + 2);
                    mp_obj_t ret = mp_call_method_n_kw(0, 0, sp + 2);
                    sp += 1;
560
                    PUSH_EXC_BLOCK(1);
561
                    PUSH(ret);
562
                    // stack: (..., __exit__, ctx_mgr, as_value)
563
                    DISPATCH();
564
                }
565
566

                ENTRY(MP_BC_WITH_CLEANUP): {
567
                    MARK_EXC_IP_SELECTIVE();
568
                    // Arriving here, there's "exception control block" on top of stack,
569
                    // and __exit__ method (with self) underneath it. Bytecode calls __exit__,
570
571
572
                    // and "deletes" it off stack, shifting "exception control block"
                    // to its place.
                    if (TOP() == mp_const_none) {
573
574
575
576
577
                        // stack: (..., __exit__, ctx_mgr, None)
                        sp[1] = mp_const_none;
                        sp[2] = mp_const_none;
                        sp -= 2;
                        mp_call_method_n_kw(3, 0, sp);
578
579
                        SET_TOP(mp_const_none);
                    } else if (MP_OBJ_IS_SMALL_INT(TOP())) {
580
581
                        mp_int_t cause_val = MP_OBJ_SMALL_INT_VALUE(TOP());
                        if (cause_val == UNWIND_RETURN) {
582
583
584
585
586
587
588
589
                            // stack: (..., __exit__, ctx_mgr, ret_val, UNWIND_RETURN)
                            mp_obj_t ret_val = sp[-1];
                            sp[-1] = mp_const_none;
                            sp[0] = mp_const_none;
                            sp[1] = mp_const_none;
                            mp_call_method_n_kw(3, 0, sp - 3);
                            sp[-3] = ret_val;
                            sp[-2] = MP_OBJ_NEW_SMALL_INT(UNWIND_RETURN);
590
591
                        } else {
                            assert(cause_val == UNWIND_JUMP);
592
593
594
595
596
597
598
599
600
601
                            // stack: (..., __exit__, ctx_mgr, dest_ip, num_exc, UNWIND_JUMP)
                            mp_obj_t dest_ip = sp[-2];
                            mp_obj_t num_exc = sp[-1];
                            sp[-2] = mp_const_none;
                            sp[-1] = mp_const_none;
                            sp[0] = mp_const_none;
                            mp_call_method_n_kw(3, 0, sp - 4);
                            sp[-4] = dest_ip;
                            sp[-3] = num_exc;
                            sp[-2] = MP_OBJ_NEW_SMALL_INT(UNWIND_JUMP);
602
                        }
603
                        sp -= 2; // we removed (__exit__, ctx_mgr)
604
605
                    } else {
                        assert(mp_obj_is_exception_type(TOP()));
606
                        // stack: (..., __exit__, ctx_mgr, traceback, exc_val, exc_type)
607
608
609
610
611
612
                        // Need to pass (sp[0], sp[-1], sp[-2]) as arguments so must reverse the
                        // order of these on the value stack (don't want to create a temporary
                        // array because it increases stack footprint of the VM).
                        mp_obj_t obj = sp[-2];
                        sp[-2] = sp[0];
                        sp[0] = obj;
613
                        mp_obj_t ret_value = mp_call_method_n_kw(3, 0, sp - 4);
614
                        if (mp_obj_is_true(ret_value)) {
615
616
617
618
                            // We need to silence/swallow the exception.  This is done
                            // by popping the exception and the __exit__ handler and
                            // replacing it with None, which signals END_FINALLY to just
                            // execute the finally handler normally.
619
                            sp -= 4;
620
                            SET_TOP(mp_const_none);
621
                            assert(exc_sp >= exc_stack);
622
                            POP_EXC_BLOCK();
623
                        } else {
624
625
626
627
628
629
                            // We need to re-raise the exception.  We pop __exit__ handler
                            // and copy the 3 exception values down (remembering that they
                            // are reversed due to above code).
                            sp[-4] = sp[0];
                            sp[-3] = sp[-1];
                            sp -= 2;
630
                        }
631
632
633
                    }
                    DISPATCH();
                }
634

635
                ENTRY(MP_BC_UNWIND_JUMP): {
636
                    MARK_EXC_IP_SELECTIVE();
637
                    DECODE_SLABEL;
638
                    PUSH((void*)(ip + slab)); // push destination ip for jump
639
                    PUSH((void*)(mp_uint_t)(*ip)); // push number of exception handlers to unwind (0x80 bit set if we also need to pop stack)
640
641
unwind_jump:;
                    mp_uint_t unum = (mp_uint_t)POP(); // get number of exception handlers to unwind
642
                    while ((unum & 0x7f) > 0) {
643
                        unum -= 1;
644
                        assert(exc_sp >= exc_stack);
645
                        if (MP_TAGPTR_TAG1(exc_sp->val_sp)) {
646
647
648
649
650
651
652
653
654
                            // We're going to run "finally" code as a coroutine
                            // (not calling it recursively). Set up a sentinel
                            // on a stack so it can return back to us when it is
                            // done (when END_FINALLY reached).
                            PUSH((void*)unum); // push number of exception handlers left to unwind
                            PUSH(MP_OBJ_NEW_SMALL_INT(UNWIND_JUMP)); // push sentinel
                            ip = exc_sp->handler; // get exception handler byte code address
                            exc_sp--; // pop exception handler
                            goto dispatch_loop; // run the exception handler
655
                        }
656
657
658
                        exc_sp--;
                    }
                    ip = (const byte*)POP(); // pop destination ip for jump
659
660
661
                    if (unum != 0) {
                        sp--;
                    }
662
                    DISPATCH_WITH_PEND_EXC_CHECK();
663
                }
664
665
666

                // matched against: POP_BLOCK or POP_EXCEPT (anything else?)
                ENTRY(MP_BC_SETUP_EXCEPT):
667
                ENTRY(MP_BC_SETUP_FINALLY): {
668
                    MARK_EXC_IP_SELECTIVE();
669
670
671
672
673
                    #if SELECTIVE_EXC_IP
                    PUSH_EXC_BLOCK((code_state->ip[-1] == MP_BC_SETUP_FINALLY) ? 1 : 0);
                    #else
                    PUSH_EXC_BLOCK((code_state->ip[0] == MP_BC_SETUP_FINALLY) ? 1 : 0);
                    #endif
674
                    DISPATCH();
675
                }
676
677

                ENTRY(MP_BC_END_FINALLY):
678
                    MARK_EXC_IP_SELECTIVE();
679
680
681
682
683
684
                    // not fully implemented
                    // if TOS is an exception, reraises the exception (3 values on TOS)
                    // if TOS is None, just pops it and continues
                    // if TOS is an integer, does something else
                    // else error
                    if (mp_obj_is_exception_type(TOP())) {
685
                        RAISE(sp[-1]);
686
687
                    }
                    if (TOP() == mp_const_none) {
688
                        sp--;
689
690
                    } else {
                        assert(MP_OBJ_IS_SMALL_INT(TOP()));
691
692
693
                        // We finished "finally" coroutine and now dispatch back
                        // to our caller, based on TOS value
                        mp_unwind_reason_t reason = MP_OBJ_SMALL_INT_VALUE(POP());
694
695
696
697
698
                        if (reason == UNWIND_RETURN) {
                            goto unwind_return;
                        } else {
                            assert(reason == UNWIND_JUMP);
                            goto unwind_jump;
699
700
701
702
703
                        }
                    }
                    DISPATCH();

                ENTRY(MP_BC_GET_ITER):
704
                    MARK_EXC_IP_SELECTIVE();
705
706
707
                    SET_TOP(mp_getiter(TOP()));
                    DISPATCH();

708
                ENTRY(MP_BC_FOR_ITER): {
709
                    MARK_EXC_IP_SELECTIVE();
710
                    DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward
711
                    code_state->sp = sp;
712
                    assert(TOP());
713
714
                    mp_obj_t value = mp_iternext_allow_raise(TOP());
                    if (value == MP_OBJ_STOP_ITERATION) {
715
                        --sp; // pop the exhausted iterator
716
                        ip += ulab; // jump to after for-block
717
                    } else {
718
                        PUSH(value); // push the next iteration value
719
720
                    }
                    DISPATCH();
721
                }
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749

                // matched against: SETUP_EXCEPT, SETUP_FINALLY, SETUP_WITH
                ENTRY(MP_BC_POP_BLOCK):
                    // we are exiting an exception handler, so pop the last one of the exception-stack
                    assert(exc_sp >= exc_stack);
                    POP_EXC_BLOCK();
                    DISPATCH();

                // matched against: SETUP_EXCEPT
                ENTRY(MP_BC_POP_EXCEPT):
                    // TODO need to work out how blocks work etc
                    // pops block, checks it's an exception block, and restores the stack, saving the 3 exception values to local threadstate
                    assert(exc_sp >= exc_stack);
                    assert(currently_in_except_block);
                    //sp = (mp_obj_t*)(*exc_sp--);
                    //exc_sp--; // discard ip
                    POP_EXC_BLOCK();
                    //sp -= 3; // pop 3 exception values
                    DISPATCH();

                ENTRY(MP_BC_NOT):
                    if (TOP() == mp_const_true) {
                        SET_TOP(mp_const_false);
                    } else {
                        SET_TOP(mp_const_true);
                    }
                    DISPATCH();

750
                ENTRY(MP_BC_BUILD_TUPLE): {
751
                    MARK_EXC_IP_SELECTIVE();
752
753
754
755
                    DECODE_UINT;
                    sp -= unum - 1;
                    SET_TOP(mp_obj_new_tuple(unum, sp));
                    DISPATCH();
756
                }
757

758
                ENTRY(MP_BC_BUILD_LIST): {
759
                    MARK_EXC_IP_SELECTIVE();
760
761
762
763
                    DECODE_UINT;
                    sp -= unum - 1;
                    SET_TOP(mp_obj_new_list(unum, sp));
                    DISPATCH();
764
                }
765

766
                ENTRY(MP_BC_LIST_APPEND): {
767
                    MARK_EXC_IP_SELECTIVE();
768
769
770
771
772
                    DECODE_UINT;
                    // I think it's guaranteed by the compiler that sp[unum] is a list
                    mp_obj_list_append(sp[-unum], sp[0]);
                    sp--;
                    DISPATCH();
773
                }
774

775
                ENTRY(MP_BC_BUILD_MAP): {
776
                    MARK_EXC_IP_SELECTIVE();
777
778
779
                    DECODE_UINT;
                    PUSH(mp_obj_new_dict(unum));
                    DISPATCH();
780
                }
781
782

                ENTRY(MP_BC_STORE_MAP):
783
                    MARK_EXC_IP_SELECTIVE();
784
785
786
787
                    sp -= 2;
                    mp_obj_dict_store(sp[0], sp[2], sp[1]);
                    DISPATCH();

788
                ENTRY(MP_BC_MAP_ADD): {
789
                    MARK_EXC_IP_SELECTIVE();
790
791
792
793
794
                    DECODE_UINT;
                    // I think it's guaranteed by the compiler that sp[-unum - 1] is a map
                    mp_obj_dict_store(sp[-unum - 1], sp[0], sp[-1]);
                    sp -= 2;
                    DISPATCH();
795
                }
796

797
#if MICROPY_PY_BUILTINS_SET
798
                ENTRY(MP_BC_BUILD_SET): {
799
                    MARK_EXC_IP_SELECTIVE();
800
801
802
803
                    DECODE_UINT;
                    sp -= unum - 1;
                    SET_TOP(mp_obj_new_set(unum, sp));
                    DISPATCH();
804
                }
805

806
                ENTRY(MP_BC_SET_ADD): {
807
                    MARK_EXC_IP_SELECTIVE();
808
809
810
811
812
                    DECODE_UINT;
                    // I think it's guaranteed by the compiler that sp[-unum] is a set
                    mp_obj_set_store(sp[-unum], sp[0]);
                    sp--;
                    DISPATCH();
813
                }
814
#endif
Damien's avatar
Damien committed
815

816
#if MICROPY_PY_BUILTINS_SLICE
817
                ENTRY(MP_BC_BUILD_SLICE): {
818
                    MARK_EXC_IP_SELECTIVE();
819
820
                    DECODE_UINT;
                    if (unum == 2) {
821
822
823
                        mp_obj_t stop = POP();
                        mp_obj_t start = TOP();
                        SET_TOP(mp_obj_new_slice(start, stop, mp_const_none));
824
                    } else {
825
826
827
828
                        mp_obj_t step = POP();
                        mp_obj_t stop = POP();
                        mp_obj_t start = TOP();
                        SET_TOP(mp_obj_new_slice(start, stop, step));
829
830
                    }
                    DISPATCH();
831
                }
832
#endif
833

834
                ENTRY(MP_BC_UNPACK_SEQUENCE): {
835
                    MARK_EXC_IP_SELECTIVE();
836
837
838
839
                    DECODE_UINT;
                    mp_unpack_sequence(sp[0], unum, sp);
                    sp += unum - 1;
                    DISPATCH();
840
                }
841

842
                ENTRY(MP_BC_UNPACK_EX): {
843
                    MARK_EXC_IP_SELECTIVE();
844
845
846
847
                    DECODE_UINT;
                    mp_unpack_ex(sp[0], unum, sp);
                    sp += (unum & 0xff) + ((unum >> 8) & 0xff);
                    DISPATCH();
848
                }
849

850
                ENTRY(MP_BC_MAKE_FUNCTION): {
851
                    DECODE_PTR;
852
                    PUSH(mp_make_function_from_raw_code(ptr, MP_OBJ_NULL, MP_OBJ_NULL));
853
                    DISPATCH();
854
                }
855

856
                ENTRY(MP_BC_MAKE_FUNCTION_DEFARGS): {
857
858
                    DECODE_PTR;
                    // Stack layout: def_tuple def_dict <- TOS
859
                    mp_obj_t def_dict = POP();
860
                    SET_TOP(mp_make_function_from_raw_code(ptr, TOP(), def_dict));
861
                    DISPATCH();
862
                }
863

864
                ENTRY(MP_BC_MAKE_CLOSURE): {
865
                    DECODE_PTR;
866
                    mp_uint_t n_closed_over = *ip++;
867
868
                    // Stack layout: closed_overs <- TOS
                    sp -= n_closed_over - 1;
869
                    SET_TOP(mp_make_closure_from_raw_code(ptr, n_closed_over, sp));
870
                    DISPATCH();
871
                }
872

873
                ENTRY(MP_BC_MAKE_CLOSURE_DEFARGS): {
874
                    DECODE_PTR;
875
                    mp_uint_t n_closed_over = *ip++;
876
877
                    // Stack layout: def_tuple def_dict closed_overs <- TOS
                    sp -= 2 + n_closed_over - 1;
878
                    SET_TOP(mp_make_closure_from_raw_code(ptr, 0x100 | n_closed_over, sp));
879
                    DISPATCH();
880
                }