[clang-format] Fix a bug in removing braces for the LLVM style
authorowenca <owenpiano@gmail.com>
Sun, 28 Aug 2022 05:22:50 +0000 (22:22 -0700)
committerowenca <owenpiano@gmail.com>
Sun, 28 Aug 2022 21:22:31 +0000 (14:22 -0700)
When an l_brace is wrapped and the line above it ends with a
comment, the annotator adds ColumnLimit to the TotalLength of the
l_brace, so the actual column position of the l_brace must be
adjusted accordingly.

Fixes #57376.

Differential Revision: https://reviews.llvm.org/D132805

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

index 7518fd3..03c6565 100644 (file)
@@ -815,6 +815,10 @@ bool UnwrappedLineParser::mightFitOnOneLine(
   auto Length = LastToken->TotalLength;
   if (OpeningBrace) {
     assert(OpeningBrace != Tokens.front().Tok);
+    if (auto Prev = OpeningBrace->Previous;
+        Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
+      Length -= ColumnLimit;
+    }
     Length -= OpeningBrace->TokenText.size() + 1;
   }
 
index 6abe155..257be01 100644 (file)
@@ -25815,6 +25815,14 @@ TEST_F(FormatTest, RemoveBraces) {
                "}",
                Style);
 
+  verifyFormat("if (a) // comment\n"
+               "  b = 1;",
+               "if (a) // comment\n"
+               "{\n"
+               "  b = 1;\n"
+               "}",
+               Style);
+
   verifyFormat("if (a) {\n"
                "Label:\n"
                "}",