Skip to content

Commit

Permalink
[clang-format] Don't over-indent comment below unbraced body (#95354)
Browse files Browse the repository at this point in the history
Fixes #45002.
  • Loading branch information
owenca authored Jun 15, 2024
1 parent 904c53d commit cddb9ce
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
5 changes: 5 additions & 0 deletions clang/lib/Format/UnwrappedLineParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ class ScopedLineState {
Parser.Line->PPLevel = PreBlockLine->PPLevel;
Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel;
}

~ScopedLineState() {
Expand Down Expand Up @@ -2708,7 +2709,9 @@ void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {

addUnwrappedLine();
++Line->Level;
++Line->UnbracedBodyLevel;
parseStructuralElement();
--Line->UnbracedBodyLevel;

if (Tok) {
assert(!Line->InPPDirective);
Expand Down Expand Up @@ -4836,6 +4839,8 @@ void UnwrappedLineParser::readToken(int LevelDifference) {
PPBranchLevel > 0) {
Line->Level += PPBranchLevel;
}
assert(Line->Level >= Line->UnbracedBodyLevel);
Line->Level -= Line->UnbracedBodyLevel;
flushComments(isOnNewLine(*FormatTok));
parsePPDirective();
PreviousWasComment = FormatTok->is(tok::comment);
Expand Down
3 changes: 3 additions & 0 deletions clang/lib/Format/UnwrappedLineParser.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ struct UnwrappedLine {
/// Whether it is part of a macro body.
bool InMacroBody = false;

/// Nesting level of unbraced body of a control statement.
unsigned UnbracedBodyLevel = 0;

bool MustBeDeclaration = false;

/// Whether the parser has seen \c decltype(auto) in this line.
Expand Down
30 changes: 30 additions & 0 deletions clang/unittests/Format/FormatTestComments.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,36 @@ TEST_F(FormatTestComments, KeepsLevelOfCommentBeforePPDirective) {
Style);
}

TEST_F(FormatTestComments, CommentsBetweenUnbracedBodyAndPPDirective) {
verifyFormat("{\n"
" if (a)\n"
" f(); // comment\n"
"#define A\n"
"}");

verifyFormat("{\n"
" while (a)\n"
" f();\n"
"// comment\n"
"#define A\n"
"}");

verifyNoChange("{\n"
" if (a)\n"
" f();\n"
" // comment\n"
"#define A\n"
"}");

verifyNoChange("{\n"
" while (a)\n"
" if (b)\n"
" f();\n"
" // comment\n"
"#define A\n"
"}");
}

TEST_F(FormatTestComments, SplitsLongLinesInComments) {
// FIXME: Do we need to fix up the " */" at the end?
// It doesn't look like any of our current logic triggers this.
Expand Down

0 comments on commit cddb9ce

Please sign in to comment.