Support 'else' block on 'try'

This commit is contained in:
K. Lange 2022-07-29 19:33:31 +09:00
parent d6c9602abd
commit 2f18ecbaa1
3 changed files with 46 additions and 3 deletions

View File

@ -2205,6 +2205,7 @@ static void tryStatement(struct GlobalState * state) {
exitJumpOffsets[0] = emitJump(OP_JUMP);
patchJump(tryJump);
int firstJump = 0;
int nextJump = -1;
_anotherExcept:
@ -2215,7 +2216,7 @@ _anotherExcept:
previous = state->parser.previous;
advance();
}
if (match(TOKEN_EXCEPT)) {
if (exitJumps && !firstJump && match(TOKEN_EXCEPT)) {
if (nextJump != -1) {
patchJump(nextJump);
emitByte(OP_POP);
@ -2254,10 +2255,18 @@ _anotherExcept:
return;
}
goto _anotherExcept;
} else if (firstJump != 1 && match(TOKEN_ELSE)) {
consume(TOKEN_COLON, "Expected ':' after 'else'.");
patchJump(exitJumpOffsets[0]);
firstJump = 1;
beginScope(state);
block(state, blockWidth, "else");
endScope(state);
goto _anotherExcept;
} else if (match(TOKEN_FINALLY)) {
consume(TOKEN_COLON, "Expected ':' after 'finally'.");
for (int i = 0; i < exitJumps; ++i) {
for (int i = firstJump; i < exitJumps; ++i) {
patchJump(exitJumpOffsets[i]);
}
size_t nameInd = renameLocal(state, exceptionObject, syntheticToken("__tmp"));
@ -2285,7 +2294,7 @@ _anotherExcept:
}
}
for (int i = 0; i < exitJumps; ++i) {
for (int i = firstJump; i < exitJumps; ++i) {
patchJump(exitJumpOffsets[i]);
}

26
test/testTryElse.krk Normal file
View File

@ -0,0 +1,26 @@
try:
print('totally fine')
except:
print('impossible!')
else:
print('good to go')
finally:
print('then the finally')
try:
print('totally fine')
except:
print('impossible!')
else:
print('good to go')
try:
print('in the try')
raise ValueError()
print('oh no, fail')
except:
print('does the except')
else:
print('should not happen, fail')
finally:
print('does the finally')

View File

@ -0,0 +1,8 @@
totally fine
good to go
then the finally
totally fine
good to go
in the try
does the except
does the finally