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

Owen Pan via cfe-commits cfe-commits at lists.llvm.org
Fri Oct 20 18:01:30 PDT 2023


=?utf-8?q?Bj=C3=B6rn_Sch=C3=A4pers?= <bjoern at hazardy.de>
Message-ID:
In-Reply-To: <llvm/llvm-project/pull/68743/clang at github.com>


================
@@ -1118,16 +1121,39 @@ 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 || C.NewlinesBefore > 0)
+        return false;
+      const auto *Tok = Changes[I - 1].Tok;
+      if (Tok->is(tok::semi)) {
+        Tok = Tok->getPreviousNonComment();
+        if (!Tok)
+          return false;
+      }
+      if (Tok->isNot(tok::r_brace)) {
+        if (Tok->isNot(tok::r_paren) || !Tok->MatchingParen)
+          return false;
+        auto BeforeParent = Tok->MatchingParen->getPreviousNonComment();
+        return BeforeParent && BeforeParent->is(TT_DoWhile);
+      }
+
+      for (auto Prev = Tok->getPreviousNonComment();
+           Prev && Prev->is(tok::r_brace);
+           Prev = Tok->getPreviousNonComment()) {
+        Tok = Prev;
+      }
+      return Tok->NewlinesBefore > 0;
+    }();
+
+    if (DontAlignThisComment) {
----------------
owenca wrote:

```suggestion
    };

    if (I > 0 && C.NewlinesBefore == 0 &&
        DontAlignThisComment(Changes[I - 1].Tok)) {
```

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


More information about the cfe-commits mailing list