Skip to content

Commit 28f93fb

Browse files
committed
Merge pull request adafruit#239 from pfalcon/end_finally
vm: Add basic implementation of END_FINALLY opcode.
2 parents 65ae601 + 382e8ee commit 28f93fb

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

py/vm.c

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,12 +325,19 @@ bool mp_execute_byte_code_2(const byte *code_info, const byte **ip_in_out, mp_ob
325325
break;
326326

327327
case MP_BC_END_FINALLY:
328-
// not implemented
328+
// not fully implemented
329329
// if TOS is an exception, reraises the exception (3 values on TOS)
330-
// if TOS is an integer, does something else
331330
// if TOS is None, just pops it and continues
331+
// if TOS is an integer, does something else
332332
// else error
333-
assert(0);
333+
if (MP_OBJ_IS_TYPE(TOP(), &exception_type)) {
334+
nlr_jump(TOP());
335+
}
336+
if (TOP() == mp_const_none) {
337+
sp--;
338+
} else {
339+
assert(0);
340+
}
334341
break;
335342

336343
case MP_BC_GET_ITER:
@@ -361,6 +368,7 @@ bool mp_execute_byte_code_2(const byte *code_info, const byte **ip_in_out, mp_ob
361368
// TODO need to work out how blocks work etc
362369
// pops block, checks it's an exception block, and restores the stack, saving the 3 exception values to local threadstate
363370
assert(exc_sp >= &exc_stack[0]);
371+
assert(currently_in_except_block);
364372
//sp = (mp_obj_t*)(*exc_sp--);
365373
//exc_sp--; // discard ip
366374
currently_in_except_block = (exc_sp[0] & 1); // restore previous state
@@ -517,6 +525,8 @@ bool mp_execute_byte_code_2(const byte *code_info, const byte **ip_in_out, mp_ob
517525
// exception occurred
518526

519527
// set file and line number that the exception occurred at
528+
// TODO: don't set traceback for exceptions re-raised by END_FINALLY.
529+
// But consider how to handle nested exceptions.
520530
if (MP_OBJ_IS_TYPE(nlr.ret_val, &exception_type)) {
521531
machine_uint_t code_info_size = code_info[0] | (code_info[1] << 8) | (code_info[2] << 16) | (code_info[3] << 24);
522532
qstr source_file = code_info[4] | (code_info[5] << 8) | (code_info[6] << 16) | (code_info[7] << 24);

tests/basics/try2.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,14 @@
1010
bar()
1111
except:
1212
print("except 1")
13+
14+
try:
15+
print("try 1")
16+
try:
17+
print("try 2")
18+
foo()
19+
except TypeError:
20+
print("except 2")
21+
bar()
22+
except NameError:
23+
print("except 1")

0 commit comments

Comments
 (0)