ecl*_*pse 11 c++ regex clang llvm-clang clang-format
我想配置 clang-format 以在 C++ 中对包含的标头进行排序,如下所示:
我在 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
Run Code Online (Sandbox Code Playgroud)
在此配置中,我假设系统/标准标头没有扩展名。它不适用于 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>
Run Code Online (Sandbox Code Playgroud)
实际结果:
#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>
Run Code Online (Sandbox Code Playgroud)
如何配置优先级3才能达到预期的结果?
我通过使用和修改 clang-format 文档中的此选项的示例来使其工作:
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
Run Code Online (Sandbox Code Playgroud)
特别是,我将优先级 3 正则表达式更改为更像原始示例:
'^(<|"(gtest|gmock|isl|json)/)'
Run Code Online (Sandbox Code Playgroud)
另外,我添加了 \Q 和 \E 修饰符以避免 Julio 提到的问题。现在一切都按预期进行。但是我仍然不知道为什么问题帖子中的解决方案不起作用。
问题是 Clan 格式使用POSIX ERE 正则表达式。这些不支持字边界。
所以<catch2/catch.hpp>永远不会匹配第二条规则。然后,针对匹配的第三条规则评估同一字符串。
如果它与第二条规则匹配,它就会在那里停止,但由于它没有匹配,它会继续下一条规则。
只需删除正则\b表达式上的所有内容即可。删除它们是安全的,因为您已经有了单词边界:左边有<,右边有/,所以即使您可以使用单词边界,它也是无用的。
- Regex: '<(boost|catch2)\/([A-Za-z0-9.\/-_])+>'
Priority: 3
Run Code Online (Sandbox Code Playgroud)
注意:请记住,除非将其放在最后一个位置,否则-内部[]应使用反斜杠进行转义。那是因为它用于范围。因此,当您写作时,[A-Za-z0-9.\/-_]您的意思A-Za-z0-9.或范围可能不是您/想要_那样。