Improve formatting of multi-variable DeclStmts.
This fixed llvm.org/PR15670
Before:
aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,
c = cccccccccccccccccccc,
d = dddddddddddddddddddd;
aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,
*c = ccccccccccccccccccc,
*d = ddddddddddddddddddd;
After:
aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,
c = cccccccccccccccccccc, d = dddddddddddddddddddd;
aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,
*c = ccccccccccccccccccc, *d = ddddddddddddddddddd;
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@178860 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp
index d6aa6a9..101b16f 100644
--- a/lib/Format/Format.cpp
+++ b/lib/Format/Format.cpp
@@ -798,9 +798,18 @@
}
} else {
if (Current.is(tok::equal) &&
- (RootToken.is(tok::kw_for) || State.ParenLevel == 0)) {
- State.Stack.back().VariablePos =
- State.Column - Previous.FormatTok.TokenLength;
+ (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
+ State.Stack.back().VariablePos == 0) {
+ State.Stack.back().VariablePos = State.Column;
+ // Move over * and & if they are bound to the variable name.
+ const AnnotatedToken *Tok = &Previous;
+ while (Tok &&
+ State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
+ State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
+ if (Tok->SpacesRequiredBefore != 0)
+ break;
+ Tok = Tok->Parent;
+ }
if (Previous.PartOfMultiVariableDeclStmt)
State.Stack.back().LastSpace = State.Stack.back().VariablePos;
}
diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp
index 2038ee1..e01034b 100644
--- a/unittests/Format/FormatTest.cpp
+++ b/unittests/Format/FormatTest.cpp
@@ -1864,7 +1864,22 @@
"bool aaaaaaaaaaaaaaaaaaaaa =\n"
" bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
" d = e && f;");
+ verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
+ " c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
+ verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
+ " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
+ verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
+ " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
+ // FIXME: If multiple variables are defined, the "*" needs to move to the new
+ // line. Also fix indent for breaking after the type, this looks bad.
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
+ " *b = bbbbbbbbbbbbbbbbbbb;");
+ // Not ideal, but pointer-with-type does not allow much here.
+ verifyGoogleFormat(
+ "aaaaaaaaa* a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
+ " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;");
}
TEST_F(FormatTest, ConditionalExpressionsInBrackets) {