From 105c1889532f3781cf97e6ecb4c6cebbdd0deee6 Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Wed, 15 Nov 2017 22:39:52 +0300 Subject: [PATCH] Fix nested exception handlers --- .../teavm/ast/decompilation/Decompiler.java | 13 ++++++++----- tests/src/test/java/org/teavm/vm/VMTest.java | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/org/teavm/ast/decompilation/Decompiler.java b/core/src/main/java/org/teavm/ast/decompilation/Decompiler.java index 1c04baa8c..268364a09 100644 --- a/core/src/main/java/org/teavm/ast/decompilation/Decompiler.java +++ b/core/src/main/java/org/teavm/ast/decompilation/Decompiler.java @@ -493,8 +493,15 @@ public class Decompiler { } // Close old bookmarks + List removedBookmarks = new ArrayList<>(); for (int i = tryCatchBookmarks.size() - 1; i >= start; --i) { TryCatchBookmark bookmark = tryCatchBookmarks.get(i); + bookmark.block.tryCatches.remove(bookmark); + removedBookmarks.add(bookmark); + } + + Collections.reverse(removedBookmarks); + for (TryCatchBookmark bookmark : removedBookmarks) { Block block = stack.peek(); while (block != bookmark.block) { TryCatchStatement tryCatchStmt = new TryCatchStatement(); @@ -509,7 +516,6 @@ public class Decompiler { } block = block.parent; } - TryCatchStatement tryCatchStmt = new TryCatchStatement(); tryCatchStmt.setExceptionType(bookmark.exceptionType); tryCatchStmt.setExceptionVariable(bookmark.exceptionVariable); @@ -523,18 +529,15 @@ public class Decompiler { if (!tryCatchStmt.getProtectedBody().isEmpty()) { blockPart.add(tryCatchStmt); } - - bookmark.block.tryCatches.remove(bookmark); } tryCatchBookmarks.subList(start, tryCatchBookmarks.size()).clear(); - } private void createNewBookmarks(List tryCatchBlocks) { // Add new bookmarks for (int i = tryCatchBookmarks.size(); i < tryCatchBlocks.size(); ++i) { - TryCatchBlock tryCatch = tryCatchBlocks.get(i); + TryCatchBlock tryCatch = tryCatchBlocks.get(tryCatchBlocks.size() - 1 - i); TryCatchBookmark bookmark = new TryCatchBookmark(); bookmark.block = stack.peek(); bookmark.offset = bookmark.block.body.size(); diff --git a/tests/src/test/java/org/teavm/vm/VMTest.java b/tests/src/test/java/org/teavm/vm/VMTest.java index b246ac10b..271188f2a 100644 --- a/tests/src/test/java/org/teavm/vm/VMTest.java +++ b/tests/src/test/java/org/teavm/vm/VMTest.java @@ -82,6 +82,25 @@ public class VMTest { assertEquals(23, a); } + @Test + public void emptyTryCatchInsideFinally() { + StringBuilder sb = new StringBuilder(); + try { + sb.append("before;"); + try { + sb.append("inside;"); + Integer.parseInt("not a number"); + sb.append("ignore;"); + } catch (NumberFormatException e) { + // do nothing + } + sb.append("after;"); + } finally { + sb.append("finally;"); + } + assertEquals("before;inside;after;finally;", sb.toString()); + } + @Test public void surrogateInStringLiteralsWork() { assertEquals(0xDDC2, "a\uDDC2b".charAt(1));