vm.c 39.4 KB
Newer Older
Damien's avatar
Damien committed
1
#include <stdio.h>
2
#include <string.h>
Damien's avatar
Damien committed
3
4
#include <assert.h>

5
#include "nlr.h"
Damien's avatar
Damien committed
6
#include "misc.h"
7
#include "mpconfig.h"
8
#include "qstr.h"
9
#include "obj.h"
Damien's avatar
Damien committed
10
#include "runtime.h"
11
#include "bc0.h"
12
#include "bc.h"
13
#include "objgenerator.h"
Damien's avatar
Damien committed
14

15
16
#define DETECT_VM_STACK_OVERFLOW (0)

Paul Sokolovsky's avatar
Paul Sokolovsky committed
17
18
19
20
21
22
23
// 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.

24
// Exception stack unwind reasons (WHY_* in CPython-speak)
25
26
// TODO perhaps compress this to RETURN=0, JUMP>0, with number of unwinds
// left to do encoded in the JUMP number
27
28
typedef enum {
    UNWIND_RETURN = 1,
29
    UNWIND_JUMP,
30
31
} mp_unwind_reason_t;

32
33
34
35
36
37
#define DECODE_UINT { \
    unum = 0; \
    do { \
        unum = (unum << 7) + (*ip & 0x7f); \
    } while ((*ip++ & 0x80) != 0); \
}
Damien's avatar
Damien committed
38
39
#define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0)
#define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0)
40
41
42
43
44
45
#define DECODE_QSTR { \
    qst = 0; \
    do { \
        qst = (qst << 7) + (*ip & 0x7f); \
    } while ((*ip++ & 0x80) != 0); \
}
46
47
#define PUSH(val) *++sp = (val)
#define POP() (*sp--)
48
49
#define TOP() (*sp)
#define SET_TOP(val) *sp = (val)
Damien's avatar
Damien committed
50

51
#define PUSH_EXC_BLOCK() \
52
53
54
55
56
    DECODE_ULABEL; /* except labels are always forward */ \
    ++exc_sp; \
    exc_sp->opcode = op; \
    exc_sp->handler = ip + unum; \
    exc_sp->val_sp = MP_TAGPTR_MAKE(sp, currently_in_except_block); \
Damien George's avatar
Damien George committed
57
    exc_sp->prev_exc = MP_OBJ_NULL; \
58
59
    currently_in_except_block = 0; /* in a try block now */

60
61
62
63
#define POP_EXC_BLOCK() \
    currently_in_except_block = MP_TAGPTR_TAG(exc_sp->val_sp); /* restore previous state */ \
    exc_sp--; /* pop back to previous exception handler */

64
mp_vm_return_kind_t mp_execute_byte_code(const byte *code, const mp_obj_t *args, uint n_args, const mp_obj_t *args2, uint n_args2, mp_obj_t *ret) {
65
66
67
68
69
70
    const byte *ip = code;

    // get code info size, and skip line number table
    machine_uint_t code_info_size = ip[0] | (ip[1] << 8) | (ip[2] << 16) | (ip[3] << 24);
    ip += code_info_size;

71
72
73
74
    // bytecode prelude: state size and exception stack size; 16 bit uints
    machine_uint_t n_state = ip[0] | (ip[1] << 8);
    machine_uint_t n_exc_stack = ip[2] | (ip[3] << 8);
    ip += 4;
75

76
77
    // allocate state for locals and stack
    mp_obj_t temp_state[10];
78
    mp_obj_t *state = &temp_state[0];
79
80
81
82
83
84
#if DETECT_VM_STACK_OVERFLOW
    if (n_state + 1 > 10) {
        state = m_new(mp_obj_t, n_state + 1);
    }
    state[n_state - n_args - n_args2] = (void*)0xdeadbeef;
#else
85
    if (n_state > 10) {
86
        state = m_new(mp_obj_t, n_state);
87
    }
88
#endif
89
90
    mp_obj_t *sp = &state[0] - 1;

91
    // allocate state for exceptions
92
93
    mp_exc_stack_t exc_state[4];
    mp_exc_stack_t *exc_stack = &exc_state[0];
94
    if (n_exc_stack > 4) {
95
        exc_stack = m_new(mp_exc_stack_t, n_exc_stack);
96
    }
97
    mp_exc_stack_t *exc_sp = &exc_stack[0] - 1;
98

99
    // init args
100
    for (uint i = 0; i < n_args; i++) {
101
        state[n_state - 1 - i] = args[i];
102
    }
103
104
105
    for (uint i = 0; i < n_args2; i++) {
        state[n_state - 1 - n_args - i] = args2[i];
    }
106

107
108
109
110
111
    // set rest of state to MP_OBJ_NULL
    for (uint i = 0; i < n_state - n_args - n_args2; i++) {
        state[i] = MP_OBJ_NULL;
    }

112
113
114
    // bytecode prelude: initialise closed over variables
    for (uint n_local = *ip++; n_local > 0; n_local--) {
        uint local_num = *ip++;
115
        state[n_state - 1 - local_num] = mp_obj_new_cell(state[n_state - 1 - local_num]);
Damien George's avatar
Damien George committed
116
117
118
    }

    // execute the byte code
119
    mp_vm_return_kind_t vm_return_kind = mp_execute_byte_code_2(code, &ip, &state[n_state - 1], &sp, exc_stack, &exc_sp, MP_OBJ_NULL);
120

121
122
123
124
125
126
127
#if DETECT_VM_STACK_OVERFLOW
    if (state[n_state - n_args - n_args2] != (void*)0xdeadbeef) {
        printf("VM stack overflow\n");
        assert(0);
    }
#endif

128
129
130
131
132
133
134
135
136
137
138
139
    switch (vm_return_kind) {
        case MP_VM_RETURN_NORMAL:
            *ret = *sp;
            return MP_VM_RETURN_NORMAL;
        case MP_VM_RETURN_EXCEPTION:
            *ret = state[n_state - 1];
            return MP_VM_RETURN_EXCEPTION;
        case MP_VM_RETURN_YIELD: // byte-code shouldn't yield
        default:
            assert(0);
            *ret = mp_const_none;
            return MP_VM_RETURN_NORMAL;
140
141
142
    }
}

