我试图检测是否在if语句中有函数调用作为条件的一部分;喜欢以下:
if (cmp(a, b)){
\do something
}
I have found I could do this with AST matcher in following manner:
Matcher.addMatcher(ifStmt(hasCondition(callExpr().bind("call_expr")))
.bind("call_if_stmt"),&handleMatch);
但问题是条件可能具有类似&,||的快捷方式。喜欢以下:
if(a != b && cmp(a,b) || c == 10){
\ do something
}
现在,这种情况有二元运动器&&||;也有一个呼叫表达方式作为其中的一部分。现在,我如何检测该语句中有呼叫表达式?绝对不知道会有多少个二进制操作员,因为捷径会在那里,所以我正在寻找一种可能使用Clange AST Matcher的概括解决方案。
在第一种情况下,if(cmp(a,b))
,CALLEXPR节点是IFSTMT的直接子。在第二种情况下,它是IFSTMT的后代,但不是孩子。取而代之的是,它嵌套在两个二元操作器节点下。(我通过使用clang-check -ast-dump test.cpp --
查看AST来发现这一点。(添加hasDescendant
遍历匹配器会发现更深层嵌套的CallexPR。不幸的是,仅此一项就找不到第一个案例。因此,我们可以使用anyOf
将其与原始匹配器相结合:
ifStmt(
hasCondition(
anyOf(
callExpr().bind("top_level_call_expr"),
hasDescendant(
callExpr().bind("nested_call_expr")
)
)
)
).bind("call_if_stmt")
如果我进行test.cpp具有以下代码:
bool cmp(int a, int b){return a < b;}
int f(int a, int c){
int b = 42;
if( a != b && cmp(a,b) || c == 10){
return 2;
}
return c;
}
int g(int a, int c){
int b = 42;
if( cmp(a,b)) {
return 2;
}
return c;
}
然后我可以用 clang-query test.cpp --
:
clang-query> let m2 ifStmt( hasCondition( anyOf(callExpr().bind("top_level_call_expr"),hasDescendant(callExpr().bind("nested_call_expr"))))).bind("call_if_stmt")
clang-query> m m2
Match #1:
/path/to/test.xpp:5:7: note: "call_if_stmt" binds here
if( a != b && cmp(a,b) || c == 10){
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/path/to/test.cpp:5:21: note: "nested_call_expr" binds here
if( a != b && cmp(a,b) || c == 10){
^~~~~~~~
/path/to/test.cpp:5:7: note: "root" binds here
if( a != b && cmp(a,b) || c == 10){
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Match #2:
/path/to/test.cpp:13:7: note: "call_if_stmt" binds here
if( cmp(a,b)) {
^~~~~~~~~~~~~~~
/path/to/test.cpp:13:7: note: "root" binds here
if( cmp(a,b)) {
^~~~~~~~~~~~~~~
/path/to/test.cpp:13:11: note: "top_level_call_expr" binds here
if( cmp(a,b)) {
^~~~~~~~
2 matches.