[clang-format] Skip preprocessor lines when finding the record lbrace
authorArthur Eubanks <aeubanks@google.com>
Wed, 13 Apr 2022 21:36:30 +0000 (14:36 -0700)
committerArthur Eubanks <aeubanks@google.com>
Thu, 14 Apr 2022 16:31:15 +0000 (09:31 -0700)
With D117142, we would now format

```
struct A {
#define A
  void f() { a(); }
#endif
};
```

into

```
struct A {
#ifdef A
  void f() {
    a();
  }
#endif
};
```

because we were looking for the record lbrace without skipping preprocess lines.

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

Reviewed By: curdeius, owenpan

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

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

index e2dbc35..9154999 100644 (file)
@@ -308,7 +308,7 @@ private:
           // Find the last line with lower level.
           auto J = I - 1;
           for (; J != AnnotatedLines.begin(); --J)
-            if ((*J)->Level < TheLine->Level)
+            if (!(*J)->InPPDirective && (*J)->Level < TheLine->Level)
               break;
           if ((*J)->Level >= TheLine->Level)
             return false;
index e837dbd..bf4ba3d 100644 (file)
@@ -12766,6 +12766,13 @@ TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
                "};",
                MergeInlineOnly);
 
+  verifyFormat("class C {\n"
+               "#ifdef A\n"
+               "  int f() { return 42; }\n"
+               "#endif\n"
+               "};",
+               MergeInlineOnly);
+
   // Also verify behavior when BraceWrapping.AfterFunction = true
   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
   MergeInlineOnly.BraceWrapping.AfterFunction = true;