[PATCH] D104044: [clang-format] Fix the issue that empty lines being removed at the beginning of namespace

Darwin Xu via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Sat Jun 19 10:07:07 PDT 2021


darwin updated this revision to Diff 353200.
darwin added a comment.

Updated with the fix code.

Look into the code, I am pretty sure this is a bug, it is about the logic of the parameter `KeepEmptyLinesAtTheStartOfBlocks`.

When `KeepEmptyLinesAtTheStartOfBlocks` is false, it will remove the empty lines at the start of the block, and namespace will be an exception. So the empty lines will be kept inside namespace.

The problem is, it can only handle the situation in which the `namespace` and the `{` are on the same line. If `BraceWrapping.AfterNamespace` is true, it will cause the `namespace` and the `{` to be separated into different lines. The original code overlooked this situation:

  // Remove empty lines after "{".
  if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
      PreviousLine->Last->is(tok::l_brace) &&
      !PreviousLine->startsWithNamespace() &&
      !startsExternCBlock(*PreviousLine))
    Newlines = 1;

As you can see, it only checks if previous line starts with namespace.

The solution is a bit of tricky, we need to check not only the **previous line**, but also the **line before the previous line**. There isn't an easy way to get this. So I added a new parameter `PrevPrevLine` to the `UnwrappedLineFormatter::formatFirstToken()` function. I have to admit this isn't an elegant solution. Let me know if there is a better way to do so.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D104044/new/

https://reviews.llvm.org/D104044

Files:
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/lib/Format/UnwrappedLineFormatter.h
  clang/unittests/Format/FormatTest.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D104044.353200.patch
Type: text/x-patch
Size: 5704 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20210619/aa3077c6/attachment-0001.bin>


More information about the cfe-commits mailing list