clang-format:宏的缩进

clang-format: indentation of macros

我正在尝试将 clang-format 应用于现有代码库并遇到以下问题:

简化(和格式化)示例代码:

#define QUERY_BEGIN()
#define QUERY_NORESULT()
#define QUERY_END()

void foo()
{
   int a = 0;

   QUERY_BEGIN()
      a = 1;
      QUERY_NORESULT()
      a = 2;
   QUERY_END()
}

我设置了以下选项:

MacroBlockEnd:   'QUERY_END'
MacroBlockBegin: 'QUERY_BEGIN'

我要实现的是宏部分的格式如下:

   QUERY_BEGIN()
      a = 1;
   QUERY_NORESULT()
      a = 2;
   QUERY_END()

我的第一个猜测是将 QUERY_NORESULT 设置为 MacroBlockEndMacroBlockBegin,但这没有帮助。它导致以下格式:

   QUERY_BEGIN()
      a = 1;
      QUERY_NORESULT
         a = 2;
      QUERY_END()

目前有没有办法实现如上所示的缩进?

  • 坏消息:抱歉,这在 clang-format(7) 的当前发行版中不可用。
  • 好消息:有一个 StatementMacros 选项,从 clang-format 8 开始可用(尚未发布,但您可以从源代码构建)。

参见this commit

Summary: Some macros are used in the body of function, and actually contain the trailing semicolon: they should thus be automatically followed by a new line, and not get merged with the next line. This is for example the case with Qt's Q_UNUSED macro:

  void foo(int a, int b) {
    Q_UNUSED(a)
    return b;
  }

This patch deals with these cases by introducing a new option to specify list of statement macros. This re-uses the system already in place for foreach macros, to ensure there is no impact on performance.

Document:

◆ StatementMacros

std::vector clang::format::FormatStyle::StatementMacros A vector of macros that should be interpreted as complete statements.

Typical macros are expressions, and require a semi-colon to be added; sometimes this is not the case, and this allows to make clang-format aware of such cases.

For example: Q_UNUSED

Definition at line 1061 of file Format.h.

Referenced by clang::format::FormatTokenLexer::FormatTokenLexer(), clang::format::getLLVMStyle(), llvm::yaml::MappingTraits< FormatStyle >::mapping(), and operator==().

解决方案:

build clang from source/等待llvm/clang8释放,然后 将 StatementMacros ['QUERY_BEGIN()', 'QUERY_NORESULT()', 'QUERY_END()'] 放入您的 .clang-format.

Workaround for old clang-format

// clang-format off
    void    unformatted_code  ;
// clang-format on

关闭此宏语句中的 clang-format。