143
144
// 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
145
146
147
148
// 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]
149
150
mp_vm_return_kind_t mp_execute_byte_code_2(const byte *code_info, const byte **ip_in_out,
                                           mp_obj_t *fastn, mp_obj_t **sp_in_out,
151
                                           mp_exc_stack_t *exc_stack, mp_exc_stack_t **exc_sp_in_out,
152
                                           volatile mp_obj_t inject_exc) {
Damien's avatar
Damien committed
153
154
    // careful: be sure to declare volatile any variables read in the exception handler (written is ok, I think)

155
    const byte *ip = *ip_in_out;
156
    mp_obj_t *sp = *sp_in_out;
Damien's avatar
Damien committed
157
    machine_uint_t unum;
158
    qstr qst;
159
    mp_obj_t obj1, obj2;
160
    nlr_buf_t nlr;
Damien's avatar
Damien committed
161

162
    volatile bool currently_in_except_block = MP_TAGPTR_TAG(*exc_sp_in_out); // 0 or 1, to detect nested exceptions
163
    mp_exc_stack_t *volatile exc_sp = MP_TAGPTR_PTR(*exc_sp_in_out); // stack grows up, exc_sp points to top of stack
164
    const byte *volatile save_ip = ip; // this is so we can access ip in the exception handler without making ip volatile (which means the compiler can't keep it in a register in the main loop)
Damien's avatar
Damien committed
165

166
    // outer exception handling loop
Damien's avatar
Damien committed
167
    for (;;) {
168
outer_dispatch_loop:
169
        if (nlr_push(&nlr) == 0) {
170
171
172
            // 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.
173
174
175
            // 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) {
176
177
                mp_obj_t t = inject_exc;
                inject_exc = MP_OBJ_NULL;
178
                nlr_raise(mp_make_raise_obj(t));
179
            }
180
181
            // loop to execute byte code
            for (;;) {
182
dispatch_loop:
183
                save_ip = ip;
184
185
                int op = *ip++;
                switch (op) {
186
187
                    case MP_BC_LOAD_CONST_FALSE:
                        PUSH(mp_const_false);
188
189
                        break;

190
191
                    case MP_BC_LOAD_CONST_NONE:
                        PUSH(mp_const_none);
192
193
                        break;

194
195
                    case MP_BC_LOAD_CONST_TRUE:
                        PUSH(mp_const_true);
196
                        break;
Damien George's avatar
Damien George committed
197
198

                    case MP_BC_LOAD_CONST_ELLIPSIS:
199
                        PUSH((mp_obj_t)&mp_const_ellipsis_obj);
Damien George's avatar
Damien George committed
200
                        break;
201

202
                    case MP_BC_LOAD_CONST_SMALL_INT: {
203
                        machine_int_t num = 0;
204
205
206
207
208
209
210
211
                        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));
212
                        break;
213
                    }
214

215
216
                    case MP_BC_LOAD_CONST_INT:
                        DECODE_QSTR;
217
                        PUSH(mp_obj_new_int_from_long_str(qstr_str(qst)));
218
219
                        break;

220
                    case MP_BC_LOAD_CONST_DEC:
Damien's avatar
Damien committed
221
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
222
                        PUSH(mp_load_const_dec(qst));
Damien's avatar
Damien committed
223
224
                        break;

225
                    case MP_BC_LOAD_CONST_ID:
226
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
227
                        PUSH(mp_load_const_str(qst)); // TODO
228
229
                        break;

230
231
                    case MP_BC_LOAD_CONST_BYTES:
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
232
                        PUSH(mp_load_const_bytes(qst));
233
234
                        break;

235
                    case MP_BC_LOAD_CONST_STRING:
236
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
237
                        PUSH(mp_load_const_str(qst));
238
239
                        break;

240
241
242
243
                    case MP_BC_LOAD_NULL:
                        PUSH(MP_OBJ_NULL);
                        break;

244
                    case MP_BC_LOAD_FAST_0:
245
                        PUSH(fastn[0]);
246
247
                        break;

248
                    case MP_BC_LOAD_FAST_1:
249
                        PUSH(fastn[-1]);
250
251
                        break;

252
                    case MP_BC_LOAD_FAST_2:
253
                        PUSH(fastn[-2]);
254
255
                        break;

256
                    case MP_BC_LOAD_FAST_N:
257
                        DECODE_UINT;
258
                        PUSH(fastn[-unum]);
259
260
                        break;

261
262
263
264
265
266
267
268
269
270
                    case MP_BC_LOAD_FAST_CHECKED:
                        DECODE_UINT;
                        obj1 = fastn[-unum];
                        if (obj1 == MP_OBJ_NULL) {
                            local_name_error:
                            nlr_raise(mp_obj_new_exception_msg(&mp_type_NameError, "local variable referenced before assignment"));
                        }
                        PUSH(obj1);
                        break;

271
                    case MP_BC_LOAD_DEREF:
Damien's avatar
Damien committed
272
                        DECODE_UINT;
273
274
275
276
277
                        obj1 = mp_obj_cell_get(fastn[-unum]);
                        if (obj1 == MP_OBJ_NULL) {
                            goto local_name_error;
                        }
                        PUSH(obj1);
Damien's avatar
Damien committed
278
279
                        break;

280
                    case MP_BC_LOAD_NAME:
281
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
282
                        PUSH(mp_load_name(qst));
283
284
                        break;

285
                    case MP_BC_LOAD_GLOBAL:
286
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
287
                        PUSH(mp_load_global(qst));
288
289
                        break;

290
                    case MP_BC_LOAD_ATTR:
291
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
292
                        SET_TOP(mp_load_attr(TOP(), qst));
293
294
                        break;

295
                    case MP_BC_LOAD_METHOD:
296
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
297
                        mp_load_method(*sp, qst, sp);
298
                        sp += 1;
299
300
                        break;

301
                    case MP_BC_LOAD_BUILD_CLASS:
Damien George's avatar
Damien George committed
302
                        PUSH(mp_load_build_class());
303
304
                        break;

305
                    case MP_BC_STORE_FAST_0:
306
                        fastn[0] = POP();
307
308
                        break;

309
                    case MP_BC_STORE_FAST_1:
310
                        fastn[-1] = POP();
311
312
                        break;

313
                    case MP_BC_STORE_FAST_2:
314
                        fastn[-2] = POP();
315
316
                        break;

317
                    case MP_BC_STORE_FAST_N:
318
                        DECODE_UINT;
319
                        fastn[-unum] = POP();
320
321
                        break;

322
                    case MP_BC_STORE_DEREF:
Damien's avatar
Damien committed
323
                        DECODE_UINT;
324
                        mp_obj_cell_set(fastn[-unum], POP());
Damien's avatar
Damien committed
325
326
                        break;

327
                    case MP_BC_STORE_NAME:
328
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
329
                        mp_store_name(qst, POP());
330
331
                        break;

332
                    case MP_BC_STORE_GLOBAL:
333
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
334
                        mp_store_global(qst, POP());
335
336
                        break;

337
                    case MP_BC_STORE_ATTR:
338
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
339
                        mp_store_attr(sp[0], qst, sp[-1]);
340
                        sp -= 2;
341
342
                        break;

343
                    case MP_BC_STORE_SUBSCR:
Damien George's avatar
Damien George committed
344
                        mp_store_subscr(sp[-1], sp[0], sp[-2]);
345
                        sp -= 3;
346
347
                        break;

348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
                    case MP_BC_DELETE_FAST:
                        DECODE_UINT;
                        if (fastn[-unum] == MP_OBJ_NULL) {
                            goto local_name_error;
                        }
                        fastn[-unum] = MP_OBJ_NULL;
                        break;

                    case MP_BC_DELETE_DEREF:
                        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);
                        break;

364
365
                    case MP_BC_DELETE_NAME:
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
366
                        mp_delete_name(qst);
367
368
                        break;

369
370
371
372
373
                    case MP_BC_DELETE_GLOBAL:
                        DECODE_QSTR;
                        mp_delete_global(qst);
                        break;

374
                    case MP_BC_DUP_TOP:
375
                        obj1 = TOP();
376
377
378
                        PUSH(obj1);
                        break;

379
                    case MP_BC_DUP_TOP_TWO:
380
381
382
                        sp += 2;
                        sp[0] = sp[-2];
                        sp[-1] = sp[-3];
383
384
                        break;

385
                    case MP_BC_POP_TOP:
386
                        sp -= 1;
387
388
                        break;

389
                    case MP_BC_ROT_TWO:
390
                        obj1 = sp[0];
391
392
                        sp[0] = sp[-1];
                        sp[-1] = obj1;
393
394
                        break;

395
                    case MP_BC_ROT_THREE:
396
                        obj1 = sp[0];
397
398
399
                        sp[0] = sp[-1];
                        sp[-1] = sp[-2];
                        sp[-2] = obj1;
400
401
                        break;

402
                    case MP_BC_JUMP:
Damien's avatar
Damien committed
403
404
                        DECODE_SLABEL;
                        ip += unum;
405
406
                        break;

407
                    case MP_BC_POP_JUMP_IF_TRUE:
Damien's avatar
Damien committed
408
                        DECODE_SLABEL;
Damien George's avatar
Damien George committed
409
                        if (mp_obj_is_true(POP())) {
Damien's avatar
Damien committed
410
                            ip += unum;
411
412
413
                        }
                        break;

414
                    case MP_BC_POP_JUMP_IF_FALSE:
Damien's avatar
Damien committed
415
                        DECODE_SLABEL;
Damien George's avatar
Damien George committed
416
                        if (!mp_obj_is_true(POP())) {
Damien's avatar
Damien committed
417
                            ip += unum;
418
419
420
                        }
                        break;

421
                    case MP_BC_JUMP_IF_TRUE_OR_POP:
Damien's avatar
Damien committed
422
                        DECODE_SLABEL;
Damien George's avatar
Damien George committed
423
                        if (mp_obj_is_true(TOP())) {
Damien's avatar
Damien committed
424
425
                            ip += unum;
                        } else {
426
                            sp--;
Damien's avatar
Damien committed
427
428
429
                        }
                        break;

430
                    case MP_BC_JUMP_IF_FALSE_OR_POP:
Damien's avatar
Damien committed
431
                        DECODE_SLABEL;
Damien George's avatar
Damien George committed
432
                        if (mp_obj_is_true(TOP())) {
433
                            sp--;
Damien's avatar
Damien committed
434
435
436
437
438
                        } else {
                            ip += unum;
                        }
                        break;

439
                        /* we are trying to get away without using this opcode
440
                    case MP_BC_SETUP_LOOP:
441
                        DECODE_UINT;
442
                        // push_block(MP_BC_SETUP_LOOP, ip + unum, sp)
443
444
445
                        break;
                        */

446
                    case MP_BC_SETUP_WITH:
447
                        obj1 = TOP();
Damien George's avatar
Damien George committed
448
449
450
                        SET_TOP(mp_load_attr(obj1, MP_QSTR___exit__));
                        mp_load_method(obj1, MP_QSTR___enter__, sp + 1);
                        obj2 = mp_call_method_n_kw(0, 0, sp + 1);
451
                        PUSH_EXC_BLOCK();
452
453
454
455
                        PUSH(obj2);
                        break;

                    case MP_BC_WITH_CLEANUP: {
456
457
458
459
                        // Arriving here, there's "exception control block" on top of stack,
                        // and __exit__ bound method underneath it. Bytecode calls __exit__,
                        // and "deletes" it off stack, shifting "exception control block"
                        // to its place.
460
461
462
463
464
                        static const mp_obj_t no_exc[] = {mp_const_none, mp_const_none, mp_const_none};
                        if (TOP() == mp_const_none) {
                            sp--;
                            obj1 = TOP();
                            SET_TOP(mp_const_none);
Damien George's avatar
Damien George committed
465
                            obj2 = mp_call_function_n_kw(obj1, 3, 0, no_exc);
466
467
468
469
470
                        } else if (MP_OBJ_IS_SMALL_INT(TOP())) {
                            mp_obj_t cause = POP();
                            switch (MP_OBJ_SMALL_INT_VALUE(cause)) {
                                case UNWIND_RETURN: {
                                    mp_obj_t retval = POP();
Damien George's avatar
Damien George committed
471
                                    obj2 = mp_call_function_n_kw(TOP(), 3, 0, no_exc);
472
473
474
475
476
                                    SET_TOP(retval);
                                    PUSH(cause);
                                    break;
                                }
                                case UNWIND_JUMP: {
Damien George's avatar
Damien George committed
477
                                    obj2 = mp_call_function_n_kw(sp[-2], 3, 0, no_exc);
478
479
480
481
482
483
484
485
486
487
488
                                    // Pop __exit__ boundmethod at sp[-2]
                                    sp[-2] = sp[-1];
                                    sp[-1] = sp[0];
                                    SET_TOP(cause);
                                    break;
                                }
                                default:
                                    assert(0);
                            }
                        } else if (mp_obj_is_exception_type(TOP())) {
                            mp_obj_t args[3] = {sp[0], sp[-1], sp[-2]};
Damien George's avatar
Damien George committed
489
                            obj2 = mp_call_function_n_kw(sp[-3], 3, 0, args);
490
491
492
493
494
495
                            // Pop __exit__ boundmethod at sp[-3]
                            // TODO: Once semantics is proven, optimize for case when obj2 == True
                            sp[-3] = sp[-2];
                            sp[-2] = sp[-1];
                            sp[-1] = sp[0];
                            sp--;
Damien George's avatar
Damien George committed
496
                            if (mp_obj_is_true(obj2)) {
497
498
499
500
                                // This is what CPython does
                                //PUSH(MP_OBJ_NEW_SMALL_INT(UNWIND_SILENCED));
                                // But what we need to do is - pop exception from value stack...
                                sp -= 3;
501
502
                                // ... pop "with" exception handler, and signal END_FINALLY
                                // to just execute finally handler normally (by pushing None
503
504
505
                                // on value stack)
                                assert(exc_sp >= exc_stack);
                                assert(exc_sp->opcode == MP_BC_SETUP_WITH);
506
                                POP_EXC_BLOCK();
507
508
509
510
511
512
513
514
                                PUSH(mp_const_none);
                            }
                        } else {
                            assert(0);
                        }
                        break;
                    }

515
516
517
518
519
520
521
522
523
                    case MP_BC_UNWIND_JUMP:
                        DECODE_SLABEL;
                        PUSH((void*)(ip + unum)); // push destination ip for jump
                        PUSH((void*)(machine_uint_t)(*ip)); // push number of exception handlers to unwind
unwind_jump:
                        unum = (machine_uint_t)POP(); // get number of exception handlers to unwind
                        while (unum > 0) {
                            unum -= 1;
                            assert(exc_sp >= exc_stack);
524
                            if (exc_sp->opcode == MP_BC_SETUP_FINALLY || exc_sp->opcode == MP_BC_SETUP_WITH) {
525
526
527
528
529
530
531
532
533
534
535
536
537
                                // 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
                            }
                            exc_sp--;
                        }
                        ip = (const byte*)POP(); // pop destination ip for jump
538
539
                        break;

Damien's avatar
Damien committed
540
                    // matched against: POP_BLOCK or POP_EXCEPT (anything else?)
541
                    case MP_BC_SETUP_EXCEPT:
542
                    case MP_BC_SETUP_FINALLY:
543
                        PUSH_EXC_BLOCK();
544
545
                        break;

546
                    case MP_BC_END_FINALLY:
547
                        // not fully implemented
548
549
                        // if TOS is an exception, reraises the exception (3 values on TOS)
                        // if TOS is None, just pops it and continues
550
                        // if TOS is an integer, does something else
551
                        // else error
552
                        if (mp_obj_is_exception_type(TOP())) {
553
                            nlr_raise(sp[-1]);
554
555
556
                        }
                        if (TOP() == mp_const_none) {
                            sp--;
557
558
559
560
561
562
563
                        } else if (MP_OBJ_IS_SMALL_INT(TOP())) {
                            // 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());
                            switch (reason) {
                                case UNWIND_RETURN:
                                    goto unwind_return;
564
565
                                case UNWIND_JUMP:
                                    goto unwind_jump;
566
567
                            }
                            assert(0);
568
569
570
                        } else {
                            assert(0);
                        }
571
572
                        break;

573
                    case MP_BC_GET_ITER:
Damien George's avatar
Damien George committed
574
                        SET_TOP(mp_getiter(TOP()));
575
576
                        break;

577
                    case MP_BC_FOR_ITER:
Damien's avatar
Damien committed
578
                        DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward
Damien George's avatar
Damien George committed
579
                        obj1 = mp_iternext_allow_raise(TOP());
580
                        if (obj1 == MP_OBJ_NULL) {
581
                            --sp; // pop the exhausted iterator
Damien's avatar
Damien committed
582
                            ip += unum; // jump to after for-block
583
584
585
586
587
                        } else {
                            PUSH(obj1); // push the next iteration value
                        }
                        break;

Damien's avatar
Damien committed
588
                    // matched against: SETUP_EXCEPT, SETUP_FINALLY, SETUP_WITH
589
                    case MP_BC_POP_BLOCK:
Damien's avatar
Damien committed
590
                        // we are exiting an exception handler, so pop the last one of the exception-stack
591
                        assert(exc_sp >= exc_stack);
592
                        POP_EXC_BLOCK();
593
594
                        break;

595
                    // matched against: SETUP_EXCEPT
596
                    case MP_BC_POP_EXCEPT:
Damien's avatar
Damien committed
597
                        // TODO need to work out how blocks work etc
598
                        // pops block, checks it's an exception block, and restores the stack, saving the 3 exception values to local threadstate
599
                        assert(exc_sp >= exc_stack);
600
                        assert(currently_in_except_block);
601
                        //sp = (mp_obj_t*)(*exc_sp--);
Damien's avatar
Damien committed
602
                        //exc_sp--; // discard ip
603
                        POP_EXC_BLOCK();
604
                        //sp -= 3; // pop 3 exception values
605
606
                        break;

607
608
609
610
611
612
613
614
                    case MP_BC_NOT:
                        if (TOP() == mp_const_true) {
                            SET_TOP(mp_const_false);
                        } else {
                            SET_TOP(mp_const_true);
                        }
                        break;

615
                    case MP_BC_UNARY_OP:
Damien's avatar
Damien committed
616
                        unum = *ip++;
Damien George's avatar
Damien George committed
617
                        SET_TOP(mp_unary_op(unum, TOP()));
Damien's avatar
Damien committed
618
619
                        break;

620
                    case MP_BC_BINARY_OP:
621
622
                        unum = *ip++;
                        obj2 = POP();
623
                        obj1 = TOP();
Damien George's avatar
Damien George committed
624
                        SET_TOP(mp_binary_op(unum, obj1, obj2));
625
626
                        break;

627
                    case MP_BC_BUILD_TUPLE:
628
                        DECODE_UINT;
629
                        sp -= unum - 1;
630
                        SET_TOP(mp_obj_new_tuple(unum, sp));
631
632
                        break;

633
                    case MP_BC_BUILD_LIST:
634
                        DECODE_UINT;
635
                        sp -= unum - 1;
636
                        SET_TOP(mp_obj_new_list(unum, sp));
637
638
                        break;

639
                    case MP_BC_LIST_APPEND:
640
641
                        DECODE_UINT;
                        // I think it's guaranteed by the compiler that sp[unum] is a list
642
                        mp_obj_list_append(sp[-unum], sp[0]);
643
                        sp--;
644
645
                        break;

646
                    case MP_BC_BUILD_MAP:
647
                        DECODE_UINT;
648
                        PUSH(mp_obj_new_dict(unum));
649
650
                        break;

651
                    case MP_BC_STORE_MAP:
652
                        sp -= 2;
653
                        mp_obj_dict_store(sp[0], sp[2], sp[1]);
654
655
                        break;

656
                    case MP_BC_MAP_ADD:
Damien's avatar
Damien committed
657
                        DECODE_UINT;
658
                        // I think it's guaranteed by the compiler that sp[-unum - 1] is a map
659
                        mp_obj_dict_store(sp[-unum - 1], sp[0], sp[-1]);
660
                        sp -= 2;
Damien's avatar
Damien committed
661
662
                        break;

663
                    case MP_BC_BUILD_SET:
664
                        DECODE_UINT;
665
                        sp -= unum - 1;
666
                        SET_TOP(mp_obj_new_set(unum, sp));
667
668
                        break;

669
                    case MP_BC_SET_ADD:
Damien's avatar
Damien committed
670
                        DECODE_UINT;
671
                        // I think it's guaranteed by the compiler that sp[-unum] is a set
672
                        mp_obj_set_store(sp[-unum], sp[0]);
673
                        sp--;
Damien's avatar
Damien committed
674
675
                        break;

676
#if MICROPY_ENABLE_SLICE
677
678
679
680
681
682
683
                    case MP_BC_BUILD_SLICE:
                        DECODE_UINT;
                        if (unum == 2) {
                            obj2 = POP();
                            obj1 = TOP();
                            SET_TOP(mp_obj_new_slice(obj1, obj2, NULL));
                        } else {
684
685
686
687
                            obj1 = mp_obj_new_exception_msg(&mp_type_NotImplementedError, "3-argument slice is not supported");
                            nlr_pop();
                            fastn[0] = obj1;
                            return MP_VM_RETURN_EXCEPTION;
688
689
                        }
                        break;
690
#endif
691

692
                    case MP_BC_UNPACK_SEQUENCE:
693
                        DECODE_UINT;
Damien George's avatar
Damien George committed
694
                        mp_unpack_sequence(sp[0], unum, sp);
695
                        sp += unum - 1;
696
697
                        break;

698
699
700
701
702
703
                    case MP_BC_UNPACK_EX:
                        DECODE_UINT;
                        mp_unpack_ex(sp[0], unum, sp);
                        sp += (unum & 0xff) + ((unum >> 8) & 0xff);
                        break;

704
                    case MP_BC_MAKE_FUNCTION:
705
                        DECODE_UINT;
706
                        PUSH(mp_make_function_from_id(unum, MP_OBJ_NULL, MP_OBJ_NULL));
707
708
709
710
                        break;

                    case MP_BC_MAKE_FUNCTION_DEFARGS:
                        DECODE_UINT;
711
712
                        // Stack layout: def_dict def_tuple <- TOS
                        obj1 = POP();
713
                        SET_TOP(mp_make_function_from_id(unum, obj1, TOP()));
714
715
                        break;

716
                    case MP_BC_MAKE_CLOSURE:
Damien's avatar
Damien committed
717
                        DECODE_UINT;
718
719
                        // Stack layout: closure_tuple <- TOS
                        SET_TOP(mp_make_closure_from_id(unum, TOP(), MP_OBJ_NULL, MP_OBJ_NULL));
720
721
722
723
                        break;

                    case MP_BC_MAKE_CLOSURE_DEFARGS:
                        DECODE_UINT;
724
                        // Stack layout: def_dict def_tuple closure_tuple <- TOS
725
                        obj1 = POP();
726
727
                        obj2 = POP();
                        SET_TOP(mp_make_closure_from_id(unum, obj1, obj2, TOP()));
Damien's avatar
Damien committed
728
729
                        break;

730
                    case MP_BC_CALL_FUNCTION:
731
                        DECODE_UINT;
732
733
734
                        // unum & 0xff == n_positional
                        // (unum >> 8) & 0xff == n_keyword
                        sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe);
