如何查找是否以及不带括号的语句? [英] How can I find if and for statements without braces?
问题描述
我正在寻找一个项目,其中某些 if
和 for
语句没有相关的括号,像这样:
I'm looking at a project in which some if
and for
statements do not have their associated brackets, like so:
if(condition)
single_line_statement;
for(int i=0;i<10;i++)
single_line_statement;
我想找到这些语句!
但是,由于存在两种不同的包围样式的代码,这变得具有挑战性:
However, this is made challenging by the existence of code with two different bracketing styles:
if(condition){
stuff;
}
和
if(condition(a) && condition(b))
{
stuff;
}
以及复杂的语句,例如(请注意嵌套的括号):
as well as by complex statements such as (note the nested brackets):
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));
}
}
如何找到 if
和用于没有括号的
语句?
推荐答案
为解决这个问题,我创建了一个方便的丹迪脚本:
To solve this problem, I created a handy dandy script:
#!/bin/bash
find . -name '*.h' -o -name '*.cpp' | #Find all C++ files
xargs pcregrep -A 1 -nHM '\b(?:if|for)\s*(\(([^()]++|(?1))*\))(?!.*{|.*\n.*{)'
这将查找所有C ++文件,然后使用与Perl兼容的正则表达式将它们作为单个长行检查每个文件的内容。此表达式使用递归(?1)
提取 if <后的
(条件)
。 / code>和用于
语句和。
字符以匹配不是换行符的字符和 \n
常量以匹配新行。负向超前(?!...)
用于查找不带括号的行。
This finds all the C++ files and then examines the contents of each file as a single, long line using a Perl Compatible Regular Expression. This expression uses recursion (?1)
to extract the (condition)
following the if
and for
statements and the .
character to match characters which are not newlines and the \n
constant to match new lines. Negative-lookahead (?!...)
is used to find the lines without braces.
正则表达式可以在此处进行在线测试。
The regular expression can be tested online here.
输出看起来像这样:
./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");
由于脚本实际上并不解析C ++,因此在某些情况下它会表现异常。例如,它将丢失:
Since the script does not, in fact, parse C++, there are situations where it will misbehave. For instance, it will miss this:
if (condition) // An example {
statement;
此答案利用 clang-tidy
来提供完整的支票,但必须合并 clang-tidy
进入一个人的构建系统。
This answer leverages clang-tidy
to provide a complete check, at the cost of having to incorporate clang-tidy
into one's build system.
这篇关于如何查找是否以及不带括号的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!