Skip to content

Commit

Permalink
Support 'else' block on 'try'
Browse files Browse the repository at this point in the history
  • Loading branch information
klange committed Jul 29, 2022
1 parent d6c9602 commit 2f18ecb
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/compiler.c
Original file line number Diff line number Diff line change
Expand Up @@ -2205,6 +2205,7 @@ static void tryStatement(struct GlobalState * state) {
exitJumpOffsets[0] = emitJump(OP_JUMP);
patchJump(tryJump);

int firstJump = 0;
int nextJump = -1;

_anotherExcept:
Expand All @@ -2215,7 +2216,7 @@ static void tryStatement(struct GlobalState * state) {
previous = state->parser.previous;
advance();
}
if (match(TOKEN_EXCEPT)) {
if (exitJumps && !firstJump && match(TOKEN_EXCEPT)) {
if (nextJump != -1) {
patchJump(nextJump);
emitByte(OP_POP);
Expand Down Expand Up @@ -2254,10 +2255,18 @@ static void tryStatement(struct GlobalState * state) {
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"));
Expand Down Expand Up @@ -2285,7 +2294,7 @@ static void tryStatement(struct GlobalState * state) {
}
}

for (int i = 0; i < exitJumps; ++i) {
for (int i = firstJump; i < exitJumps; ++i) {
patchJump(exitJumpOffsets[i]);
}

Expand Down
26 changes: 26 additions & 0 deletions test/testTryElse.krk
Original file line number Diff line number Diff line change
@@ -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')
8 changes: 8 additions & 0 deletions test/testTryElse.krk.expect
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 2f18ecb

Please sign in to comment.