[PATCH] D133647: [clang-format] Parse the else part of `#if 0`

sstwcw via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Sat Sep 10 12:42:49 PDT 2022


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

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

Previously things outside of `#if` blocks were parsed as if only the
first branch of the conditional compilation branch existed.  Unless the
first condition is 0, then the outer parts would be parsed as if
everything inside the conditional parts didn't exist.  Now we use the
second conditional branch if the first condition is 0.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133647

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===================================================================
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -5993,6 +5993,16 @@
                          ");\n"
                          "#else\n"
                          "#endif");
+
+  // Verify that indentation is correct when there is an `#if 0` with an
+  // `#else`.
+  verifyFormat("#if 0\n"
+               "{\n"
+               "#else\n"
+               "{\n"
+               "#endif\n"
+               "  x;\n"
+               "}");
 }
 
 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===================================================================
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1124,7 +1124,9 @@
   ++PPBranchLevel;
   assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
   if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
-    PPLevelBranchIndex.push_back(0);
+    // If the first branch is unreachable, set the BranchIndex to 1.  This way
+    // the next branch it will be parsed if there is one.
+    PPLevelBranchIndex.push_back(Unreachable ? 1 : 0);
     PPLevelBranchCount.push_back(0);
   }
   PPChainBranchIndex.push(0);


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D133647.459305.patch
Type: text/x-patch
Size: 1358 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20220910/830518d0/attachment.bin>


More information about the cfe-commits mailing list