vm.c 37.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"
14
#include "objtuple.h"
Damien's avatar
Damien committed
15

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

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

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

50
#define PUSH_EXC_BLOCK() \
51
52
53
54
55
    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
56
    exc_sp->prev_exc = MP_OBJ_NULL; \
57
58
    currently_in_except_block = 0; /* in a try block now */

59
60
61
62
#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 */

63
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) {
64
65
66
67
68
69
    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;

70
71
72
73
    // 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;
74

75
76
    // allocate state for locals and stack
    mp_obj_t temp_state[10];
77
    mp_obj_t *state = &temp_state[0];
78
    if (n_state > 10) {
79
        state = m_new(mp_obj_t, n_state);
80
    }
81
82
    mp_obj_t *sp = &state[0] - 1;

83
    // allocate state for exceptions
84
85
    mp_exc_stack_t exc_state[4];
    mp_exc_stack_t *exc_stack = &exc_state[0];
86
    if (n_exc_stack > 4) {
87
        exc_stack = m_new(mp_exc_stack_t, n_exc_stack);
88
    }
89
    mp_exc_stack_t *exc_sp = &exc_stack[0] - 1;
90

91
    // init args
92
    for (uint i = 0; i < n_args; i++) {
93
        state[n_state - 1 - i] = args[i];
94
    }
95
96
97
    for (uint i = 0; i < n_args2; i++) {
        state[n_state - 1 - n_args - i] = args2[i];
    }
98

99
100
101
102
103
104
105
    // bytecode prelude: initialise closed over variables
    for (uint n_local = *ip++; n_local > 0; n_local--) {
        uint local_num = *ip++;
        if (local_num < n_args + n_args2) {
            state[n_state - 1 - local_num] = mp_obj_new_cell(state[n_state - 1 - local_num]);
        } else {
            state[n_state - 1 - local_num] = mp_obj_new_cell(MP_OBJ_NULL);
Damien George's avatar
Damien George committed
106
107
108
109
        }
    }

    // execute the byte code
110
    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);
111
112
113
114
115
116
117
118
119
120
121
122
123

    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;
124
125
126
    }
}

127
128
// 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
129
130
131
132
// 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]
133
134
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,
135
                                           mp_exc_stack_t *exc_stack, mp_exc_stack_t **exc_sp_in_out,
