使用Clang ASTMatcher发出匹配的非嵌套for语句

Issue matching non-nested for statements with Clang ASTMatcher

本文关键字:嵌套 for 语句 Clang ASTMatcher 使用      更新时间:2023-10-16

我正在尝试使用Clang ASTMatcher's在c++代码中匹配单个for循环,即在源文件中如下

for(int x=0;x<10;x++){ } 
for(int y=0;y<10;y++){for(int z=0;z<5;z++){}}

我只想匹配' for(int x=0;x<10<x++){ } '

为了完成这个任务,我构建了一个匹配器:
StatementMatcher forStmtMatcher = forStmt(unless(anyOf(hasAncestor(forStmt()),hasDescendant(forStmt()))))

,我认为它应该工作,但它没有。匹配包括我不想要的for(int y=0;y<10;y++),如果我交换anyOf()匹配器中条件的位置,它将匹配for(int z=0;z<5;z++),而我也不想要。

谁能解释一下为什么或告诉我如何解决它?

我同意你所发布的看起来应该工作-但是它无法产生clang-query 3.8和4.0的预期结果。如果您尝试绑定中间匹配的变量,它似乎可以工作。

Clang查询代码(为清晰设置类型,删除换行符以运行)

set bind-root false
match forStmt(
    unless(hasAncestor(forStmt().bind('x'))),      
    unless(hasDescendant(forStmt().bind('y')))).bind('for')

等效示例:

int main()
{ 
    for(int x=0;x<10;x++){ }
    for(int y=0;y<10;y++){for(int z=0;z<5;z++){}}
}

生产:

Match #1:
/vagrant/stackoverflow-ast-query/loops.cpp:3:5: note: "for" binds here
    for(int x=0;x<10;x++){ }
    ^~~~~~~~~~~~~~~~~~~~~~~~
1 match.

看起来像是AST匹配器构造函数转换中可能存在的错误。