Skip to content

Commit f465a48

Browse files
d0nc1h0towenca
authored andcommitted
[clang-format] Fix segmentation fault when formatting nested namespaces
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
1 parent 1078627 commit f465a48

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

clang/lib/Format/UnwrappedLineFormatter.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -386,11 +386,14 @@ class LineJoiner {
386386
// Reduce indent level for bodies of namespaces which were compacted,
387387
// but only if their content was indented in the first place.
388388
auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
389-
auto OutdentBy = I[J]->Level - TheLine->Level;
389+
const int OutdentBy = I[J]->Level - TheLine->Level;
390+
assert(OutdentBy >= 0);
390391
for (auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
391392
++CompactedLine) {
392-
if (!(*CompactedLine)->InPPDirective)
393-
(*CompactedLine)->Level -= OutdentBy;
393+
if (!(*CompactedLine)->InPPDirective) {
394+
const int Level = (*CompactedLine)->Level;
395+
(*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
396+
}
394397
}
395398
}
396399
return J - 1;

clang/unittests/Format/FormatTest.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4180,6 +4180,16 @@ TEST_F(FormatTest, FormatsNamespaces) {
41804180
"void foo() {}\n"
41814181
"} // namespace ns",
41824182
Style);
4183+
4184+
FormatStyle LLVMWithCompactInnerNamespace = getLLVMStyle();
4185+
LLVMWithCompactInnerNamespace.CompactNamespaces = true;
4186+
LLVMWithCompactInnerNamespace.NamespaceIndentation = FormatStyle::NI_Inner;
4187+
verifyFormat("namespace ns1 { namespace ns2 { namespace ns3 {\n"
4188+
"// block for debug mode\n"
4189+
"#ifndef NDEBUG\n"
4190+
"#endif\n"
4191+
"}}} // namespace ns1::ns2::ns3",
4192+
LLVMWithCompactInnerNamespace);
41834193
}
41844194

41854195
TEST_F(FormatTest, NamespaceMacros) {

0 commit comments

Comments
 (0)