136
                                           volatile mp_obj_t inject_exc) {
Damien's avatar
Damien committed
137
138
    // careful: be sure to declare volatile any variables read in the exception handler (written is ok, I think)

139
    const byte *ip = *ip_in_out;
140
    mp_obj_t *sp = *sp_in_out;
Damien's avatar
Damien committed
141
    machine_uint_t unum;
142
    qstr qst;
143
    mp_obj_t obj1, obj2;
144
    nlr_buf_t nlr;
Damien's avatar
Damien committed
145

146
    volatile bool currently_in_except_block = MP_TAGPTR_TAG(*exc_sp_in_out); // 0 or 1, to detect nested exceptions
147
    mp_exc_stack_t *volatile exc_sp = MP_TAGPTR_PTR(*exc_sp_in_out); // stack grows up, exc_sp points to top of stack
148
    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
149

150
    // outer exception handling loop
Damien's avatar
Damien committed
151
    for (;;) {
152
outer_dispatch_loop:
153
        if (nlr_push(&nlr) == 0) {
154
155
156
            // 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.
157
158
159
            // 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) {
160
161
                mp_obj_t t = inject_exc;
                inject_exc = MP_OBJ_NULL;
Damien George's avatar
Damien George committed
162
                nlr_jump(mp_make_raise_obj(t));
163
            }
164
165
            // loop to execute byte code
            for (;;) {
166
dispatch_loop:
167
                save_ip = ip;
168
169
                int op = *ip++;
                switch (op) {
170
171
                    case MP_BC_LOAD_CONST_FALSE:
                        PUSH(mp_const_false);
172
173
                        break;

174
175
                    case MP_BC_LOAD_CONST_NONE:
                        PUSH(mp_const_none);
176
177
                        break;

178
179
                    case MP_BC_LOAD_CONST_TRUE:
                        PUSH(mp_const_true);
180
                        break;
Damien George's avatar
Damien George committed
181
182

                    case MP_BC_LOAD_CONST_ELLIPSIS:
183
                        PUSH((mp_obj_t)&mp_const_ellipsis_obj);
Damien George's avatar
Damien George committed
184
                        break;
185

186
                    case MP_BC_LOAD_CONST_SMALL_INT: {
187
                        machine_int_t num = 0;
188
189
190
191
192
193
194
195
                        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));
196
                        break;
197
                    }
198

199
200
                    case MP_BC_LOAD_CONST_INT:
                        DECODE_QSTR;
201
                        PUSH(mp_obj_new_int_from_long_str(qstr_str(qst)));
202
203
                        break;

204
                    case MP_BC_LOAD_CONST_DEC:
Damien's avatar
Damien committed
205
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
206
                        PUSH(mp_load_const_dec(qst));
Damien's avatar
Damien committed
207
208
                        break;

209
                    case MP_BC_LOAD_CONST_ID:
210
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
211
                        PUSH(mp_load_const_str(qst)); // TODO
212
213
                        break;

214
215
                    case MP_BC_LOAD_CONST_BYTES:
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
216
                        PUSH(mp_load_const_bytes(qst));
217
218
                        break;

219
                    case MP_BC_LOAD_CONST_STRING:
220
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
221
                        PUSH(mp_load_const_str(qst));
222
223
                        break;

224
                    case MP_BC_LOAD_FAST_0:
225
                        PUSH(fastn[0]);
226
227
                        break;

228
                    case MP_BC_LOAD_FAST_1:
229
                        PUSH(fastn[-1]);
230
231
                        break;

232
                    case MP_BC_LOAD_FAST_2:
233
                        PUSH(fastn[-2]);
234
235
                        break;

236
                    case MP_BC_LOAD_FAST_N:
237
                        DECODE_UINT;
238
                        PUSH(fastn[-unum]);
239
240
                        break;

241
                    case MP_BC_LOAD_DEREF:
Damien's avatar
Damien committed
242
                        DECODE_UINT;
Damien George's avatar
Damien George committed
243
                        PUSH(mp_get_cell(fastn[-unum]));
Damien's avatar
Damien committed
244
245
                        break;

246
                    case MP_BC_LOAD_NAME:
247
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
248
                        PUSH(mp_load_name(qst));
249
250
                        break;

251
                    case MP_BC_LOAD_GLOBAL:
252
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
253
                        PUSH(mp_load_global(qst));
254
255
                        break;

256
                    case MP_BC_LOAD_ATTR:
257
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
258
                        SET_TOP(mp_load_attr(TOP(), qst));
259
260
                        break;

261
                    case MP_BC_LOAD_METHOD:
262
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
263
                        mp_load_method(*sp, qst, sp);
264
                        sp += 1;
265
266
                        break;

267
                    case MP_BC_LOAD_BUILD_CLASS:
Damien George's avatar
Damien George committed
268
                        PUSH(mp_load_build_class());
269
270
                        break;

271
                    case MP_BC_STORE_FAST_0:
272
                        fastn[0] = POP();
273
274
                        break;

275
                    case MP_BC_STORE_FAST_1:
276
                        fastn[-1] = POP();
277
278
                        break;

279
                    case MP_BC_STORE_FAST_2:
280
                        fastn[-2] = POP();
281
282
                        break;

283
                    case MP_BC_STORE_FAST_N:
284
                        DECODE_UINT;
285
                        fastn[-unum] = POP();
286
287
                        break;

288
                    case MP_BC_STORE_DEREF:
Damien's avatar
Damien committed
289
                        DECODE_UINT;
Damien George's avatar
Damien George committed
290
                        mp_set_cell(fastn[-unum], POP());
Damien's avatar
Damien committed
291
292
                        break;

293
                    case MP_BC_STORE_NAME:
294
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
295
                        mp_store_name(qst, POP());
296
297
                        break;

298
                    case MP_BC_STORE_GLOBAL:
299
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
300
                        mp_store_global(qst, POP());
301
302
                        break;

303
                    case MP_BC_STORE_ATTR:
304
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
305
                        mp_store_attr(sp[0], qst, sp[-1]);
306
                        sp -= 2;
307
308
                        break;

309
                    case MP_BC_STORE_SUBSCR:
Damien George's avatar
Damien George committed
310
                        mp_store_subscr(sp[-1], sp[0], sp[-2]);
311
                        sp -= 3;
312
313
                        break;

314
315
316
317
318
                    case MP_BC_DELETE_FAST_N:
                        DECODE_UINT;
                        fastn[-unum] = MP_OBJ_NULL;
                        break;

319
320
                    case MP_BC_DELETE_NAME:
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
321
                        mp_delete_name(qst);
322
323
                        break;

324
                    case MP_BC_DUP_TOP:
325
                        obj1 = TOP();
326
327
328
                        PUSH(obj1);
                        break;

329
                    case MP_BC_DUP_TOP_TWO:
330
331
332
                        sp += 2;
                        sp[0] = sp[-2];
                        sp[-1] = sp[-3];
333
334
                        break;

335
                    case MP_BC_POP_TOP:
336
                        sp -= 1;
337
338
                        break;

339
                    case MP_BC_ROT_TWO:
340
                        obj1 = sp[0];
341
342
                        sp[0] = sp[-1];
                        sp[-1] = obj1;
343
344
                        break;

345
                    case MP_BC_ROT_THREE:
346
                        obj1 = sp[0];
347
348
349
                        sp[0] = sp[-1];
                        sp[-1] = sp[-2];
                        sp[-2] = obj1;
350
351
                        break;

352
                    case MP_BC_JUMP:
Damien's avatar
Damien committed
353
354
                        DECODE_SLABEL;
                        ip += unum;
355
356
                        break;

357
                    case MP_BC_POP_JUMP_IF_TRUE:
Damien's avatar
Damien committed
358
                        DECODE_SLABEL;
Damien George's avatar
Damien George committed
359
                        if (mp_obj_is_true(POP())) {
Damien's avatar
Damien committed
360
                            ip += unum;
361
362
363
                        }
                        break;

364
                    case MP_BC_POP_JUMP_IF_FALSE:
Damien's avatar
Damien committed
365
                        DECODE_SLABEL;
Damien George's avatar
Damien George committed
366
                        if (!mp_obj_is_true(POP())) {
Damien's avatar
Damien committed
367
                            ip += unum;
368
369
370
                        }
                        break;

371
                    case MP_BC_JUMP_IF_TRUE_OR_POP:
Damien's avatar
Damien committed
372
                        DECODE_SLABEL;
Damien George's avatar
Damien George committed
373
                        if (mp_obj_is_true(TOP())) {
Damien's avatar
Damien committed
374
375
                            ip += unum;
                        } else {
376
                            sp--;
Damien's avatar
Damien committed
377
378
379
                        }
                        break;

380
                    case MP_BC_JUMP_IF_FALSE_OR_POP:
Damien's avatar
Damien committed
381
                        DECODE_SLABEL;
Damien George's avatar
Damien George committed
382
                        if (mp_obj_is_true(TOP())) {
383
                            sp--;
Damien's avatar
Damien committed
384
385
386
387
388
                        } else {
                            ip += unum;
                        }
                        break;

389
                        /* we are trying to get away without using this opcode
390
                    case MP_BC_SETUP_LOOP:
391
                        DECODE_UINT;
392
                        // push_block(MP_BC_SETUP_LOOP, ip + unum, sp)
393
394
395
                        break;
                        */

396
                    case MP_BC_SETUP_WITH:
397
                        obj1 = TOP();
Damien George's avatar
Damien George committed
398
399
400
                        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);
401
                        PUSH_EXC_BLOCK();
402
403
404
405
                        PUSH(obj2);
                        break;

                    case MP_BC_WITH_CLEANUP: {
406
407
408
409
                        // 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.
410
411
412
413
414
                        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
415
                            obj2 = mp_call_function_n_kw(obj1, 3, 0, no_exc);
416
417
418
419
420
                        } 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
421
                                    obj2 = mp_call_function_n_kw(TOP(), 3, 0, no_exc);
422
423
424
425
426
                                    SET_TOP(retval);
                                    PUSH(cause);
                                    break;
                                }
                                case UNWIND_JUMP: {
Damien George's avatar
Damien George committed
427
                                    obj2 = mp_call_function_n_kw(sp[-2], 3, 0, no_exc);
428
429
430
431
432
433
434
435
436
437
438
                                    // 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
439
                            obj2 = mp_call_function_n_kw(sp[-3], 3, 0, args);
440
441
442
443
444
445
                            // 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
446
                            if (mp_obj_is_true(obj2)) {
447
448
449
450
                                // 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;
451
452
                                // ... pop "with" exception handler, and signal END_FINALLY
                                // to just execute finally handler normally (by pushing None
453
454
455
                                // on value stack)
                                assert(exc_sp >= exc_stack);
                                assert(exc_sp->opcode == MP_BC_SETUP_WITH);
456
                                POP_EXC_BLOCK();
457
458
459
460
461
462
463
464
                                PUSH(mp_const_none);
                            }
                        } else {
                            assert(0);
                        }
                        break;
                    }

