[clang] f465a48 - [clang-format] Fix segmentation fault when formatting nested namespaces
Owen Pan via cfe-commits
cfe-commits at lists.llvm.org
Tue Sep 5 11:18:36 PDT 2023
Author: Arkadiy Yudintsev
Date: 2023-09-05T11:12:14-07:00
New Revision: f465a482caa94d01a2dd74e4c673adeb1f222f2f
URL: https://github.com/llvm/llvm-project/commit/f465a482caa94d01a2dd74e4c673adeb1f222f2f
DIFF: https://github.com/llvm/llvm-project/commit/f465a482caa94d01a2dd74e4c673adeb1f222f2f.diff
LOG: [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
Added:
Modified:
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/FormatTest.cpp
Removed:
################################################################################
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 8f0b05ecb91d67..0dcf3b7c8dd06b 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 21b681e290522e..721cf29e0db474 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) {
More information about the cfe-commits
mailing list