[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 17:59:44 PDT 2023
=?utf-8?q?Björn_Schäpers?= <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;
+ }
----------------
owenca wrote:
```suggestion
if (Tok->is(tok::r_paren)) {
// Back up past the parentheses and a `TT_DoWhile` that may precede.
Tok = Tok->MatchingParen;
if (!Tok)
return false;
Tok = Tok->getPreviousNonComment();
if (!Tok)
return false;
if (Tok->is(TT_DoWhile)) {
Tok = Tok->getPreviousNonComment();
if (!Tok)
return false;
}
}
if (Tok->isNot(tok::r_brace))
return false;
while (Tok->Previous && Tok->Previous->is(tok::r_brace))
Tok = Tok->Previous;
```
Because we should also cover `}(); //` for lambdas.
FWIW, I don't think we need to use `getPreviousNonComment()` when looking for consecutive closing braces unless we want to handle something like `} /* foo */ } //`.
https://github.com/llvm/llvm-project/pull/68743
More information about the cfe-commits
mailing list