[clang-format] Fix mis-attributing preprocessor directives to macros
authorJacob Abraham <jacob.r.abraham@gmail.com>
Tue, 11 Oct 2022 02:57:17 +0000 (19:57 -0700)
committerowenca <owenpiano@gmail.com>
Tue, 11 Oct 2022 02:57:58 +0000 (19:57 -0700)
This solves the issue where a case statement inside a macro greedily
adds preprocessor lines such as #include to the macro even if they
are not a part of the macro to begin with.

Fixes #58214.

Differential Revision: https://reviews.llvm.org/D135422

clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/FormatTest.cpp

index 7076a9f..d3aa062 100644 (file)
@@ -643,6 +643,7 @@ private:
     unsigned Length = 0;
     bool EndsWithComment = false;
     bool InPPDirective = I[0]->InPPDirective;
+    bool InMacroBody = I[0]->InMacroBody;
     const unsigned Level = I[0]->Level;
     for (; NumStmts < 3; ++NumStmts) {
       if (I + 1 + NumStmts == E)
@@ -650,6 +651,8 @@ private:
       const AnnotatedLine *Line = I[1 + NumStmts];
       if (Line->InPPDirective != InPPDirective)
         break;
+      if (Line->InMacroBody != InMacroBody)
+        break;
       if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
         break;
       if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
index e29fe10..a777382 100644 (file)
@@ -2999,6 +2999,10 @@ TEST_F(FormatTest, ShortCaseLabels) {
                "}",
                Style);
   Style.ColumnLimit = 21;
+  verifyFormat("#define X           \\\n"
+               "  case 0: break;\n"
+               "#include \"f\"",
+               Style);
   verifyFormat("switch (a) {\n"
                "case 1: x = 1; break;\n"
                "case 2: return;\n"