465
466
467
468
469
470
471
472
473
                    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);
474
                            if (exc_sp->opcode == MP_BC_SETUP_FINALLY || exc_sp->opcode == MP_BC_SETUP_WITH) {
475
476
477
478
479
480
481
482
483
484
485
486
487
                                // 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
488
489
                        break;

Damien's avatar
Damien committed
490
                    // matched against: POP_BLOCK or POP_EXCEPT (anything else?)
491
                    case MP_BC_SETUP_EXCEPT:
492
                    case MP_BC_SETUP_FINALLY:
493
                        PUSH_EXC_BLOCK();
494
495
                        break;

496
                    case MP_BC_END_FINALLY:
497
                        // not fully implemented
498
499
                        // if TOS is an exception, reraises the exception (3 values on TOS)
                        // if TOS is None, just pops it and continues
500
                        // if TOS is an integer, does something else
501
                        // else error
502
503
                        if (mp_obj_is_exception_type(TOP())) {
                            nlr_jump(sp[-1]);
504
505
506
                        }
                        if (TOP() == mp_const_none) {
                            sp--;
507
508
509
510
511
512
513
                        } 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;
514
515
                                case UNWIND_JUMP:
                                    goto unwind_jump;
516
517
                            }
                            assert(0);
518
519
520
                        } else {
                            assert(0);
                        }
