[clang] 37e754e - [clang-format] Insert closing braces after an unaffected line

via cfe-commits cfe-commits at lists.llvm.org
Mon Oct 24 20:00:14 PDT 2022


Author: owenca
Date: 2022-10-24T20:00:06-07:00
New Revision: 37e754e5801c5de2e84ca2d7d40a48c780787f01

URL: https://github.com/llvm/llvm-project/commit/37e754e5801c5de2e84ca2d7d40a48c780787f01
DIFF: https://github.com/llvm/llvm-project/commit/37e754e5801c5de2e84ca2d7d40a48c780787f01.diff

LOG: [clang-format] Insert closing braces after an unaffected line

The token that records the number of closing braces to be inserted
may be on an unaffected line. Extra work is required in order to
actually insert the closing braces after inserting the matching
opening braces of affected lines.

Fixes #58161.

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

Added: 
    

Modified: 
    clang/lib/Format/Format.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 1bab870ee52ab..16010617539d0 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1874,26 +1874,37 @@ class BracesInserter : public TokenAnalyzer {
   void insertBraces(SmallVectorImpl<AnnotatedLine *> &Lines,
                     tooling::Replacements &Result) {
     const auto &SourceMgr = Env.getSourceManager();
+    int OpeningBraceSurplus = 0;
     for (AnnotatedLine *Line : Lines) {
       insertBraces(Line->Children, Result);
-      if (!Line->Affected)
+      if (!Line->Affected && OpeningBraceSurplus == 0)
         continue;
       for (FormatToken *Token = Line->First; Token && !Token->Finalized;
            Token = Token->Next) {
-        if (Token->BraceCount == 0)
+        int BraceCount = Token->BraceCount;
+        if (BraceCount == 0)
           continue;
         std::string Brace;
-        if (Token->BraceCount < 0) {
-          assert(Token->BraceCount == -1);
+        if (BraceCount < 0) {
+          assert(BraceCount == -1);
+          if (!Line->Affected)
+            break;
           Brace = Token->is(tok::comment) ? "\n{" : "{";
+          ++OpeningBraceSurplus;
         } else {
-          Brace = '\n' + std::string(Token->BraceCount, '}');
+          if (OpeningBraceSurplus == 0)
+            break;
+          if (OpeningBraceSurplus < BraceCount)
+            BraceCount = OpeningBraceSurplus;
+          Brace = '\n' + std::string(BraceCount, '}');
+          OpeningBraceSurplus -= BraceCount;
         }
         Token->BraceCount = 0;
         const auto Start = Token->Tok.getEndLoc();
         cantFail(Result.add(tooling::Replacement(SourceMgr, Start, 0, Brace)));
       }
     }
+    assert(OpeningBraceSurplus == 0);
   }
 };
 


        


More information about the cfe-commits mailing list