如何以clang格式创建外部标题的类别?

问题描述 投票:1回答:2

我想配置clang-format以在C ++中对包含的头进行排序,如下所示:

  • 主标题(与当前cpp文件关联),
  • 通过“”包含本地标题,
  • 其他标题包含在<>中,
  • 来自特定外部库的标头(例如boost,catch2),
  • 系统/标准标题。

我在macOS上使用clang-format 8.0.0。我当前的配置(仅与包含相关的代码段)如下:

SortIncludes: true
IncludeBlocks: Regroup
IncludeCategories:
  # Headers in <> without extension.
  - Regex:           '<([A-Za-z0-9\/-_])+>'
    Priority:        4
  # Headers in <> from specific external libraries.
  - Regex:           '<((\bboost\b)|(\bcatch2\b))\/([A-Za-z0-9.\/-_])+>'
    Priority:        3
  # Headers in <> with extension.
  - Regex:           '<([A-Za-z0-9.\/-_])+>'
    Priority:        2
  # Headers in "" with extension.
  - Regex:           '"([A-Za-z0-9.\/-_])+"'
    Priority:        1

在此配置中,我假设系统/标准标头没有扩展名。它不适用于UNIX / POSIX标头。自动检测主标题并为其分配优先级0.到目前为止,除了外部库的类别外,所有内容似乎都按预期工作。看起来clang-format将它分配给优先级2。

预期结果:

#include "test.h"

#include <allocator/region.hpp>
#include <page.hpp>
#include <page_allocator.hpp>
#include <test_utils.hpp>
#include <utils.hpp>
#include <zone_allocator.hpp>

#include <catch2/catch.hpp>     // <--------

#include <array>
#include <cmath>
#include <cstring>
#include <map>

实际结果:

#include "test.h"

#include <allocator/region.hpp>
#include <catch2/catch.hpp>     // <--------
#include <page.hpp>
#include <page_allocator.hpp>
#include <test_utils.hpp>
#include <utils.hpp>
#include <zone_allocator.hpp>

#include <array>
#include <cmath>
#include <cstring>
#include <map>

如何配置优先级3以获得预期的结果?

c++ regex clang llvm-clang clang-format
2个回答
1
投票

问题是Clan格式使用POSIX ERE regexes。那些不支持单词边界。

所以<catch2/catch.hpp>永远不会匹配第二条规则。然后,对匹配的第三个规则评估相同的字符串。

如果它与第二条规则匹配,它就会停在那里,但由于它没有,它继续下一条规则。

只需删除正则表达式中的所有\b。删除它们是安全的,因为你已经有了单词边界:在左边你有<,在右边你有/所以即使你可以使用单词boudaries,它也没用。

  - Regex:           '<(boost|catch2)\/([A-Za-z0-9.\/-_])+>'
    Priority:        3

注意:请记住,-内部的[]应该用反斜杠打,除非它放在最后一个位置。那是因为它用于范围。因此,当你写[A-Za-z0-9.\/-_]时,你的意思是从A-Za-z0-9.range/_,这可能你并不意味着那样。


0
投票

我通过使用和修改clang格式文档中的示例来实现此选项:

SortIncludes: true
IncludeBlocks: Regroup
IncludeCategories:
  # Headers in <> without extension.
  - Regex:           '<([A-Za-z0-9\Q/-_\E])+>'
    Priority:        4
  # Headers in <> from specific external libraries.
  - Regex:           '<(catch2|boost)\/'
    Priority:        3
  # Headers in <> with extension.
  - Regex:           '<([A-Za-z0-9.\Q/-_\E])+>'
    Priority:        2
  # Headers in "" with extension.
  - Regex:           '"([A-Za-z0-9.\Q/-_\E])+"'
    Priority:        1

特别是,我将优先级3正则表达式改为更像原始的example

'^(<|"(gtest|gmock|isl|json)/)'

另外,我添加了\ Q和\ E修饰符以避免Julio提到的问题。现在一切都按预期工作。但是我仍然不知道为什么问题的解决方案不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.