0

I m working on clang libtooling, I needed the left hand side of the assignment operation ,

So I used VisitBinaryOperator(BinaryOperator *B) to get the left hand side , I did some research on it and implemented in the following way


bool VisitBinaryOperator(BinaryOperator *B)
{
  if(B->isAssignmentOp())
{
Expr *E = B->getLHS();
  if(const clang::DeclRefExpr *lhs =  dyn_cast<clang::DeclRefExpr>(E))
  {
    cout<< "Count 1\n";
  }
}
    return true;
}


This is my sample program

#define abc ab
int ab[5];
int b[10];
int main()
{
b[0] = 0;
b[1] = b[0];
abc[1] = 0;
}

For this program VisitBinaryOperator function should go inside the if condition , as b[0],b[1],abc[1] are referred in the main function .

But control is not going inside only , and I m failing to debug it also .

Please Let me know the answer for this issue.

Jon marsh
  • 279
  • 7
  • 12
  • http://clang-developers.42468.n3.nabble.com/clang-3-8-libtooling-cannot-visit-some-BinaryOperator-td4054719.html – doptimusprime Oct 31 '19 at 05:06
  • @doptimusprime It didnt worked. when i give a integer variable like i = 10 , I can get the name of the variable. But when I give the array variable i[0] = 10, condition Itself is not being satisfied. – Jon marsh Oct 31 '19 at 05:36

1 Answers1

1

You did everything correctly and Clang did it as well. The problem here is that b[0] (and other LHSs as well) are not DeclRefExpr. b is a DeclRefExpr and b[0] is an ArraySubscriptExpr.

If you print out the AST sub-tree for the first assignment, here is what you'll get:

    |-BinaryOperator 0x5601f96e8a30 <line:5:3, col:10> 'int' lvalue '='
    | |-ArraySubscriptExpr 0x5601f96e89f0 <col:3, col:6> 'int' lvalue
    | | |-ImplicitCastExpr 0x5601f96e89d8 <col:3> 'int *' <ArrayToPointerDecay>
    | | | `-DeclRefExpr 0x5601f96e8968 <col:3> 'int [10]' lvalue Var 0x5601f96e87f0 'b' 'int [10]'
    | | `-IntegerLiteral 0x5601f96e8988 <col:5> 'int' 0
    | `-IntegerLiteral 0x5601f96e8a10 <col:10> 'int' 0

As the result, if you want to get DeclRefExpr you need either get there manually (through ArraySubscriptExpr and ImplicitCastExpr expressions) or by using RecursiveASTVisitor.

I hope this information is useful. Happy hacking with Clang!

Valeriy Savchenko
  • 1,524
  • 8
  • 19