[PATCH] D129064: [clang-format] Avoid crash in LevelIndentTracker.

Marek Kurdej via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Mon Jul 4 02:34:29 PDT 2022


curdeius created this revision.
curdeius added reviewers: HazardyKnusperkeks, owenpan, MyDeveloperDay.
Herald added a project: All.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fixes https://github.com/llvm/llvm-project/issues/56352.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129064

Files:
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/unittests/Format/FormatTestSelective.cpp


Index: clang/unittests/Format/FormatTestSelective.cpp
===================================================================
--- clang/unittests/Format/FormatTestSelective.cpp
+++ clang/unittests/Format/FormatTestSelective.cpp
@@ -609,6 +609,14 @@
                      "  return a == 8 ? 32 : 16;\n"
                      "}\n";
   EXPECT_EQ(Code, format(Code, 40, 0));
+
+  // https://llvm.org/PR56352
+  Style.CompactNamespaces = true;
+  Style.NamespaceIndentation = FormatStyle::NI_All;
+  Code = "\n"
+         "namespace ns1 { namespace ns2 {\n"
+         "}}";
+  EXPECT_EQ(Code, format(Code, 0, 0));
 }
 
 } // end namespace
Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===================================================================
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -66,7 +66,8 @@
           (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
       Indent = Line.Level * IndentWidth + AdditionalIndent;
     } else {
-      IndentForLevel.resize(Line.Level + 1);
+      if (IndentForLevel.size() < Line.Level + 1)
+        IndentForLevel.resize(Line.Level + 1);
       Indent = getIndent(Line.Level);
     }
     if (static_cast<int>(Indent) + Offset >= 0)
@@ -91,6 +92,7 @@
     unsigned LevelIndent = Line.First->OriginalColumn;
     if (static_cast<int>(LevelIndent) - Offset >= 0)
       LevelIndent -= Offset;
+    assert(Line.Level < IndentForLevel.size());
     if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
         !Line.InPPDirective) {
       IndentForLevel[Line.Level] = LevelIndent;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D129064.442037.patch
Type: text/x-patch
Size: 1628 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20220704/1d1452d6/attachment.bin>


More information about the cfe-commits mailing list