Damien George's avatar
Damien George committed
735
                        SET_TOP(mp_call_function_n_kw(*sp, unum & 0xff, (unum >> 8) & 0xff, sp + 1));
736
737
                        break;

738
739
740
741
742
743
                    case MP_BC_CALL_FUNCTION_VAR_KW:
                        DECODE_UINT;
                        // unum & 0xff == n_positional
                        // (unum >> 8) & 0xff == n_keyword
                        // We have folowing stack layout here:
                        // fun arg0 arg1 ... kw0 val0 kw1 val1 ... seq dict <- TOS
744
745
                        sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 2;
                        SET_TOP(mp_call_method_n_kw_var(false, unum, sp));
746
747
                        break;

748
                    case MP_BC_CALL_METHOD:
749
                        DECODE_UINT;
750
751
752
                        // unum & 0xff == n_positional
                        // (unum >> 8) & 0xff == n_keyword
                        sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 1;
Damien George's avatar
Damien George committed
753
                        SET_TOP(mp_call_method_n_kw(unum & 0xff, (unum >> 8) & 0xff, sp));
754
                        break;
755
756
757
758
759
760
761

                    case MP_BC_CALL_METHOD_VAR_KW:
                        DECODE_UINT;
                        // unum & 0xff == n_positional
                        // (unum >> 8) & 0xff == n_keyword
                        // We have folowing stack layout here:
                        // fun self arg0 arg1 ... kw0 val0 kw1 val1 ... seq dict <- TOS
