Skip to content

Commit

Permalink
[clang-format] Correctly count annoated lines of a namespace body
Browse files Browse the repository at this point in the history
Fixes #63882.

Differential Revision: https://reviews.llvm.org/D157244
  • Loading branch information
owenca committed Aug 10, 2023
1 parent 332a34c commit 2b8542c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
6 changes: 4 additions & 2 deletions clang/lib/Format/NamespaceEndCommentsFixer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -359,8 +359,10 @@ std::pair<tooling::Replacements, unsigned> NamespaceEndCommentsFixer::analyze(
computeEndCommentText(NamespaceName, AddNewline, NamespaceTok,
Style.SpacesInLineCommentPrefix.Minimum);
if (!hasEndComment(EndCommentPrevTok)) {
bool isShort = I - StartLineIndex <= Style.ShortNamespaceLines + 1;
if (!isShort) {
unsigned LineCount = 0;
for (auto J = StartLineIndex + 1; J < I; ++J)
LineCount += AnnotatedLines[J]->size();
if (LineCount > Style.ShortNamespaceLines) {
addEndComment(EndCommentPrevTok,
std::string(Style.SpacesBeforeTrailingComments, ' ') +
EndCommentText,
Expand Down
7 changes: 7 additions & 0 deletions clang/lib/Format/TokenAnnotator.h
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ class AnnotatedLine {
}
}

size_t size() const {
size_t Size = 1;
for (const auto *Child : Children)
Size += Child->size();
return Size;
}

~AnnotatedLine() {
for (AnnotatedLine *Child : Children)
delete Child;
Expand Down
16 changes: 16 additions & 0 deletions clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,22 @@ TEST_F(ShortNamespaceLinesTest, MultipleUnwrappedLine) {
"int k;\n"
"}\n",
Style));

// The namespace body has 5 unwrapped/annotated lines.
const std::string NestedLambdas{"namespace foo {\n"
"auto bar = [] {\n" // line 1
" int i;\n" // line 2
" return [] {\n" // line 3
" int j;" // line 4
" return 0;\n" // line 5
" };\n" // part of line 3
"};\n" // part of line 1
"}"};
Style.ShortNamespaceLines = 4;
EXPECT_EQ(NestedLambdas + " // namespace foo",
fixNamespaceEndComments(NestedLambdas, Style));
++Style.ShortNamespaceLines;
EXPECT_EQ(NestedLambdas, fixNamespaceEndComments(NestedLambdas, Style));
}

TEST_F(ShortNamespaceLinesTest, NamespaceAlias) {
Expand Down

0 comments on commit 2b8542c

Please sign in to comment.