[clang] [clang-format] Handle Trailing Whitespace After Line Continuation (P2223R2) (PR #145243)

Naveen Seth Hanig via cfe-commits cfe-commits at lists.llvm.org
Tue Jun 24 07:45:24 PDT 2025


================
@@ -25768,6 +25768,29 @@ TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
   verifyFormat("foo(operator, , -42);", Style);
 }
 
+TEST_F(FormatTest, LineSpliceWithTrailingWhitespace) {
+  // Test that each sequence of a backslash (\) immediately followed by zero or
+  // more horizontal whitespace characters and then a new-line character is
+  // treated as a single logical line while formatting (as per P2223R2).
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
+  Style.UseTab = FormatStyle::UT_Never;
+
+  verifyFormat("int i;",
+               "  \\  \n"
+               "  int i;",
+               Style);
+  verifyFormat("#define FOO(args) \\\n  struct a {};\n",
+               "#define FOO( args )   \\   \n"
+               "struct a{\\\t\t\t\n"
+               "  };\n",
+               Style);
+  verifyFormat("comment here",
+               "comment \\ \n"
+               "here",
+               Style);
----------------
naveen-seth wrote:

Sorry, I forgot the leading `//`.

Currently, `clang-format` already detects line-splicing in comments, even with trailing whitespace. However, unlike with directives and other cases, trailing whitespace in comment splices is not removed.

For example, with the current behavior, the following test passes:

```cpp
  verifyFormat("//comment \\     \n"
               "here",
               "//comment \\     \n"
               "here",
               Style);
```

instead of trimming the whitespace as it does elsewhere.
This is what I would have expected:

```cpp
  verifyFormat("//comment \\\n"
               "here",
               "//comment \\     \n"
               "here",
               Style);
```

I wasn't sure whether this should be addressed in this patch or if it's intended behavior, so I’ve deleted the test for now.
Please let me know if this needs fixing, and thank you for the review.

https://github.com/llvm/llvm-project/pull/145243


More information about the cfe-commits mailing list