diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp index 16fa2e7b50f1c3..dbf1e4cbbf6a31 100644 --- a/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -312,10 +312,15 @@ class LineJoiner { break; // Check if the found line starts a record. - for (const FormatToken *RecordTok = (*J)->Last; RecordTok; - RecordTok = RecordTok->Previous) - if (RecordTok->is(tok::l_brace)) - return isRecordLBrace(*RecordTok); + const FormatToken *LastNonComment = (*J)->Last; + assert(LastNonComment); + if (LastNonComment->is(tok::comment)) { + LastNonComment = LastNonComment->getPreviousNonComment(); + // There must be another token (usually `{`), because we chose a + // line that has a smaller level. + assert(LastNonComment); + } + return isRecordLBrace(*LastNonComment); } } diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 6e5dd3284633c4..73503696741a77 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -3809,6 +3809,18 @@ TEST_F(FormatTest, FormatsNamespaces) { " }\n" "} // namespace\n", ShortInlineFunctions); + verifyFormat("namespace { /* comment */\n" + " void f() {\n" + " return;\n" + " }\n" + "} // namespace\n", + ShortInlineFunctions); + verifyFormat("namespace { // comment\n" + " void f() {\n" + " return;\n" + " }\n" + "} // namespace\n", + ShortInlineFunctions); verifyFormat("namespace {\n" " int some_int;\n" " void f() {\n" @@ -3828,6 +3840,18 @@ TEST_F(FormatTest, FormatsNamespaces) { " };\n" "} // namespace\n", ShortInlineFunctions); + verifyFormat("namespace {\n" + " class X { /* comment */\n" + " void f() { return; }\n" + " };\n" + "} // namespace\n", + ShortInlineFunctions); + verifyFormat("namespace {\n" + " class X { // comment\n" + " void f() { return; }\n" + " };\n" + "} // namespace\n", + ShortInlineFunctions); verifyFormat("namespace {\n" " struct X {\n" " void f() { return; }\n"