C++ 如何找到没有大括号的if和for语句?

C++ 如何找到没有大括号的if和for语句?,c++,command-line,C++,Command Line,我在看一个项目,其中一些if和for语句没有关联的括号,如下所示: if(condition) single_line_statement; for(int i=0;i<10;i++) single_line_statement; 及 以及复杂的语句,例如(请注意嵌套的括号): 如何找到不带括号的if和语句的呢?为了解决这个问题,我创建了一个方便的脚本: #/bin/bash 找到-名称** h '-ONNE.*.CPP '*找到所有C++文件 xargs pcregrep-A

我在看一个项目,其中一些
if
for
语句没有关联的括号,如下所示:

if(condition)
  single_line_statement;
for(int i=0;i<10;i++)
  single_line_statement;

以及复杂的语句,例如(请注意嵌套的括号):


如何找到不带括号的
if
语句的
呢?

为了解决这个问题,我创建了一个方便的脚本:

#/bin/bash
找到-名称** h '-ONNE.*.CPP '*找到所有C++文件
xargs pcregrep-A 1-nHM'\b(?:if | for)\s*(\(([^()]++|(?1))*\)(?!.{124;.*\ n.{)]

查找所有C++文件,然后使用Perl兼容正则表达式将每个文件的内容作为单个长线检查。此表达式使用递归<代码>(1)< /> >提取<代码>(条件)

if
for
语句之后,使用
字符匹配非换行符,并使用
\n
常量匹配新行。使用负前瞻
(?!…)
查找不带大括号的行

正则表达式可以在线测试

输出如下所示:

./dir1/file1.cpp:845:        if (!a)
./dir1/file1.cpp-846-            std::cout << "a not found!" << std::endl;
--
./dir2/file2.cpp:20:    if (b == NULL)
./dir2/file2.cpp-21-        throw std::runtime_error("b was NULL");

利用
clangtidy
提供完整的检查,代价是必须将
clangtidy
合并到构建系统中。

我使用
vera++
验证项目中的代码是否符合特定的样式规则

Vera: https://bitbucket.org/verateam/vera/wiki/Rules  
Rule: T019 Control structures should have complete curly-braced block of code

您可以将
find
缩短为:
find-name'*.h'-o-name'*.cpp'
,不幸的是,很容易找到regexp不起作用的示例。虽然这在简单的情况下就足够了。如果括号是后面注释的一部分,则regex会产生误判condition@Richard不幸的是,我不需要这样做EGEX不能解析C++语法。正如我所说的,这在简单的情况下是足够的,但是我恐怕在100%的情况下不可能实现这一点。我没有说别的,只是不希望有些人觉得你的脚本在所有情况下都能工作(或者有可能使它修复你的正则表达式)。
for (auto const &x : y)
{
    for (auto const &m : ted.bob())
    {
        if (m.n(o) != 0)
        {
            p[q] = true;
        }
        r["s"].push_back(rn.t(u));
    }
}
./dir1/file1.cpp:845:        if (!a)
./dir1/file1.cpp-846-            std::cout << "a not found!" << std::endl;
--
./dir2/file2.cpp:20:    if (b == NULL)
./dir2/file2.cpp-21-        throw std::runtime_error("b was NULL");
if (condition) // An example {
  statement;
Vera: https://bitbucket.org/verateam/vera/wiki/Rules  
Rule: T019 Control structures should have complete curly-braced block of code