521
522
                        break;

523
                    case MP_BC_GET_ITER:
Damien George's avatar
Damien George committed
524
                        SET_TOP(mp_getiter(TOP()));
525
526
                        break;

527
                    case MP_BC_FOR_ITER:
Damien's avatar
Damien committed
528
                        DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward
Damien George's avatar
Damien George committed
529
                        obj1 = mp_iternext_allow_raise(TOP());
530
                        if (obj1 == MP_OBJ_NULL) {
531
                            --sp; // pop the exhausted iterator
Damien's avatar
Damien committed
532
                            ip += unum; // jump to after for-block
533
534
535
536
537
                        } else {
                            PUSH(obj1); // push the next iteration value
                        }
                        break;

Damien's avatar
Damien committed
538
                    // matched against: SETUP_EXCEPT, SETUP_FINALLY, SETUP_WITH
539
                    case MP_BC_POP_BLOCK:
Damien's avatar
Damien committed
540
                        // we are exiting an exception handler, so pop the last one of the exception-stack
541
                        assert(exc_sp >= exc_stack);
542
                        POP_EXC_BLOCK();
543
544
                        break;

545
                    // matched against: SETUP_EXCEPT
546
                    case MP_BC_POP_EXCEPT:
Damien's avatar
Damien committed
547
                        // TODO need to work out how blocks work etc
548
                        // pops block, checks it's an exception block, and restores the stack, saving the 3 exception values to local threadstate
549
                        assert(exc_sp >= exc_stack);
550
                        assert(currently_in_except_block);
551
                        //sp = (mp_obj_t*)(*exc_sp--);
Damien's avatar
Damien committed
552
                        //exc_sp--; // discard ip
553
                        POP_EXC_BLOCK();
554
                        //sp -= 3; // pop 3 exception values
555
556
                        break;

557
558
559
560
561
562
563
564
                    case MP_BC_NOT:
                        if (TOP() == mp_const_true) {
                            SET_TOP(mp_const_false);
                        } else {
                            SET_TOP(mp_const_true);
                        }
                        break;

565
                    case MP_BC_UNARY_OP:
Damien's avatar
Damien committed
566
                        unum = *ip++;
