[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
This commit is contained in:
Arkadiy Yudintsev 2023-09-05 11:12:14 -07:00 committed by Owen Pan
parent 1078627cf8
commit f465a482ca
2 changed files with 16 additions and 3 deletions

View File

@ -386,11 +386,14 @@ private:
// 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;

View File

@ -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) {