Skip to content

Commit

Permalink
[clang-format] Don't confuse initializer equal signs in for loops (#7…
Browse files Browse the repository at this point in the history
…7712)

clang-format has logic to align declarations of multiple variables of
the same type, aligning them at the equals sign. This logic is applied
in for loops as well. However, this alignment logic also erroneously
affected the equals signs of designated initializers.

This patch forbids alignment if the token 2 tokens back from the equals
sign is a designated initializer period.

Fixes #73902
  • Loading branch information
rymiel committed Jan 22, 2024
1 parent 4821c90 commit fa6025e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion clang/lib/Format/ContinuationIndenter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,9 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,

if (Current.is(tok::equal) &&
(State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
CurrentState.VariablePos == 0) {
CurrentState.VariablePos == 0 &&
(!Previous.Previous ||
Previous.Previous->isNot(TT_DesignatedInitializerPeriod))) {
CurrentState.VariablePos = State.Column;
// Move over * and & if they are bound to the variable name.
const FormatToken *Tok = &Previous;
Expand Down
12 changes: 12 additions & 0 deletions clang/unittests/Format/FormatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5008,6 +5008,18 @@ TEST_F(FormatTest, DesignatedInitializers) {
" [3] = cccccccccccccccccccccccccccccccccccccc,\n"
" [4] = dddddddddddddddddddddddddddddddddddddd,\n"
" [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");

verifyFormat("for (const TestCase &test_case : {\n"
" TestCase{\n"
" .a = 1,\n"
" .b = 1,\n"
" },\n"
" TestCase{\n"
" .a = 2,\n"
" .b = 2,\n"
" },\n"
" }) {\n"
"}\n");
}

TEST_F(FormatTest, BracedInitializerIndentWidth) {
Expand Down

0 comments on commit fa6025e

Please sign in to comment.