Damien George's avatar
Damien George committed
567
                        SET_TOP(mp_unary_op(unum, TOP()));
Damien's avatar
Damien committed
568
569
                        break;

570
                    case MP_BC_BINARY_OP:
571
572
                        unum = *ip++;
                        obj2 = POP();
573
                        obj1 = TOP();
Damien George's avatar
Damien George committed
574
                        SET_TOP(mp_binary_op(unum, obj1, obj2));
575
576
                        break;

577
                    case MP_BC_BUILD_TUPLE:
578
                        DECODE_UINT;
579
                        sp -= unum - 1;
Damien George's avatar
Damien George committed
580
                        SET_TOP(mp_build_tuple(unum, sp));
581
582
                        break;

583
                    case MP_BC_BUILD_LIST:
584
                        DECODE_UINT;
585
                        sp -= unum - 1;
Damien George's avatar
Damien George committed
586
                        SET_TOP(mp_build_list(unum, sp));
587
588
                        break;

589
                    case MP_BC_LIST_APPEND:
590
591
                        DECODE_UINT;
                        // I think it's guaranteed by the compiler that sp[unum] is a list
Damien George's avatar
Damien George committed
592
                        mp_list_append(sp[-unum], sp[0]);
593
                        sp--;
594
595
                        break;

596
                    case MP_BC_BUILD_MAP:
597
                        DECODE_UINT;
Damien George's avatar
Damien George committed
598
                        PUSH(mp_build_map(unum));
599
600
                        break;

601
                    case MP_BC_STORE_MAP:
602
                        sp -= 2;
Damien George's avatar
Damien George committed
603
                        mp_store_map(sp[0], sp[2], sp[1]);
604
605
                        break;

606
                    case MP_BC_MAP_ADD:
Damien's avatar
Damien committed
607
                        DECODE_UINT;
608
                        // I think it's guaranteed by the compiler that sp[-unum - 1] is a map
Damien George's avatar
Damien George committed
609
                        mp_store_map(sp[-unum - 1], sp[0], sp[-1]);
610
                        sp -= 2;
Damien's avatar
Damien committed
611
612
                        break;

613
                    case MP_BC_BUILD_SET:
614
                        DECODE_UINT;
615
                        sp -= unum - 1;
Damien George's avatar
Damien George committed
616
                        SET_TOP(mp_build_set(unum, sp));
617
618
                        break;

619
                    case MP_BC_SET_ADD:
Damien's avatar
Damien committed
620
                        DECODE_UINT;
621
                        // I think it's guaranteed by the compiler that sp[-unum] is a set
Damien George's avatar
Damien George committed
622
                        mp_store_set(sp[-unum], sp[0]);
623
                        sp--;
Damien's avatar
Damien committed
624
625
                        break;

626
#if MICROPY_ENABLE_SLICE
627
628
629
630
631
632
633
634
635
636
637
                    case MP_BC_BUILD_SLICE:
                        DECODE_UINT;
                        if (unum == 2) {
                            obj2 = POP();
                            obj1 = TOP();
                            SET_TOP(mp_obj_new_slice(obj1, obj2, NULL));
                        } else {
                            printf("3-argument slice is not supported\n");
                            assert(0);
                        }
                        break;
638
#endif
639

640
                    case MP_BC_UNPACK_SEQUENCE:
641
                        DECODE_UINT;
Damien George's avatar
Damien George committed
642
                        mp_unpack_sequence(sp[0], unum, sp);
643
                        sp += unum - 1;
644
645
                        break;

646
                    case MP_BC_MAKE_FUNCTION:
647
                        DECODE_UINT;
Damien George's avatar
Damien George committed
648
                        PUSH(mp_make_function_from_id(unum, false, MP_OBJ_NULL));
649
650
651
652
                        break;

                    case MP_BC_MAKE_FUNCTION_DEFARGS:
                        DECODE_UINT;
Damien George's avatar
Damien George committed
653
                        SET_TOP(mp_make_function_from_id(unum, false, TOP()));
654
655
                        break;

656
                    case MP_BC_MAKE_CLOSURE:
Damien's avatar
Damien committed
657
                        DECODE_UINT;
Damien George's avatar
Damien George committed
658
                        SET_TOP(mp_make_closure_from_id(unum, TOP(), MP_OBJ_NULL));
