[clang] [clang-format] Don't align comments over scopes (PR #68743)

Owen Pan via cfe-commits cfe-commits at lists.llvm.org
Mon Oct 16 03:25:55 PDT 2023


================
@@ -1118,16 +1121,40 @@ void WhitespaceManager::alignTrailingComments() {
       }
     }
 
-    // We don't want to align namespace end comments.
-    const bool DontAlignThisComment =
-        I > 0 && C.NewlinesBefore == 0 &&
-        Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-    if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-        DontAlignThisComment) {
+    // We don't want to align comments which end a scope, which are here
+    // identified by most closing braces.
+    const bool DontAlignThisComment = [&] {
+      if (I == 0)
+        return false;
+      if (C.NewlinesBefore != 0)
+        return false;
+      const auto &PrevChange = Changes[I - 1];
+      if (PrevChange.Tok->is(tok::r_brace))
+        return true;
+      if (PrevChange.Tok->is(tok::semi)) {
+        if (auto PrevNonComment = PrevChange.Tok->getPreviousNonComment()) {
+          if (PrevNonComment->is(tok::r_paren) &&
+              PrevNonComment->MatchingParen &&
+              PrevNonComment->MatchingParen->endsSequence(
+                  tok::l_paren, tok::kw_while, TT_ControlStatementRBrace)) {
+            return true;
+          }
+          return PrevNonComment->isOneOf(
+              TT_ClassRBrace, TT_ControlStatementRBrace, TT_ElseRBrace,
+              TT_EnumRBrace, TT_NamespaceRBrace, TT_RecordRBrace,
+              TT_StructRBrace, TT_UnionRBrace);
+        }
+      }
+      return false;
----------------
owenca wrote:

We can skip do-while loops (or handle them in another patch) because we would also need to handle those without braces or with the closing brace on its own line.

https://github.com/llvm/llvm-project/pull/68743


More information about the cfe-commits mailing list