[clang-format] Handle trailing comment for InsertBraces
authorowenca <owenpiano@gmail.com>
Thu, 24 Feb 2022 18:15:11 +0000 (10:15 -0800)
committerowenca <owenpiano@gmail.com>
Fri, 25 Feb 2022 20:29:47 +0000 (12:29 -0800)
Differential Revision: https://reviews.llvm.org/D120503

clang/lib/Format/Format.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

index ec6574b..c12096d 100644 (file)
@@ -1855,7 +1855,7 @@ private:
           assert(Token->BraceCount == -1);
           Brace = '{';
         } else {
-          Brace = std::string(Token->BraceCount, '}');
+          Brace = '\n' + std::string(Token->BraceCount, '}');
         }
         Token->BraceCount = 0;
         const auto Start = Token->Tok.getEndLoc();
index e2cbcea..502a84c 100644 (file)
@@ -2336,10 +2336,9 @@ void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
     assert(!Line->InPPDirective);
     Tok = nullptr;
     for (const auto &L : llvm::reverse(*CurrentLines)) {
-      if (!L.InPPDirective) {
-        Tok = getLastNonComment(L);
-        if (Tok)
-          break;
+      if (!L.InPPDirective && getLastNonComment(L)) {
+        Tok = L.Tokens.back().Tok;
+        break;
       }
     }
     assert(Tok);
index 624f3a7..8008cce 100644 (file)
@@ -24482,6 +24482,13 @@ TEST_F(FormatTest, InsertBraces) {
                Style);
 
   verifyFormat("if (a) {\n"
+               "  f(); // comment\n"
+               "}",
+               "if (a)\n"
+               "  f(); // comment",
+               Style);
+
+  verifyFormat("if (a) {\n"
                "  f();\n"
                "}\n"
                "#undef A\n"