659
660
661
662
663
                        break;

                    case MP_BC_MAKE_CLOSURE_DEFARGS:
                        DECODE_UINT;
                        obj1 = POP();
Damien George's avatar
Damien George committed
664
                        SET_TOP(mp_make_closure_from_id(unum, obj1, TOP()));
Damien's avatar
Damien committed
665
666
                        break;

667
                    case MP_BC_CALL_FUNCTION:
668
                        DECODE_UINT;
669
670
671
                        // unum & 0xff == n_positional
                        // (unum >> 8) & 0xff == n_keyword
                        sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe);
Damien George's avatar
Damien George committed
672
                        SET_TOP(mp_call_function_n_kw(*sp, unum & 0xff, (unum >> 8) & 0xff, sp + 1));
673
674
                        break;

675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
                    case MP_BC_CALL_FUNCTION_VAR: {
                        DECODE_UINT;
                        // unum & 0xff == n_positional
                        // (unum >> 8) & 0xff == n_keyword
                        // We have folowing stack layout here:
                        // arg0 arg1 ... kw0 val0 kw1 val1 ... seq <- TOS
                        // We need to splice seq after all positional args and before kwargs
                        // TODO: optimize one day to avoid constructing new arg array? Will be hard.
                        mp_obj_t seq = POP();
                        int total_stack_args = (unum & 0xff) + ((unum >> 7) & 0x1fe);
                        sp -= total_stack_args;

                        // Convert vararg sequence to tuple. Note that it can be arbitrary iterator.
                        // This is null call for tuple, and TODO: we actually could optimize case of list.
                        mp_obj_tuple_t *varargs = mp_obj_tuple_make_new(MP_OBJ_NULL, 1, 0, &seq);

                        int pos_args_len = (unum & 0xff) + varargs->len;
                        mp_obj_t *args = m_new(mp_obj_t, total_stack_args + varargs->len);
                        m_seq_cat(args, sp + 1, unum & 0xff, varargs->items, varargs->len, mp_obj_t);
                        m_seq_copy(args + pos_args_len, sp + (unum & 0xff) + 1, ((unum >> 7) & 0x1fe), mp_obj_t);

                        SET_TOP(mp_call_function_n_kw(*sp, pos_args_len, (unum >> 8) & 0xff, args));
                        m_del(mp_obj_t, args, total_stack_args + varargs->len);
                        break;
                    }

701
                    case MP_BC_CALL_METHOD:
702
                        DECODE_UINT;
703
704
705
                        // unum & 0xff == n_positional
                        // (unum >> 8) & 0xff == n_keyword
                        sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 1;
Damien George's avatar
Damien George committed
706
                        SET_TOP(mp_call_method_n_kw(unum & 0xff, (unum >> 8) & 0xff, sp));
707
708
                        break;

709
                    case MP_BC_RETURN_VALUE:
710
711
unwind_return:
                        while (exc_sp >= exc_stack) {
712
                            if (exc_sp->opcode == MP_BC_SETUP_FINALLY || exc_sp->opcode == MP_BC_SETUP_WITH) {
713
714
715
716
717
718
719
720
721
722
723
724
725
726
                                // 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--;
                        }
727
                        nlr_pop();
728
                        *sp_in_out = sp;
729
                        assert(exc_sp == exc_stack - 1);
730
                        return MP_VM_RETURN_NORMAL;
731

732
733
                    case MP_BC_RAISE_VARARGS:
                        unum = *ip++;
734
735
                        assert(unum <= 1);
                        if (unum == 0) {
Damien George's avatar
Damien George committed
736
737
                            // search for the inner-most previous exception, to reraise it
                            obj1 = MP_OBJ_NULL;
738
                            for (mp_exc_stack_t *e = exc_sp; e >= exc_stack; e--) {
Damien George's avatar
Damien George committed
739
740
741
742
743
744
                                if (e->prev_exc != MP_OBJ_NULL) {
                                    obj1 = e->prev_exc;
                                    break;
                                }
                            }
                            if (obj1 == MP_OBJ_NULL) {
745
746
                                nlr_jump(mp_obj_new_exception_msg(&mp_type_RuntimeError, "No active exception to reraise"));
                            }
747
748
749
                        } else {
                            obj1 = POP();
                        }
Damien George's avatar
Damien George committed
750
                        nlr_jump(mp_make_raise_obj(obj1));
751

752
                    case MP_BC_YIELD_VALUE:
753
yield:
754
755
756
                        nlr_pop();
                        *ip_in_out = ip;
                        *sp_in_out = sp;
757
                        *exc_sp_in_out = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block);