762
763
                        sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 3;
                        SET_TOP(mp_call_method_n_kw_var(true, unum, sp));
764
                        break;
765

766
                    case MP_BC_RETURN_VALUE:
767
768
unwind_return:
                        while (exc_sp >= exc_stack) {
769
                            if (exc_sp->opcode == MP_BC_SETUP_FINALLY || exc_sp->opcode == MP_BC_SETUP_WITH) {
770
771
772
773
774
775
776
777
778
779
780
781
782
783
                                // 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(MP_OBJ_NEW_SMALL_INT(UNWIND_RETURN));
                                ip = exc_sp->handler;
                                // We don't need to do anything with sp, finally is just
                                // syntactic sugar for sequential execution??
                                // sp =
                                exc_sp--;
                                goto dispatch_loop;
                            }
                            exc_sp--;
                        }
784
                        nlr_pop();
785
                        *sp_in_out = sp;
786
                        assert(exc_sp == exc_stack - 1);
787
                        return MP_VM_RETURN_NORMAL;
788

789
790
                    case MP_BC_RAISE_VARARGS:
                        unum = *ip++;
791
792
                        assert(unum <= 1);
                        if (unum == 0) {
Damien George's avatar
Damien George committed
793
794
                            // search for the inner-most previous exception, to reraise it
                            obj1 = MP_OBJ_NULL;
795
                            for (mp_exc_stack_t *e = exc_sp; e >= exc_stack; e--) {
Damien George's avatar
Damien George committed
796
797
798
799
800
801
                                if (e->prev_exc != MP_OBJ_NULL) {
                                    obj1 = e->prev_exc;
                                    break;
                                }
                            }
                            if (obj1 == MP_OBJ_NULL) {
802
                                nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "No active exception to reraise"));
