7

I want to match any statement that has a call expression as a descendant on the AST. Here is a simple example:

int foo() {
  return 5;
}

int main() {
  int a;
  a = foo();
  return 0:
}

In this example I want to match the a = foo(); statement. In order to do that I have created the following matcher and it works just fine:

StatementMatcher sm = stmt(hasParent(compoundStmt()),
                           hasDescendant(callExpr()));

The problem is that this matcher does not work if I change the RHS of the statement to a more complex expression, e.g. a = 5 + foo(); instead of a = foo();. The description of the hasDescendant matcher in Clang's documentation says this:

Matches AST nodes that have descendant AST nodes that match the provided matcher.

According to this, the matcher should work in the second case as well, but it doesn't. Why not? Is there any other way to match this kind of statements?

I provide you with the ast-dumps of both cases.

a = foo(); dump:

`-CompoundStmt 0x4223c40 <line:6:12, line:10:1>
 |-DeclStmt 0x4223b08 <line:7:3, col:8>
 | `-VarDecl 0x4223ab0 <col:3, col:7> a 'int'
 |-BinaryOperator 0x4223bd8 <line:8:3, col:11> 'int' '='
 | |-DeclRefExpr 0x4223b20 <col:3> 'int' lvalue Var 0x4223ab0 'a' 'int'
 | `-CallExpr 0x4223bb0 <col:7, col:11> 'int'
 |   `-ImplicitCastExpr 0x4223b98 <col:7> 'int (*)()' <FunctionToPointerDecay>
 |     `-DeclRefExpr 0x4223b48 <col:7> 'int ()' Function 0x42238e0 'foo' 'int ()'
 `-ReturnStmt 0x4223c20 <line:9:3, col:10>
   `-IntegerLiteral 0x4223c00 <col:10> 'int' 0

a = 5 + foo(); dump:

`-CompoundStmt 0x4a9ec88 <line:6:12, line:10:1>
 |-DeclStmt 0x4a9eb08 <line:7:3, col:8>
 | `-VarDecl 0x4a9eab0 <col:3, col:7> a 'int'
 |-BinaryOperator 0x4a9ec20 <line:8:3, col:15> 'int' '='
 | |-DeclRefExpr 0x4a9eb20 <col:3> 'int' lvalue Var 0x4a9eab0 'a' 'int'
 | `-BinaryOperator 0x4a9ebf8 <col:7, col:15> 'int' '+'
 |   |-IntegerLiteral 0x4a9eb48 <col:7> 'int' 5
 |   `-CallExpr 0x4a9ebd0 <col:11, col:15> 'int'
 |     `-ImplicitCastExpr 0x4a9ebb8 <col:11> 'int (*)()' <FunctionToPointerDecay>
 |       `-DeclRefExpr 0x4a9eb68 <col:11> 'int ()' Function 0x4a9e8e0 'foo' 'int ()'
 `-ReturnStmt 0x4a9ec68 <line:9:3, col:10>
   `-IntegerLiteral 0x4a9ec48 <col:10> 'int' 0
Thanasis
  • 107
  • 5

0 Answers0