758
                        return MP_VM_RETURN_YIELD;
759

760
                    case MP_BC_YIELD_FROM: {
761
762
//#define EXC_MATCH(exc, type) MP_OBJ_IS_TYPE(exc, type)
#define EXC_MATCH(exc, type) mp_obj_exception_match(exc, type)
763
#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, &mp_type_GeneratorExit)) { nlr_jump(t); }
764
765
                        mp_vm_return_kind_t ret_kind;
                        obj1 = POP();
766
                        mp_obj_t t_exc = MP_OBJ_NULL;
767
                        if (inject_exc != MP_OBJ_NULL) {
768
                            t_exc = inject_exc;
769
                            inject_exc = MP_OBJ_NULL;
770
                            ret_kind = mp_obj_gen_resume(TOP(), mp_const_none, t_exc, &obj2);
771
                        } else {
772
                            ret_kind = mp_obj_gen_resume(TOP(), obj1, MP_OBJ_NULL, &obj2);
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
                        }

                        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);
                            }

791
792
793
                            // If we injected GeneratorExit downstream, then even
                            // if it was swallowed, we re-raise GeneratorExit
                            GENERATOR_EXIT_IF_NEEDED(t_exc);
794
795
796
797
798
799
                            break;
                        }
                        if (ret_kind == MP_VM_RETURN_EXCEPTION) {
                            // Pop exhausted gen
                            sp--;
                            if (EXC_MATCH(obj2, &mp_type_StopIteration)) {
800
801
802
803
                                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);
804
805
806
807
808
809
810
                                break;
                            } else {
                                nlr_jump(obj2);
                            }
                        }
                    }

811
                    case MP_BC_IMPORT_NAME:
812
813
                        DECODE_QSTR;
                        obj1 = POP();
Damien George's avatar
Damien George committed
814
                        SET_TOP(mp_import_name(qst, obj1, TOP()));
815
816
                        break;

817
                    case MP_BC_IMPORT_FROM:
818
                        DECODE_QSTR;
Damien George's avatar
Damien George committed
819
                        obj1 = mp_import_from(TOP(), qst);
820
821
822
                        PUSH(obj1);
                        break;

823
                    case MP_BC_IMPORT_STAR:
Damien George's avatar
Damien George committed
824
                        mp_import_all(POP());
825
826
                        break;

827
                    default:
Damien's avatar
Damien committed
828
                        printf("code %p, byte code 0x%02x not implemented\n", ip, op);
829
830
                        assert(0);
                        nlr_pop();
831
                        return MP_VM_RETURN_NORMAL;
Damien's avatar
Damien committed
832
                }
833
834
835
836
837
            }

        } else {
            // exception occurred

838
839
840
841
842
843
844
845
846
            // check if it's a StopIteration within a for block
            if (*save_ip == MP_BC_FOR_ITER && mp_obj_is_subclass_fast(mp_obj_get_type(nlr.ret_val), &mp_type_StopIteration)) {
                ip = save_ip + 1;
                DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward
                --sp; // pop the exhausted iterator
                ip += unum; // jump to after for-block
                goto outer_dispatch_loop; // continue with dispatch loop
            }

847
            // set file and line number that the exception occurred at
848
849
            // TODO: don't set traceback for exceptions re-raised by END_FINALLY.
            // But consider how to handle nested exceptions.
850
851
            // TODO need a better way of not adding traceback to constant objects (right now, just GeneratorExit_obj)
            if (mp_obj_is_exception_instance(nlr.ret_val) && nlr.ret_val != &mp_const_GeneratorExit_obj) {
852
                machine_uint_t code_info_size = code_info[0] | (code_info[1] << 8) | (code_info[2] << 16) | (code_info[3] << 24);
853
854
                qstr source_file = code_info[4] | (code_info[5] << 8) | (code_info[6] << 16) | (code_info[7] << 24);
                qstr block_name = code_info[8] | (code_info[9] << 8) |