clang-format: [Java] Support try blocks with resources.
authorDaniel Jasper <djasper@google.com>
Wed, 14 Jan 2015 10:48:41 +0000 (10:48 +0000)
committerDaniel Jasper <djasper@google.com>
Wed, 14 Jan 2015 10:48:41 +0000 (10:48 +0000)
Before:
  try
    (SomeResource rs = someFunction()) {
      Something();
    }

After:
  try (SomeResource rs = someFunction()) {
    Something();
  }

llvm-svn: 225973

clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestJava.cpp

index d0d888f..4ba3f91 100644 (file)
@@ -1701,7 +1701,8 @@ bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
             (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
                           tok::kw_switch, tok::kw_case) ||
-             (Left.isOneOf(tok::kw_catch, tok::kw_new, tok::kw_delete) &&
+             (Left.isOneOf(tok::kw_try, tok::kw_catch, tok::kw_new,
+                           tok::kw_delete) &&
               (!Left.Previous || Left.Previous->isNot(tok::period))) ||
              Left.IsForEachMacro)) ||
            (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
index 01c8acf..ec04af5 100644 (file)
@@ -1164,6 +1164,10 @@ void UnwrappedLineParser::parseTryCatch() {
         nextToken();
     }
   }
+  // Parse try with resource.
+  if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
+    parseParens();
+  }
   if (FormatTok->is(tok::l_brace)) {
     CompoundStatementIndenter Indenter(this, Style, Line->Level);
     parseBlock(/*MustBeDeclaration=*/false);
index af4199b..8d6daa6 100644 (file)
@@ -361,6 +361,17 @@ TEST_F(FormatTestJava, TryCatchFinally) {
                "}");
 }
 
+TEST_F(FormatTestJava, TryWithResources) {
+  verifyFormat("try (SomeResource rs = someFunction()) {\n"
+               "  Something();\n"
+               "}");
+  verifyFormat("try (SomeResource rs = someFunction()) {\n"
+               "  Something();\n"
+               "} catch (SomeException e) {\n"
+               "  HandleException(e);\n"
+               "}");
+}
+
 TEST_F(FormatTestJava, SynchronizedKeyword) {
   verifyFormat("synchronized (mData) {\n"
                "  // ...\n"