Skip to content

Commit

Permalink
[clang-format] Fix segmentation fault when formatting nested namespaces
Browse files Browse the repository at this point in the history
Fixing the clang-format crash with the segmentation fault error when
formatting code with nested namespaces.

Fixes #64701.

Differential Revision: https://reviews.llvm.org/D158363
  • Loading branch information
d0nc1h0t authored and owenca committed Sep 5, 2023
1 parent 1078627 commit f465a48
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
9 changes: 6 additions & 3 deletions clang/lib/Format/UnwrappedLineFormatter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -386,11 +386,14 @@ class LineJoiner {
// Reduce indent level for bodies of namespaces which were compacted,
// but only if their content was indented in the first place.
auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
auto OutdentBy = I[J]->Level - TheLine->Level;
const int OutdentBy = I[J]->Level - TheLine->Level;
assert(OutdentBy >= 0);
for (auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
++CompactedLine) {
if (!(*CompactedLine)->InPPDirective)
(*CompactedLine)->Level -= OutdentBy;
if (!(*CompactedLine)->InPPDirective) {
const int Level = (*CompactedLine)->Level;
(*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
}
}
}
return J - 1;
Expand Down
10 changes: 10 additions & 0 deletions clang/unittests/Format/FormatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4180,6 +4180,16 @@ TEST_F(FormatTest, FormatsNamespaces) {
"void foo() {}\n"
"} // namespace ns",
Style);

FormatStyle LLVMWithCompactInnerNamespace = getLLVMStyle();
LLVMWithCompactInnerNamespace.CompactNamespaces = true;
LLVMWithCompactInnerNamespace.NamespaceIndentation = FormatStyle::NI_Inner;
verifyFormat("namespace ns1 { namespace ns2 { namespace ns3 {\n"
"// block for debug mode\n"
"#ifndef NDEBUG\n"
"#endif\n"
"}}} // namespace ns1::ns2::ns3",
LLVMWithCompactInnerNamespace);
}

TEST_F(FormatTest, NamespaceMacros) {
Expand Down

0 comments on commit f465a48

Please sign in to comment.