diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp index 8f0b05ecb91d6..0dcf3b7c8dd06 100644 --- a/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -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; diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 21b681e290522..721cf29e0db47 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -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) {