803
                            }
804
805
806
                        } else {
                            obj1 = POP();
                        }
807
                        nlr_raise(mp_make_raise_obj(obj1));
808

809
                    case MP_BC_YIELD_VALUE:
810
yield:
811
812
813
                        nlr_pop();
                        *ip_in_out = ip;
                        *sp_in_out = sp;
814
                        *exc_sp_in_out = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block);
815
                        return MP_VM_RETURN_YIELD;
816

817
                    case MP_BC_YIELD_FROM: {
818
819
//#define EXC_MATCH(exc, type) MP_OBJ_IS_TYPE(exc, type)
#define EXC_MATCH(exc, type) mp_obj_exception_match(exc, type)
820
#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, &mp_type_GeneratorExit)) { nlr_raise(t); }
821
822
                        mp_vm_return_kind_t ret_kind;
                        obj1 = POP();
823
                        mp_obj_t t_exc = MP_OBJ_NULL;
824
                        if (inject_exc != MP_OBJ_NULL) {
825
                            t_exc = inject_exc;
826
                            inject_exc = MP_OBJ_NULL;
827
                            ret_kind = mp_resume(TOP(), MP_OBJ_NULL, t_exc, &obj2);
828
                        } else {
829
                            ret_kind = mp_resume(TOP(), obj1, MP_OBJ_NULL, &obj2);
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
                        }

                        if (ret_kind == MP_VM_RETURN_YIELD) {
                            ip--;
                            PUSH(obj2);
                            goto yield;
                        }
                        if (ret_kind == MP_VM_RETURN_NORMAL) {
                            // Pop exhausted gen
                            sp--;
                            if (obj2 == MP_OBJ_NULL) {
                                // Optimize StopIteration
                                // TODO: get StopIteration's value
                                PUSH(mp_const_none);
                            } else {
                                PUSH(obj2);
                            }

848
849
850
                            // If we injected GeneratorExit downstream, then even
                            // if it was swallowed, we re-raise GeneratorExit
                            GENERATOR_EXIT_IF_NEEDED(t_exc);
851
852
853
854
855
856
                            break;
                        }
                        if (ret_kind == MP_VM_RETURN_EXCEPTION) {
                            // Pop exhausted gen
                            sp--;
                            if (EXC_MATCH(obj2, &mp_type_StopIteration)) {
857
858
859
860
                                PUSH(mp_obj_exception_get_value(obj2));
                                // If we injected GeneratorExit downstream, then even
                                // if it was swallowed, we re-raise GeneratorExit
                                GENERATOR_EXIT_IF_NEEDED(t_exc);