Skip to content

Commit 2b8542c

Browse files
committed
[clang-format] Correctly count annoated lines of a namespace body
Fixes #63882. Differential Revision: https://reviews.llvm.org/D157244
1 parent 332a34c commit 2b8542c

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

clang/lib/Format/NamespaceEndCommentsFixer.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -359,8 +359,10 @@ std::pair<tooling::Replacements, unsigned> NamespaceEndCommentsFixer::analyze(
359359
computeEndCommentText(NamespaceName, AddNewline, NamespaceTok,
360360
Style.SpacesInLineCommentPrefix.Minimum);
361361
if (!hasEndComment(EndCommentPrevTok)) {
362-
bool isShort = I - StartLineIndex <= Style.ShortNamespaceLines + 1;
363-
if (!isShort) {
362+
unsigned LineCount = 0;
363+
for (auto J = StartLineIndex + 1; J < I; ++J)
364+
LineCount += AnnotatedLines[J]->size();
365+
if (LineCount > Style.ShortNamespaceLines) {
364366
addEndComment(EndCommentPrevTok,
365367
std::string(Style.SpacesBeforeTrailingComments, ' ') +
366368
EndCommentText,

clang/lib/Format/TokenAnnotator.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,13 @@ class AnnotatedLine {
9191
}
9292
}
9393

94+
size_t size() const {
95+
size_t Size = 1;
96+
for (const auto *Child : Children)
97+
Size += Child->size();
98+
return Size;
99+
}
100+
94101
~AnnotatedLine() {
95102
for (AnnotatedLine *Child : Children)
96103
delete Child;

clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1376,6 +1376,22 @@ TEST_F(ShortNamespaceLinesTest, MultipleUnwrappedLine) {
13761376
"int k;\n"
13771377
"}\n",
13781378
Style));
1379+
1380+
// The namespace body has 5 unwrapped/annotated lines.
1381+
const std::string NestedLambdas{"namespace foo {\n"
1382+
"auto bar = [] {\n" // line 1
1383+
" int i;\n" // line 2
1384+
" return [] {\n" // line 3
1385+
" int j;" // line 4
1386+
" return 0;\n" // line 5
1387+
" };\n" // part of line 3
1388+
"};\n" // part of line 1
1389+
"}"};
1390+
Style.ShortNamespaceLines = 4;
1391+
EXPECT_EQ(NestedLambdas + " // namespace foo",
1392+
fixNamespaceEndComments(NestedLambdas, Style));
1393+
++Style.ShortNamespaceLines;
1394+
EXPECT_EQ(NestedLambdas, fixNamespaceEndComments(NestedLambdas, Style));
13791395
}
13801396

13811397
TEST_F(ShortNamespaceLinesTest, NamespaceAlias) {

0 commit comments

Comments
 (0)