Skip to content

Commit 25282bd

Browse files
committed
[clang-format] Handle PointerAlignment in if and switch statements with initializers (C++17) the same way as in for loops.
Reviewed By: MyDeveloperDay, owenpan Differential Revision: https://reviews.llvm.org/D119650
1 parent 9cb9445 commit 25282bd

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

clang/lib/Format/TokenAnnotator.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ namespace format {
2626

2727
namespace {
2828

29+
/// Returns \c true if the line starts with a token that can start a statement
30+
/// with an initializer.
31+
static bool startsWithInitStatement(const AnnotatedLine &Line) {
32+
return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) ||
33+
Line.startsWith(tok::kw_switch);
34+
}
35+
2936
/// Returns \c true if the token can be used as an identifier in
3037
/// an Objective-C \c \@selector, \c false otherwise.
3138
///
@@ -1135,7 +1142,7 @@ class AnnotatingParser {
11351142
else if (Contexts.back().InInheritanceList)
11361143
Tok->setType(TT_InheritanceComma);
11371144
else if (Contexts.back().FirstStartOfName &&
1138-
(Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
1145+
(Contexts.size() == 1 || startsWithInitStatement(Line))) {
11391146
Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
11401147
Line.IsMultiVariableDeclStmt = true;
11411148
}
@@ -3090,7 +3097,7 @@ bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
30903097
FormatStyle::PAS_Left ||
30913098
(Line.IsMultiVariableDeclStmt &&
30923099
(Left.NestingLevel == 0 ||
3093-
(Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))));
3100+
(Left.NestingLevel == 1 && startsWithInitStatement(Line)))));
30943101
}
30953102
if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
30963103
(!Left.is(TT_PointerOrReference) ||

clang/unittests/Format/FormatTest.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8396,6 +8396,12 @@ TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
83968396
Style);
83978397
verifyFormat("vector<int*> a, b;", Style);
83988398
verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
8399+
verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style);
8400+
verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style);
8401+
verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}",
8402+
Style);
8403+
verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", Style);
8404+
verifyFormat("/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", Style);
83998405
}
84008406

84018407
TEST_F(FormatTest, ConditionalExpressionsInBrackets) {

0 commit comments

Comments
 (0)